~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
Merge branch 'dev' into feature/per-user-encrypted-databases
LearningCircuit0ffe51289769
diff --cc src/local_deep_research/config/llm_config.pyindex 3c5c25ccaa,fa26d71415..9342e73d47--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@@ -616,6 -617,16 +616,16 @@@ def wrap_llm_without_think_tags):"""Create a wrapper class that processes LLM outputs with remove_think_tags and token counting"""+ # First apply rate limiting if enabled++ from ..utilities.db_utils import get_db_setting+ from ..web_search_engines.rate_limiting.llm import (+ create_rate_limited_llm_wrapper,+ )- from ..utilities.db_utils import get_db_setting++ # Check if LLM rate limiting is enabled (independent of search rate limiting)+ if get_db_setting("rate_limiting.llm_enabled", False):+ llm = create_rate_limited_llm_wrapper(llm, provider)+# Import token counting functionality if research_id is providedcallbacks = []if research_id is not None:diff --cc src/local_deep_research/setup_data_dir.pyindex d321d3d794,e64da2e090..8952cb8e9a--- a/src/local_deep_research/setup_data_dir.py+++ b/src/local_deep_research/setup_data_dir.py@@@ -1,41 -1,31 +1,41 @@@#!/usr/bin/env python"""Data directory setup script for Local Deep Research.-Creates the data directory for the application database if it doesn't exist.+Creates the data directories using centralized path configuration.++NOTE: This script is largely deprecated as directories are now created+automatically when needed using the centralized path configuration."""-import osfrom loguru import logger+from .config.paths import (+ get_cache_directory,+ get_data_directory,+ get_database_path,+ get_logs_directory,+ get_research_outputs_directory,+)+def setup_data_dir():- """Set up the data directory for the application."""- # Get the project root directory (3 levels up from this file)- current_dir = os.path.dirname(os.path.abspath(__file__))- project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))+ """Set up all data directories for the application using centralized paths."""+ # Get all directories+ data_dir = get_data_directory()+ outputs_dir = get_research_outputs_directory()+ cache_dir = get_cache_directory()+ logs_dir = get_logs_directory()- # Define the data directory path- data_dir = os.path.join(project_root, "data")+ # Create directories if they don't exist+ for directory in [data_dir, outputs_dir, cache_dir, logs_dir]:+ directory.mkdir(parents=True, exist_ok=True)+ print(f"Ensured directory exists: {directory}")- # Create the data directory if it doesn't exist- if not os.path.exists(data_dir):- os.makedirs(data_dir)- logger.info(f"Created data directory at: {data_dir}")- else:- logger.info(f"Data directory already exists at: {data_dir}")+ # Log directory creation results+ logger.info(f"Data directories configured at: {data_dir}")-+- # Return the path to the data directory- return data_dir+ # Return the main data directory path+ return str(data_dir)if __name__ == "__main__":diff --cc src/local_deep_research/utilities/db_utils.pyindex 2815a8336d,2556e56a4f..b100d03dda--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@@ -1,84 -1,81 +1,118 @@@- from typing import Any, Dict-import os-from typing import Any, Dict, Callable+ import functools++from typing import Any, Callable, Dictfrom cachetools import LRUCache+from flask import g, session as flask_sessionfrom loguru import logger-from sqlalchemy import create_engine-from sqlalchemy.orm import Session, sessionmaker+from sqlalchemy.orm import Session-from ..utilities.threading_utils import thread_specific_cache+from ..config.paths import get_data_directory, get_database_path+from ..database.encrypted_db import db_managerfrom ..web.services.settings_manager import SettingsManager+from .threading_utils import thread_specific_cache-# Database path.-DATA_DIR = os.path.abspath(- os.path.join(os.path.dirname(__file__), "..", "..", "data")-)-DB_PATH = os.path.join(DATA_DIR, "ldr.db")+# Database paths using new centralized configuration+DATA_DIR = get_data_directory()+DB_PATH = get_database_path()@thread_specific_cache(cache=LRUCache(maxsize=10))- def get_db_session(_namespace: str = "", username: str | None = None) -> Session:-def get_db_session(_namespace: str = "") -> Session:++def get_db_session(++ _namespace: str = "", username: str | None = None++) -> Session:"""+ Get database session - uses encrypted per-user database if authenticated.+Args:_namespace: This can be specified to an arbitrary string in order to- force the caching mechanism to create separate settings even in- the same thread. Usually it does not need to be specified.+ force the caching mechanism to create separate settings even in+ the same thread. Usually it does not need to be specified.+ username: Optional username for thread context (e.g., background research threads).+ If not provided, will try to get from Flask context.Returns:- The singleton DB session for each thread.-+ The database session for the current user/context.+ """+ # If username is explicitly provided (e.g., from background thread)+ if username:+ user_session = db_manager.get_session(username)+ if user_session:+ return user_session+ raise RuntimeError(f"No database found for user {username}")++ # Otherwise, check Flask request context+ try:+ # Check if we have a database session in Flask's g object+ if hasattr(g, "db_session") and g.db_session:+ return g.db_session++ # Check if we have a username in the Flask session+ username = flask_session.get("username")+ if username:+ user_session = db_manager.get_session(username)+ if user_session:+ return user_session+ except RuntimeError:+ # Not in a Flask request context+ pass++ # No shared database - require authenticated user+ raise RuntimeError(+ "No authenticated user found. Database access requires authentication."+ )+++def get_settings_manager(username: str | None = None) -> SettingsManager:"""- engine = create_engine(f"sqlite:///{DB_PATH}")- session_class = sessionmaker(bind=engine)- return session_class()+ Get the settings manager for the current context.+ Args:+ username: Optional username for thread context (e.g., background research threads).-def get_settings_manager() -> SettingsManager:- """Returns:The singleton settings manager.-"""- return SettingsManager(db_session=get_db_session())+ try:- db_session = get_db_session(username)++ db_session = get_db_session(username=username)+ except RuntimeError:+ # No authenticated user - settings manager will use defaults+ db_session = None+ return SettingsManager(db_session=db_session)+ def no_db_settings(func: Callable[..., Any]) -> Callable[..., Any]:+ """+ Decorator that runs the wrapped function with the settings database+ completely disabled. This will prevent the function from accidentally+ reading settings from the DB. Settings can only be read from environment+ variables or the defaults file.++ Args:+ func: The function to wrap.++ Returns:+ The wrapped function.++ """++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ # Temporarily disable DB access in the settings manager.+ manager = get_settings_manager()+ db_session = manager.db_session+ manager.db_session = None++ try:+ return func(*args, **kwargs)+ finally:+ # Restore the original database session.+ manager.db_session = db_session++ return wrapper++def get_db_setting(- key: str, default_value: Any | None = None+ key: str, default_value: Any | None = None, username: str | None = None) -> str | Dict[str, Any] | None:"""Get a setting from the database with fallback to default value@@@ -94,7 -90,7 +128,9 @@@"""try:# Get settings manager which handles database access- return get_settings_manager(username).get_setting(key, default=default_value)- return get_settings_manager().get_setting(key, default=default_value)++ return get_settings_manager(username).get_setting(++ key, default=default_value++ )except Exception:logger.exception(f"Error getting setting {key} from database")diff --cc src/local_deep_research/web/app_factory.pyindex fdb96fa23a,55b68594df..12a1f0fe52--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@@ -317,12 -255,27 +317,7 @@@ def register_error_handlers(app)def create_database(app):"""- Create the database and tables for the application.+ DEPRECATED: Database creation is now handled per-user via encrypted_db.py+ This function is kept for compatibility but does nothing."""- from sqlalchemy import create_engine- from sqlalchemy.orm import scoped_session, sessionmaker-- # Configure SQLite to use URI mode, which allows for relative file paths- engine = create_engine(- app.config["SQLALCHEMY_DATABASE_URI"],- echo=app.config.get("SQLALCHEMY_ECHO", False),- connect_args={"check_same_thread": False},- )-- app.engine = engine-- # Configure session factory- session_factory = sessionmaker(- bind=engine, autocommit=False, autoflush=False- )- app.db_session = scoped_session(session_factory)-- # Add teardown context- @app.teardown_appcontext- def remove_session(exception=None):- app.db_session.remove()+ pass-- # Add teardown context- @app.teardown_appcontext- def remove_session(exception=None):- app.db_session.remove()diff --cc src/local_deep_research/web/routes/research_routes.pyindex a0156b9df5,d4b629b74c..a5bb251755--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@@ -9,26 -9,22 +9,29 @@@ from flask importjsonify,redirect,request,- send_from_directory,+ send_file,+ send_from_directory,+ session,url_for,)from loguru import logger-from ..models.database import (- calculate_duration,- get_db_connection,+from ...config.paths import get_research_outputs_directory+from ...database.encrypted_db import db_manager+from ...database.models import (+ QueuedResearch,+ ResearchHistory,+ ResearchLog,+ UserActiveResearch,)+from ...utilities.db_utils import get_db_session+from ..auth.decorators import login_required+from ..models.database import calculate_durationfrom ..services.research_service import (++ OUTPUT_DIR,++ export_report_to_format,run_research_process,start_research_process,- export_report_to_format,- OUTPUT_DIR,)from ..utils.templates import render_template_with_defaultsfrom .globals import active_research, termination_flags@@@ -902,24 -737,91 +905,84 @@@ def get_research_report(research_id)session.close()+ @research_bp.route(+ "/api/v1/research/<research_id>/export/<format>", methods=["POST"]+ )++@login_required+ def export_research_report(research_id, format):+ """Export research report to different formats (LaTeX or Quarto)"""+ try:+ if format not in ["latex", "quarto", "ris"]:+ return jsonify(+ {"error": "Invalid format. Use 'latex', 'quarto', or 'ris'"}+ ), 400++ # Get research from database+ session = get_db_session()+ try:+ research = (+ session.query(ResearchHistory).filter_by(id=research_id).first()+ )+ if not research:+ return jsonify({"error": "Research not found"}), 404++ # Get the report path+ if not research.report_path:+ return jsonify(+ {"error": "Report path not found in database"}+ ), 404++ report_path = OUTPUT_DIR / research.report_path+ if not report_path.exists():+ return jsonify({"error": "Report file not found"}), 404++ # Export to requested format+ try:+ export_path = export_report_to_format(report_path, format)++ # Send the file+ return send_file(+ export_path,+ as_attachment=True,+ download_name=export_path.name,+ mimetype="text/plain"+ if format == "latex"+ else "text/markdown",+ )+ except Exception as e:- logger.exception(f"Error exporting report: {str(e)}")++ logger.exception(f"Error exporting report: {e!s}")+ return jsonify(+ {+ "error": f"Failed to export to {format}. Please try again later."+ }+ ), 500++ finally:+ session.close()++ except Exception as e:- logger.exception(f"Error in export endpoint: {str(e)}")++ logger.exception(f"Error in export endpoint: {e!s}")+ return jsonify({"error": "An internal error has occurred"}), 500++-@research_bp.route("/api/research/<research_id>/status")+@research_bp.route("/api/research/<string:research_id>/status")+@login_requireddef get_research_status(research_id):"""Get the status of a research process"""- conn = get_db_connection()- cursor = conn.cursor()- cursor.execute(- "SELECT status, progress, completed_at, report_path, research_meta FROM research_history WHERE id = ?",- (research_id,),+ db_session = get_db_session()+ research = (+ db_session.query(ResearchHistory).filter_by(id=research_id).first())- result = cursor.fetchone()- if result is None:- conn.close()+ if research is None:+ db_session.close()return jsonify({"error": "Research not found"}), 404- status, progress, completed_at, report_path, metadata_str = result-- # Parse metadata if it exists- metadata = {}- if metadata_str:- try:- metadata = json.loads(metadata_str)- except json.JSONDecodeError:- current_app.logger.warning(- f"Invalid JSON in metadata for research {research_id}"- )+ status = research.status+ progress = research.progress+ completed_at = research.completed_at+ report_path = research.report_path+ metadata = research.research_meta or {}# Extract and format error information for better UI displayerror_info = {}diff --cc src/local_deep_research/web/routes/settings_routes.pyindex 66b1adbae1,47c3725368..eac066485b--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@@ -16,16 -16,13 +16,15 @@@ from flask importfrom flask_wtf.csrf import generate_csrffrom loguru import logger+from ...config.paths import get_data_directory, get_database_path+from ...database.models import Setting, SettingTypefrom ...utilities.db_utils import (-- get_db_setting,get_db_session,++ get_db_setting,get_settings_manager,)from ...utilities.url_utils import normalize_url-from ..database.models import Setting, SettingType+from ..auth.decorators import login_required- from ..services.settings_manager import SettingsManagerfrom ..services.settings_service import (create_or_update_setting,set_setting,@@@ -455,8 -450,7 +454,8 @@@ def save_all_settings())- @settings_bp.route("/reset_to_defaults", methods=["GET"])+ @settings_bp.route("/reset_to_defaults", methods=["POST"])+@login_requireddef reset_to_defaults():"""Reset all settings to their default values"""db_session = get_db_session()@@@ -1284,7 -1269,7 +1283,7 @@@ def api_get_available_models()from datetime import datetime# Clear old cache entries for providers we're updating-- for provider_key in providers.keys():++ for provider_key in providers:provider_name = provider_key.replace("_models", "").upper()diff --cc src/local_deep_research/web/services/research_service.pyindex 0144ab8fe5,1a2ab06b9c..1c4d656420--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@@ -15,17 -11,97 +16,92 @@@ from ...error_handling.report_generatofrom ...metrics.search_tracker import set_search_contextfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystem- from ...utilities.db_utils import get_db_session++from ...text_optimization import CitationFormatter, CitationMode++from ...utilities.db_utils import get_db_session, get_db_settingfrom ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_results-from ...utilities.db_utils import get_db_sessionfrom ...utilities.threading_utils import thread_context, thread_with_app_context-from ..database.models import ResearchStrategy, ResearchHistoryfrom ..models.database import calculate_durationfrom .socket_service import SocketIOService-from ...error_handling.report_generator import ErrorReportGenerator-from ...text_optimization import CitationFormatter, CitationMode-from ...utilities.db_utils import get_db_setting-# Output directory for research results-_PROJECT_ROOT = Path(__file__).parents[4]-OUTPUT_DIR = _PROJECT_ROOT / "research_outputs"+OUTPUT_DIR = get_research_outputs_directory()+ def get_citation_formatter():+ """Get citation formatter with settings from database."""+ citation_format = get_db_setting(+ "report.citation_format", "domain_id_hyperlinks"+ )+ mode_map = {+ "number_hyperlinks": CitationMode.NUMBER_HYPERLINKS,+ "domain_hyperlinks": CitationMode.DOMAIN_HYPERLINKS,+ "domain_id_hyperlinks": CitationMode.DOMAIN_ID_HYPERLINKS,+ "domain_id_always_hyperlinks": CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS,+ "no_hyperlinks": CitationMode.NO_HYPERLINKS,+ }+ mode = mode_map.get(citation_format, CitationMode.DOMAIN_ID_HYPERLINKS)+ return CitationFormatter(mode=mode)+++ def export_report_to_format(report_path: Path, format: str, title: str = None):+ """+ Export a markdown report to different formats.++ Args:+ report_path: Path to the markdown report file+ format: Export format ('latex' or 'quarto')+ title: Optional title for the document++ Returns:+ Path to the generated file+ """+ # Read the markdown content+ with report_path.open("r", encoding="utf-8") as f:+ markdown_content = f.read()++ if format == "latex":+ from ...text_optimization.citation_formatter import LaTeXExporter++ exporter = LaTeXExporter()+ exported_content = exporter.export_to_latex(markdown_content)+ export_path = report_path.with_suffix(".tex")+ elif format == "quarto":+ from ...text_optimization.citation_formatter import QuartoExporter++ exporter = QuartoExporter()+ # Extract title from markdown if not provided+ if not title:+ title_match = re.search(+ r"^#\s+(.+)$", markdown_content, re.MULTILINE+ )+ title = title_match.group(1) if title_match else "Research Report"+ exported_content = exporter.export_to_quarto(markdown_content, title)+ export_path = report_path.with_suffix(".qmd")++ # Also save the bibliography file for Quarto+ bib_content = exporter._generate_bibliography(markdown_content)+ bib_path = report_path.parent / "references.bib"+ with bib_path.open("w", encoding="utf-8") as f:+ f.write(bib_content)+ logger.info(f"Created bibliography file: {bib_path}")+ elif format == "ris":+ from ...text_optimization.citation_formatter import RISExporter++ exporter = RISExporter()+ exported_content = exporter.export_to_ris(markdown_content)+ export_path = report_path.with_suffix(".ris")+ else:+ raise ValueError(f"Unsupported export format: {format}")++ # Save exported file+ with export_path.open("w", encoding="utf-8") as f:+ f.write(exported_content)++ logger.info(f"Exported report to {format}: {export_path}")+ return export_path++-def save_research_strategy(research_id, strategy_name):+def save_research_strategy(research_id, strategy_name, username=None):"""Save the strategy used for a research to the database.diff --cc src/local_deep_research/web/services/settings_manager.pyindex c55814c541,2d67c0c081..963506a65d--- a/src/local_deep_research/web/services/settings_manager.py+++ b/src/local_deep_research/web/services/settings_manager.py@@@ -1,7 -1,7 +1,7 @@@import importlib.resources as pkg_resourcesimport jsonimport os- from typing import Any, Dict, Optional, Type, Union-from typing import Any, Dict, Optional, Type, Union, List++from typing import Any, Dict, List, Optional, Type, Unionfrom loguru import loggerfrom sqlalchemy import func, or_@@@ -66,6 -66,6 +66,11 @@@ class SettingsManagerself.db_session = db_sessionself.db_first = True # Always prioritize DB settings++ # Check if we should lock all the settings.++ self.__settings_locked = self.get_setting("app.lock_settings", False)++ if self.__settings_locked:++ logger.info("Settings are locked. Disabling all settings changes.")++@propertydef default_settings(self) -> Dict[str, Any]:"""diff --cc tests/rate_limiting/test_rate_limiting.pyindex 71c03aeee6,2cd902ba8c..241f29ebc4--- a/tests/rate_limiting/test_rate_limiting.py+++ b/tests/rate_limiting/test_rate_limiting.py@@@ -7,9 -7,9 +7,7 @@@ import unittesfrom unittest.mock import patchimport pytest- from sqlalchemy import create_engine- from src.local_deep_research.utilities.db_utils import DB_PATH-from sqlalchemy import create_engine-from src.local_deep_research.web_search_engines.rate_limiting import (AdaptiveRateLimitTracker,RateLimitError,diff --cc tests/test_settings_manager.pyindex 3e250da953,6e7b38129b..ea5d99573b--- a/tests/test_settings_manager.py+++ b/tests/test_settings_manager.py@@@ -1,380 -1,574 +1,380 @@@-import os-from typing import Any--import pytest-from sqlalchemy.exc import SQLAlchemyError--from src.local_deep_research.web.services.settings_manager import (- Setting,- SettingsManager,- SettingType,- check_env_setting,-)-from src.local_deep_research.utilities.db_utils import get_db_setting---def test_check_env_setting_exists(monkeypatch):- monkeypatch.setenv("LDR_APP_VERSION", "1.0.0")- assert check_env_setting("app.version") == "1.0.0"---def test_check_env_setting_not_exists():- # Ensure the environment variable is not set- if "LDR_APP_VERSION" in os.environ:- del os.environ["LDR_APP_VERSION"]- assert check_env_setting("app.version") is None--- "ui_element, setting_value, expected",- [- ("text", "hello", "hello"),- ("select", "option_a", "option_a"),- ("password", "secret", "secret"),- ("number", "3.14", 3.14),- ("range", "3.14", 3.14),- ("checkbox", "true", True),- ("json", {"key": "value"}, {"key": "value"}),- ],-)-def test_get_setting_from_db(- mocker, ui_element: str, setting_value: str, expected: Any-):- """- Tests that we can successfully read settings from the DB.-- Args:- mocker: The fixture to use for mocking.- ui_element: The value of the `ui_element` parameter, which controls the return type.- setting_value: The value to use for the setting in the DB.- expected: The expected typed value of the setting.- """- # Arrange: Set up the mock database session and a sample setting- mock_db_session = mocker.MagicMock()- mock_setting = Setting(- key="test.setting", value=setting_value, ui_element=ui_element- )- mock_db_session.query.return_value.filter.return_value.all.return_value = [- mock_setting- ]-- # Act: Call the get_setting method with the test key- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.get_setting("test.setting")-- # Assert: Verify that the result matches the expected value- assert result == expected, f"Expected {expected}, but got {result}"--- "ui_element, env_value, expected",- [- ("text", "hello", "hello"),- ("select", "option_a", "option_a"),- ("password", "secret", "secret"),- ("number", "3.14", 3.14),- ("range", "3.14", 3.14),- ("checkbox", "true", True),- ],-)-def test_get_setting_from_env(- mocker, monkeypatch, ui_element: str, env_value: str, expected: Any-):- """- Tests that we can successfully override DB settings with environment- variables.-- Args:- mocker: The fixture to use for mocking.- ui_element: The value of the `ui_element` parameter, which controls the return type.- env_value: The value to use for the setting in the environment variable.- expected: The expected typed value of the setting.- """- # Arrange: Set up the mock database session and ensure an environment variable is set- mock_db_session = mocker.MagicMock()- monkeypatch.setenv("LDR_TEST_SETTING", env_value)- # Ensure DB query returns an old version to verify environment variable is prioritized- mock_setting = Setting(- key="test.setting", value="db_value", ui_element=ui_element- )- mock_db_session.query.return_value.filter.return_value.all.return_value = [- mock_setting- ]-- # Act: Call the get_setting method with the test key- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.get_setting("test.setting")-- # Assert: Verify that the result matches the expected value- assert result == expected, f"Expected {expected}, but got {result}"---def test_get_setting_default(mocker):- mock_db_session = mocker.MagicMock()- # Ensure DB query returns nothing- mock_db_session.query.return_value.filter.return_value.all.return_value = []-- settings_manager = SettingsManager(db_session=mock_db_session)- assert (- settings_manager.get_setting(- "non_existent_setting", default="default_value"- )- == "default_value"- )---def test_get_setting_no_db(mocker, monkeypatch):- """- Tests that it correctly reads a setting from the defaults file when no- database is provided.-- Args:- mocker: The fixture to use for mocking.- monkeypatch: The fixture to use for patching.-- """- # Arrange- # Set up the mock defaults file- mock_defaults = {- "test.setting": {- "category": "app_interface",- "description": "Enable debug mode for the web application",- "editable": True,- "max_value": None,- "min_value": None,- "name": "Test Setting",- "options": None,- "step": None,- "type": SettingType.APP,- "ui_element": "text",- "value": "default_value",- "visible": True,- }- }- mocker.patch(- "src.local_deep_research.web.services.settings_manager.json.loads",- return_value=mock_defaults,- )-- # Act: Call the get_setting method with the test key- settings_manager = SettingsManager(db_session=None)- result = settings_manager.get_setting("test.setting")-- # Assert: Verify that the result matches the expected value- assert result == "default_value", (- f"Expected 'default_value', but got {result}"- )---def test_get_setting_invalid_type(mocker):- """- Tests that when a setting's value cannot be converted to the type- specified by the `ui_element`, it will always return the default value.-- Args:- mocker: The fixture to use for mocking.-- """- # Arrange: Set up a mock DB session and setting with an invalid type- mock_db_session = mocker.MagicMock()- mock_setting = Setting(- key="test.invalid_type", value="not_a_number", ui_element="number"- )- mock_db_session.query.return_value.filter.return_value.all.return_value = [- mock_setting- ]-- # Act: Call get_setting with a default value and an invalid type- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.get_setting("test.invalid_type", default=10)-- # Assert: Check that the default value is returned and not the invalid string- assert result == 10---# The mocker fixture is automatically available-def test_set_setting_update_existing(mocker):- mock_db_session = mocker.MagicMock()- mock_setting = Setting(key="app.version", value="1.0.0", editable=True)- mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting- mocker.patch(- "src.local_deep_research.web.services.settings_manager.func.now"- ) # Patching the func.now call-- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.set_setting("app.version", "2.0.0")-- assert result is True- assert mock_setting.value == "2.0.0"- mock_db_session.commit.assert_called_once()- mock_db_session.rollback.assert_not_called()---def test_set_setting_update_non_editable(mocker):- """- Tests that `set_setting` returns False and the setting is not updated- when that setting is marked as non-editable.-- Args:- mocker: The fixture to use for mocking.-- """- mock_db_session = mocker.MagicMock()- mock_setting = Setting(- key="app.version", value="1.0.0", editable=False, ui_element="text"- )- mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting-- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.set_setting("app.version", "2.0.0")-- assert result is False- assert mock_setting.value == "1.0.0"- mock_db_session.commit.assert_not_called()- mock_db_session.rollback.assert_not_called()--- "lock_settings_via_env", [True, False], ids=("lock_via_env", "lock_via_db")-)-def test_set_setting_locked(mocker, monkeypatch, lock_settings_via_env: bool):- """- Tests that `set_setting` returns False and the setting is not updated- when the settings are locked by setting `app.lock_settings` to True.-- Args:- mocker: The fixture to use for mocking.- monkeypatch: The fixture to use for patching.- lock_settings_via_env: Whether to lock settings via the environment variable.-- """- mock_db_session = mocker.MagicMock()- mock_setting = Setting(- key="app.version", value="1.0.0", editable=True, ui_element="text"- )- mock_lock_setting = Setting(- key="app.lock_settings",- # We need the setting in the DB regardless so it can get the type.- value=not lock_settings_via_env,- editable=True,- ui_element="checkbox",- )- mock_db_session.query.return_value.filter.return_value.all.return_value = [- mock_lock_setting- ]- mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting-- mocker.patch(- "src.local_deep_research.web.services.settings_manager.func.now"- ) # Patching the func.now call-- if lock_settings_via_env:- monkeypatch.setenv("LDR_APP_LOCK_SETTINGS", "1")-- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.set_setting("app.version", "2.0.0")-- assert result is False- assert mock_setting.value == "1.0.0"- mock_db_session.commit.assert_not_called()- mock_db_session.rollback.assert_not_called()---def test_set_setting_create_new(mocker):- mock_db_session = mocker.MagicMock()- mock_db_session.query.return_value.filter.return_value.first.return_value = None- mocker.patch(- "src.local_deep_research.web.services.settings_manager.func.now"- ) # Patching the func.now call-- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.set_setting("new.setting", "new_value")-- assert result is True- mock_db_session.add.assert_called_once()- new_setting = mock_db_session.add.call_args[0][0]- assert isinstance(new_setting, Setting)- assert new_setting.key == "new.setting"- assert new_setting.value == "new_value"- assert (- new_setting.type == SettingType.APP- ) # Assuming 'app' type for this key- mock_db_session.commit.assert_called_once()- mock_db_session.rollback.assert_not_called()---def test_set_setting_db_error(mocker):- mock_db_session = mocker.MagicMock()- # Set the side_effect to an instance of SQLAlchemyError- mock_db_session.query.return_value.filter.return_value.first.side_effect = (- SQLAlchemyError("Simulated DB Error")- )-- # Mock the logger to check if error is logged- mock_logger = mocker.patch(- "src.local_deep_research.web.services.settings_manager.logger"- )-- settings_manager = SettingsManager(db_session=mock_db_session)- result = settings_manager.set_setting("app.version", "2.0.0")-- # Assert that the method returned False- assert result is False-- mock_db_session.rollback.assert_called_once()- mock_db_session.commit.assert_not_called()- mock_logger.error.assert_called_once()- # mock_logger.error.assert_called_once_with("Error setting value for app.version: Simulated DB Error")---def test_app_get_setting_from_real_db(- setup_database_for_all_tests, monkeypatch-):- """- Tests get_setting via settings_service, using the real file-based database.- `setup_database_for_all_tests` yields `SessionLocal`, which is a sessionmaker.- """- SessionLocal = setup_database_for_all_tests # Get the SessionLocal class from the fixture- session = SessionLocal() # Create a new session instance for this test-- # Add a setting to the database using this session- # Changed key to be specific to this test- setting = Setting(- key="test.app.version.get", # Use a unique key for this test- value="1.0.0",- type=SettingType.APP,- name="Version",- description="App version",- ui_element="text",- visible=True,- editable=True,- )- session.add(setting)- session.commit()-- monkeypatch.delenv(- "LDR_APP_VERSION", raising=False- ) # Ensure no env override-- # Check that the value was saved.- value = get_db_setting("test.app.version.get")- assert value == "1.0.0"-- session.close() # Close the session for this test--- "lock_settings, expected_editable",- [(True, False), (False, True)],- ids=["lock_settings", "no_lock_settings"],-)-def test_get_all_settings_from_real_file_db(- setup_database_for_all_tests,- monkeypatch,- lock_settings: bool,- expected_editable: bool,-):- """- Tests retrieving all settings from a real *file-based* database.- """- # Create a new session for this test- session = (- setup_database_for_all_tests()- ) # Call the sessionmaker to get a new session-- # Add some settings to the database- setting1 = Setting(- key="all.settings.app.version",- value="1.0.0",- type=SettingType.APP,- name="Version",- description="App version",- ui_element="text",- visible=True,- editable=True,- )- setting2 = Setting(- key="all.settings.llm.temperature",- value=0.7,- type=SettingType.LLM,- name="Temperature",- description="LLM temperature",- ui_element="number",- visible=True,- editable=True,- )- session.add_all([setting1, setting2])-- # Modify the app.lock_settings setting- lock_setting = (- session.query(Setting)- .filter(Setting.key == "app.lock_settings")- .first()- )- assert lock_setting is not None- lock_setting.value = lock_settings-- session.commit() # Commit to save them to the database-- # Ensure no conflicting environment variables are set for this test- monkeypatch.delenv("LDR_APP_VERSION", raising=False)- monkeypatch.delenv("LDR_LLM_TEMPERATURE", raising=False)-- settings_manager = SettingsManager(- db_session=session- ) # Pass the session instance- all_settings = settings_manager.get_all_settings()-- # Assertions should check for the unique keys- assert "all.settings.app.version" in all_settings- assert all_settings["all.settings.app.version"]["value"] == "1.0.0"- assert all_settings["all.settings.app.version"]["type"] == "APP"- assert (- all_settings["all.settings.app.version"]["editable"]- is expected_editable- )- assert all_settings["all.settings.app.version"]["name"] == "Version"-- assert "all.settings.llm.temperature" in all_settings- assert all_settings["all.settings.llm.temperature"]["value"] == 0.7- assert all_settings["all.settings.llm.temperature"]["type"] == "LLM"- assert (- all_settings["all.settings.llm.temperature"]["editable"]- is expected_editable- )- assert all_settings["all.settings.llm.temperature"]["name"] == "Temperature"-- # IMPORTANT: Close the session created within the test- session.close()---def test_get_all_settings_from_defaults_file(mocker):- """- Tests that it can read all the settings from the defaults file if no- database is provided to the settings manager.-- Args:- mocker: The fixture to use for mocking.-- """- # Arrange- # Set up the mock defaults file- mock_defaults = {- "test.setting1": {- "category": "app_interface",- "description": "Test setting 1",- "editable": True,- "max_value": None,- "min_value": None,- "name": "Test Setting 1",- "options": None,- "step": None,- "type": SettingType.APP,- "ui_element": "text",- "value": "default_value1",- "visible": True,- },- "test.setting2": {- "category": "app_interface",- "description": "Test setting 2",- "editable": True,- "max_value": None,- "min_value": None,- "name": "Test Setting 2",- "options": None,- "step": None,- "type": SettingType.APP,- "ui_element": "text",- "value": "default_value2",- "visible": True,- },- }- mocker.patch(- "src.local_deep_research.web.services.settings_manager.json.loads",- return_value=mock_defaults,- )-- # Act: Call the get_all_settings method- settings_manager = SettingsManager(db_session=None)- all_settings = settings_manager.get_all_settings()-- # Assert: Verify that the result matches the expected values- for key, setting in mock_defaults.items():- # It just gives us the names of the types instead of the enum.- setting["type"] = setting["type"].name- assert all_settings == mock_defaults---def test_get_all_settings_db_error(mock_db_session, mock_logger):- """Tests handling a SQLAlchemyError when retrieving all settings."""- # Configure the mock session to raise a SQLAlchemyError- mock_db_session.query(Setting).all.side_effect = SQLAlchemyError(- "Simulated DB Error"- )-- settings_manager = SettingsManager(db_session=mock_db_session)- all_settings = settings_manager.get_all_settings()-- # Assert that an empty dictionary is returned and the error was logged- assert all_settings == {}- mock_db_session.query(Setting).all.assert_called_once()- mock_logger.error.assert_called_once()- # You can check the log message content if needed---def test_get_setting_with_substring_keys(setup_database_for_all_tests):- """- Tests that we can get the correct value for a setting, even when its key- is a substring of the key for a different setting.-- Args:- setup_database_for_all_tests: Fixture that sets up a real database- for testing. (This is necessary because the bug fix this is- testing depends on the actual behavior of the SQLAlchemy `filter()`- function.)-- """- # Arrange.- session_local_class = setup_database_for_all_tests- session = session_local_class()-- with session:- # Add two settings with overlapping keys but different full keys- setting1 = Setting(- key="test.hello",- value="world",- ui_element="text",- type="APP",- name="Test Setting 1",- visible=True,- editable=True,- )- setting2 = Setting(- key="test.hello_world",- value="universe",- ui_element="text",- type="APP",- name="Test Setting 2",- visible=True,- editable=True,- )- session.add(setting1)- session.add(setting2)- session.commit()-- settings_manager = SettingsManager(db_session=session)-- # Act and assert.- # Test getting the "test.hello" setting- result1 = settings_manager.get_setting("test.hello")- assert result1 == "world"-- # Test getting the "test.hello_world" setting.- result2 = settings_manager.get_setting("test.hello_world")- assert result2 == "universe"+import os+from typing import Any++import pytest+from sqlalchemy.exc import SQLAlchemyError++from src.local_deep_research.web.services.settings_manager import (+ Setting,+ SettingsManager,+ SettingType,+ check_env_setting,+)- from src.local_deep_research.utilities.db_utils import get_db_setting+++def test_check_env_setting_exists(monkeypatch):+ monkeypatch.setenv("LDR_APP_VERSION", "1.0.0")+ assert check_env_setting("app.version") == "1.0.0"+++def test_check_env_setting_not_exists():+ # Ensure the environment variable is not set+ if "LDR_APP_VERSION" in os.environ:+ del os.environ["LDR_APP_VERSION"]+ assert check_env_setting("app.version") is None+++ "ui_element, setting_value, expected",+ [+ ("text", "hello", "hello"),+ ("select", "option_a", "option_a"),+ ("password", "secret", "secret"),+ ("number", "3.14", 3.14),+ ("range", "3.14", 3.14),+ ("checkbox", "true", True),+ ("json", {"key": "value"}, {"key": "value"}),+ ],+)+def test_get_setting_from_db(+ mocker, ui_element: str, setting_value: str, expected: Any+):+ """+ Tests that we can successfully read settings from the DB.++ Args:+ mocker: The fixture to use for mocking.+ ui_element: The value of the `ui_element` parameter, which controls the return type.+ setting_value: The value to use for the setting in the DB.+ expected: The expected typed value of the setting.+ """+ # Arrange: Set up the mock database session and a sample setting+ mock_db_session = mocker.MagicMock()+ mock_setting = Setting(+ key="test.setting", value=setting_value, ui_element=ui_element+ )+ mock_db_session.query.return_value.filter.return_value.all.return_value = [+ mock_setting+ ]++ # Act: Call the get_setting method with the test key+ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.get_setting("test.setting")++ # Assert: Verify that the result matches the expected value+ assert result == expected, f"Expected {expected}, but got {result}"+++ "ui_element, env_value, expected",+ [+ ("text", "hello", "hello"),+ ("select", "option_a", "option_a"),+ ("password", "secret", "secret"),+ ("number", "3.14", 3.14),+ ("range", "3.14", 3.14),+ ("checkbox", "true", True),+ ],+)+def test_get_setting_from_env(+ mocker, monkeypatch, ui_element: str, env_value: str, expected: Any+):+ """+ Tests that we can successfully override DB settings with environment+ variables.++ Args:+ mocker: The fixture to use for mocking.+ ui_element: The value of the `ui_element` parameter, which controls the return type.+ env_value: The value to use for the setting in the environment variable.+ expected: The expected typed value of the setting.+ """+ # Arrange: Set up the mock database session and ensure an environment variable is set+ mock_db_session = mocker.MagicMock()+ monkeypatch.setenv("LDR_TEST_SETTING", env_value)+ # Ensure DB query returns an old version to verify environment variable is prioritized+ mock_setting = Setting(+ key="test.setting", value="db_value", ui_element=ui_element+ )+ mock_db_session.query.return_value.filter.return_value.all.return_value = [+ mock_setting+ ]++ # Act: Call the get_setting method with the test key+ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.get_setting("test.setting")++ # Assert: Verify that the result matches the expected value+ assert result == expected, f"Expected {expected}, but got {result}"+++def test_get_setting_default(mocker):+ mock_db_session = mocker.MagicMock()+ # Ensure DB query returns nothing+ mock_db_session.query.return_value.filter.return_value.all.return_value = []++ settings_manager = SettingsManager(db_session=mock_db_session)+ assert (+ settings_manager.get_setting(+ "non_existent_setting", default="default_value"+ )+ == "default_value"+ )+++def test_get_setting_invalid_type(mocker):+ """+ Tests that when a setting's value cannot be converted to the type+ specified by the `ui_element`, it will always return the default value.++ Args:+ mocker: The fixture to use for mocking.++ """+ # Arrange: Set up a mock DB session and setting with an invalid type+ mock_db_session = mocker.MagicMock()+ mock_setting = Setting(+ key="test.invalid_type", value="not_a_number", ui_element="number"+ )+ mock_db_session.query.return_value.filter.return_value.all.return_value = [+ mock_setting+ ]++ # Act: Call get_setting with a default value and an invalid type+ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.get_setting("test.invalid_type", default=10)++ # Assert: Check that the default value is returned and not the invalid string+ assert result == 10+++# The mocker fixture is automatically available+def test_set_setting_update_existing(mocker):+ mock_db_session = mocker.MagicMock()+ mock_setting = Setting(key="app.version", value="1.0.0")+ mock_db_session.query.return_value.filter.return_value.first.return_value = mock_setting+ mocker.patch(+ "src.local_deep_research.web.services.settings_manager.func.now"+ ) # Patching the func.now call++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("app.version", "2.0.0")++ assert result is True+ assert mock_setting.value == "2.0.0"+ mock_db_session.commit.assert_called_once()+ mock_db_session.rollback.assert_not_called()+++def test_set_setting_create_new(mocker):+ mock_db_session = mocker.MagicMock()+ mock_db_session.query.return_value.filter.return_value.first.return_value = None+ mocker.patch(+ "src.local_deep_research.web.services.settings_manager.func.now"+ ) # Patching the func.now call++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("new.setting", "new_value")++ assert result is True+ mock_db_session.add.assert_called_once()+ new_setting = mock_db_session.add.call_args[0][0]+ assert isinstance(new_setting, Setting)+ assert new_setting.key == "new.setting"+ assert new_setting.value == "new_value"+ assert (+ new_setting.type == SettingType.APP+ ) # Assuming 'app' type for this key+ mock_db_session.commit.assert_called_once()+ mock_db_session.rollback.assert_not_called()+++def test_set_setting_db_error(mocker):+ mock_db_session = mocker.MagicMock()+ # Set the side_effect to an instance of SQLAlchemyError+ mock_db_session.query.return_value.filter.return_value.first.side_effect = (+ SQLAlchemyError("Simulated DB Error")+ )++ # Mock the logger to check if error is logged+ mock_logger = mocker.patch(+ "src.local_deep_research.web.services.settings_manager.logger"+ )++ settings_manager = SettingsManager(db_session=mock_db_session)+ result = settings_manager.set_setting("app.version", "2.0.0")++ # Assert that the method returned False+ assert result is False++ mock_db_session.rollback.assert_called_once()+ mock_db_session.commit.assert_not_called()+ mock_logger.error.assert_called_once()+ # mock_logger.error.assert_called_once_with("Error setting value for app.version: Simulated DB Error")+++def test_app_get_setting_from_real_db(+ setup_database_for_all_tests, monkeypatch+):+ """+ Tests get_setting via settings_service, using the real file-based database.+ `setup_database_for_all_tests` yields `SessionLocal`, which is a sessionmaker.+ """+ SessionLocal = setup_database_for_all_tests # Get the SessionLocal class from the fixture+ session = SessionLocal() # Create a new session instance for this test++ # Add a setting to the database using this session+ # Changed key to be specific to this test+ setting = Setting(+ key="test.app.version.get", # Use a unique key for this test+ value="1.0.0",+ type=SettingType.APP,+ name="Version",+ description="App version",+ ui_element="text",+ visible=True,+ editable=True,+ )+ session.add(setting)+ session.commit()++ monkeypatch.delenv(+ "LDR_APP_VERSION", raising=False+ ) # Ensure no env override+- # Call the get_setting function from settings_service- value = get_app_setting("test.app.version.get", db_session=session)++ # Create settings manager with the session and get the setting++ settings_manager = SettingsManager(db_session=session)++ value = settings_manager.get_setting("test.app.version.get")+ assert value == "1.0.0"++ session.close() # Close the session for this test+++def test_get_all_settings_from_real_file_db(+ setup_database_for_all_tests, monkeypatch+):+ """+ Tests retrieving all settings from a real *file-based* database.+ """+ # Create a new session for this test+ session = (+ setup_database_for_all_tests()+ ) # Call the sessionmaker to get a new session++ # Add some settings to the database+ setting1 = Setting(+ key="all.settings.app.version",+ value="1.0.0",+ type=SettingType.APP,+ name="Version",+ description="App version",+ ui_element="text",+ visible=True,+ editable=True,+ )+ setting2 = Setting(+ key="all.settings.llm.temperature",+ value=0.7,+ type=SettingType.LLM,+ name="Temperature",+ description="LLM temperature",+ ui_element="number",+ visible=True,+ editable=True,+ )+ session.add_all([setting1, setting2])+ session.commit() # Commit to save them to the database++ # Ensure no conflicting environment variables are set for this test+ monkeypatch.delenv("LDR_APP_VERSION", raising=False)+ monkeypatch.delenv("LDR_LLM_TEMPERATURE", raising=False)++ settings_manager = SettingsManager(+ db_session=session+ ) # Pass the session instance+ all_settings = settings_manager.get_all_settings()++ # Assertions should check for the unique keys+ assert "all.settings.app.version" in all_settings+ assert all_settings["all.settings.app.version"]["value"] == "1.0.0"+ assert all_settings["all.settings.app.version"]["type"] == "APP"+ assert all_settings["all.settings.app.version"]["editable"] is True+ assert all_settings["all.settings.app.version"]["name"] == "Version"++ assert "all.settings.llm.temperature" in all_settings+ assert all_settings["all.settings.llm.temperature"]["value"] == 0.7+ assert all_settings["all.settings.llm.temperature"]["type"] == "LLM"+ assert all_settings["all.settings.llm.temperature"]["editable"] is True+ assert all_settings["all.settings.llm.temperature"]["name"] == "Temperature"++ # IMPORTANT: Close the session created within the test+ session.close()+++def test_get_all_settings_db_error(mock_db_session, mock_logger):+ """Tests handling a SQLAlchemyError when retrieving all settings."""+ # Configure the mock session to raise a SQLAlchemyError+ mock_db_session.query(Setting).all.side_effect = SQLAlchemyError(+ "Simulated DB Error"+ )++ settings_manager = SettingsManager(db_session=mock_db_session)+ all_settings = settings_manager.get_all_settings()++ # Assert that an empty dictionary is returned and the error was logged+ assert all_settings == {}+ mock_db_session.query(Setting).all.assert_called_once()+ mock_logger.error.assert_called_once()+ # You can check the log message content if needed+++def test_get_setting_with_substring_keys(setup_database_for_all_tests):+ """+ Tests that we can get the correct value for a setting, even when its key+ is a substring of the key for a different setting.++ Args:+ setup_database_for_all_tests: Fixture that sets up a real database+ for testing. (This is necessary because the bug fix this is+ testing depends on the actual behavior of the SQLAlchemy `filter()`+ function.)++ """+ # Arrange.+ session_local_class = setup_database_for_all_tests+ session = session_local_class()++ with session:+ # Add two settings with overlapping keys but different full keys+ setting1 = Setting(+ key="test.hello",+ value="world",+ ui_element="text",+ type="APP",+ name="Test Setting 1",+ visible=True,+ editable=True,+ )+ setting2 = Setting(+ key="test.hello_world",+ value="universe",+ ui_element="text",+ type="APP",+ name="Test Setting 2",+ visible=True,+ editable=True,+ )+ session.add(setting1)+ session.add(setting2)+ session.commit()++ settings_manager = SettingsManager(db_session=session)++ # Act and assert.+ # Test getting the "test.hello" setting+ result1 = settings_manager.get_setting("test.hello")+ assert result1 == "world"++ # Test getting the "test.hello_world" setting.+ result2 = settings_manager.get_setting("test.hello_world")+ assert result2 == "universe"