~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
feat: Add database migration and queue system improvements
LearningCircuit27e2d7092690
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.pyindex 16686e49b8..599d19c4ee 100644--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py@@ -12,7 +12,7 @@ from loguru import loggerclass BaseSearchStrategy(ABC):"""Abstract base class for all search strategies."""- def __init__(self, all_links_of_system=None):+ def __init__(self, all_links_of_system=None, settings_snapshot=None):"""Initialize the base strategy with common attributes."""self.progress_callback = Noneself.questions_by_iteration = {}@@ -20,6 +20,17 @@ class BaseSearchStrategy(ABC):self.all_links_of_system = (all_links_of_system if all_links_of_system is not None else [])+ self.settings_snapshot = settings_snapshot or {}++ def get_setting(self, key: str, default=None):+ """Get a setting value from the snapshot."""+ if key in self.settings_snapshot:+ value = self.settings_snapshot[key]+ # Extract value from dict structure if needed+ if isinstance(value, dict) and "value" in value:+ return value["value"]+ return value+ return defaultdef set_progress_callback(self, callback: Callable[[str, int, dict], None]diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.pyindex efcba6a4bd..eaef18ad5f 100644--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py@@ -6,7 +6,8 @@ from loguru import loggerfrom ...citation_handler import CitationHandlerfrom ...config.llm_config import get_llmfrom ...config.search_config import get_search-from ...utilities.db_utils import get_db_setting++# Removed get_db_setting import - using settings_snapshot insteadfrom ...utilities.thread_context import preserve_research_contextfrom ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..filters.cross_engine_filter import CrossEngineFilter@@ -34,10 +35,14 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):cross_engine_max_results: int = None,all_links_of_system=None,use_atomic_facts: bool = False,+ settings_snapshot=None,):"""Initialize with optional dependency injection for testing."""- # Pass the links list to the parent class- super().__init__(all_links_of_system=all_links_of_system)+ # Pass the links list and settings to the parent class+ super().__init__(+ all_links_of_system=all_links_of_system,+ settings_snapshot=settings_snapshot,+ )self.search = search or get_search()self.model = model or get_llm()self.progress_callback = None@@ -119,7 +124,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):}# Determine number of iterations to run- iterations_to_run = get_db_setting("search.iterations", 2)+ iterations_to_run = self.get_setting("search.iterations", 2)logger.debug("Selected amount of iterations: " + str(iterations_to_run))iterations_to_run = int(iterations_to_run)try:@@ -156,7 +161,9 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):current_knowledge=context,query=query,questions_per_iteration=int(- get_db_setting("search.questions_per_iteration")+ self.get_setting(+ "search.questions_per_iteration", 5+ ) # Default to 5 if not set),questions_by_iteration=self.questions_by_iteration,)@@ -189,7 +196,9 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):current_knowledge=context,query=query,questions_per_iteration=int(- get_db_setting("search.questions_per_iteration", 2)+ self.get_setting(+ "search.questions_per_iteration", 2+ )),questions_by_iteration=self.questions_by_iteration,)@@ -326,7 +335,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):reorder=True, # Always reorder in final filteringreindex=True, # Always reindex in final filteringmax_results=int(- get_db_setting("search.final_max_results") or 100+ self.get_setting("search.final_max_results", 100)),start_index=len(self.all_links_of_system),)diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.pyindex 5643f683d5..a0584a72af 100644--- a/src/local_deep_research/citation_handler.py+++ b/src/local_deep_research/citation_handler.py@@ -4,8 +4,6 @@ from typing import Any, Dict, List, Optional, Unionfrom loguru import logger-from .utilities.db_utils import get_db_setting-class CitationHandler:"""@@ -13,13 +11,24 @@ class CitationHandler:Maintains backward compatibility while allowing strategy-specific handlers."""- def __init__(self, llm, handler_type: Optional[str] = None):+ def __init__(+ self, llm, handler_type: Optional[str] = None, settings_snapshot=None+ ):self.llm = llm+ self.settings_snapshot = settings_snapshot or {}# Determine which handler to useif handler_type is None:- # Try to get from settings, default to standard- handler_type = get_db_setting("citation.handler_type", "standard")+ # Try to get from settings snapshot, default to standard+ if "citation.handler_type" in self.settings_snapshot:+ value = self.settings_snapshot["citation.handler_type"]+ handler_type = (+ value["value"]+ if isinstance(value, dict) and "value" in value+ else value+ )+ else:+ handler_type = "standard"# Import and instantiate the appropriate handlerself._handler = self._create_handler(handler_type)@@ -38,7 +47,9 @@ class CitationHandler:)logger.info("Using StandardCitationHandler")- return StandardCitationHandler(self.llm)+ return StandardCitationHandler(+ self.llm, settings_snapshot=self.settings_snapshot+ )elif handler_type in ["forced", "forced_answer", "browsecomp"]:from .citation_handlers.forced_answer_citation_handler import (@@ -48,7 +59,9 @@ class CitationHandler:logger.info("Using ForcedAnswerCitationHandler for better benchmark performance")- return ForcedAnswerCitationHandler(self.llm)+ return ForcedAnswerCitationHandler(+ self.llm, settings_snapshot=self.settings_snapshot+ )elif handler_type in ["precision", "precision_extraction", "simpleqa"]:from .citation_handlers.precision_extraction_handler import (@@ -58,7 +71,9 @@ class CitationHandler:logger.info("Using PrecisionExtractionHandler for precise answer extraction")- return PrecisionExtractionHandler(self.llm)+ return PrecisionExtractionHandler(+ self.llm, settings_snapshot=self.settings_snapshot+ )else:logger.warning(@@ -68,7 +83,9 @@ class CitationHandler:StandardCitationHandler,)- return StandardCitationHandler(self.llm)+ return StandardCitationHandler(+ self.llm, settings_snapshot=self.settings_snapshot+ )def analyze_initial(self, query: str, search_results: Union[str, List[Dict]]diff --git a/src/local_deep_research/citation_handlers/base_citation_handler.py b/src/local_deep_research/citation_handlers/base_citation_handler.pyindex 1a94053145..f9d16e0959 100644--- a/src/local_deep_research/citation_handlers/base_citation_handler.py+++ b/src/local_deep_research/citation_handlers/base_citation_handler.py@@ -11,8 +11,19 @@ from langchain_core.documents import Documentclass BaseCitationHandler(ABC):"""Abstract base class for citation handlers."""- def __init__(self, llm):+ def __init__(self, llm, settings_snapshot=None):self.llm = llm+ self.settings_snapshot = settings_snapshot or {}++ def get_setting(self, key: str, default=None):+ """Get a setting value from the snapshot."""+ if key in self.settings_snapshot:+ value = self.settings_snapshot[key]+ # Extract value from dict structure if needed+ if isinstance(value, dict) and "value" in value:+ return value["value"]+ return value+ return defaultdef _create_documents(self, search_results: Union[str, List[Dict]], nr_of_links: int = 0diff --git a/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py b/src/local_deep_research/citation_handlers/forced_answer_citation_handler.pyindex a163a282bc..289e794992 100644--- a/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py+++ b/src/local_deep_research/citation_handlers/forced_answer_citation_handler.py@@ -7,7 +7,6 @@ from typing import Any, Dict, List, Unionfrom loguru import logger-from ..utilities.db_utils import get_db_settingfrom .base_citation_handler import BaseCitationHandler@@ -65,7 +64,7 @@ Example response format:# Fact-checking step (if enabled)fact_check_response = ""- if get_db_setting("general.enable_fact_checking", True):+ if self.get_setting("general.enable_fact_checking", True):fact_check_prompt = f"""Analyze these sources for factual consistency:1. Cross-reference major claims between sources2. Identify the most frequently mentioned answerdiff --git a/src/local_deep_research/citation_handlers/standard_citation_handler.py b/src/local_deep_research/citation_handlers/standard_citation_handler.pyindex d0ee2b8ac9..ee939195af 100644--- a/src/local_deep_research/citation_handlers/standard_citation_handler.py+++ b/src/local_deep_research/citation_handlers/standard_citation_handler.py@@ -4,7 +4,6 @@ Standard citation handler - the original implementation.from typing import Any, Dict, List, Union-from ..utilities.db_utils import get_db_settingfrom .base_citation_handler import BaseCitationHandler@@ -57,7 +56,7 @@ New Sources:{formatted_sources}Return any inconsistencies or conflicts found."""- if get_db_setting("general.enable_fact_checking", True):+ if self.get_setting("general.enable_fact_checking", True):fact_check_response = self.llm.invoke(fact_check_prompt).contentelse:diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 9342e73d47..d0fa750c15 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -9,9 +9,9 @@ from langchain_openai import ChatOpenAIfrom loguru import loggerfrom ..llm import get_llm_from_registry, is_llm_registered-from ..utilities.db_utils import get_db_settingfrom ..utilities.search_utilities import remove_think_tagsfrom ..utilities.url_utils import normalize_url+from .thread_settings import _thread_local# Valid provider optionsVALID_PROVIDERS = [@@ -26,6 +26,21 @@ VALID_PROVIDERS = []+def get_db_setting(key, default=None, username=None):+ """Get setting from context only - no database access from threads."""+ # Check if we have a settings context in this thread+ if (+ hasattr(_thread_local, "settings_context")+ and _thread_local.settings_context+ ):+ return _thread_local.settings_context.get_setting(key, default)++ # If no context, raise an error - threads should never access database directly+ raise RuntimeError(+ f"No settings context available in thread for key '{key}'. All settings must be passed via settings_snapshot."+ )++def is_openai_available():"""Check if OpenAI is available"""try:diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex 88cfd58715..cde955d456 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -1,7 +1,6 @@# local_deep_research/config.pyfrom loguru import logger-from ..utilities.db_utils import get_db_settingfrom ..web_search_engines.search_engine_factory import (get_search as factory_get_search,)@@ -10,26 +9,61 @@ from .llm_config import get_llm# Whether to check the quality search results using the LLM.QUALITY_CHECK_DDG_URLS = True+# Import shared thread-local storage+from .thread_settings import _thread_local-def get_search_snippets_only_setting():++def get_db_setting(key, default=None, username=None, settings_snapshot=None):+ """Get setting from context only - no database access from threads."""+ # First check if we have settings_snapshot passed directly+ if settings_snapshot and key in settings_snapshot:+ value = settings_snapshot[key]+ # Extract value from dict structure if needed+ if isinstance(value, dict) and "value" in value:+ return value["value"]+ return value++ # Then check if we have a settings context in this thread+ if (+ hasattr(_thread_local, "settings_context")+ and _thread_local.settings_context+ ):+ return _thread_local.settings_context.get_setting(key, default)++ # If no context, raise an error - threads should never access database directly+ raise RuntimeError(+ f"No settings context available in thread for key '{key}'. All settings must be passed via settings_snapshot."+ )+++def get_search_snippets_only_setting(username=None):"""Lazily retrieve the 'search.snippets_only' setting."""- return get_db_setting("search.snippets_only", True)+ return get_db_setting("search.snippets_only", True, username=username)# Expose get_search function-def get_search(search_tool=None, llm_instance=None):+def get_search(+ search_tool=None, llm_instance=None, username=None, settings_snapshot=None+):"""Helper function to get search engineArgs:search_tool: Override the search tool setting (e.g. searxng, wikipedia)llm_instance: Override the LLM instance+ username: Optional username for thread context (e.g., background research threads)+ settings_snapshot: Settings snapshot from thread context"""# Use specified tool or default from settings- tool = search_tool or get_db_setting("search.tool", "searxng")+ tool = search_tool or get_db_setting(+ "search.tool",+ "searxng",+ username=username,+ settings_snapshot=settings_snapshot,+ )logger.info(f"Creating search engine with tool: {tool}")# Get LLM instance (use provided or get fresh one)@@ -39,14 +73,47 @@ def get_search(search_tool=None, llm_instance=None):params = {"search_tool": tool,"llm_instance": llm,- "max_results": get_db_setting("search.max_results", 10),- "region": get_db_setting("search.region", "wt-wt"),- "time_period": get_db_setting("search.time_period", "all"),- "safe_search": get_db_setting("search.safe_search", True),- "search_snippets_only": get_search_snippets_only_setting(),- "search_language": get_db_setting("search.search_language", "English"),+ "max_results": get_db_setting(+ "search.max_results",+ 10,+ username=username,+ settings_snapshot=settings_snapshot,+ ),+ "region": get_db_setting(+ "search.region",+ "wt-wt",+ username=username,+ settings_snapshot=settings_snapshot,+ ),+ "time_period": get_db_setting(+ "search.time_period",+ "all",+ username=username,+ settings_snapshot=settings_snapshot,+ ),+ "safe_search": get_db_setting(+ "search.safe_search",+ True,+ username=username,+ settings_snapshot=settings_snapshot,+ ),+ "search_snippets_only": get_db_setting(+ "search.snippets_only",+ True,+ username=username,+ settings_snapshot=settings_snapshot,+ ),+ "search_language": get_db_setting(+ "search.search_language",+ "English",+ username=username,+ settings_snapshot=settings_snapshot,+ ),"max_filtered_results": get_db_setting(- "search.max_filtered_results", 5+ "search.max_filtered_results",+ 5,+ username=username,+ settings_snapshot=settings_snapshot,),}@@ -56,7 +123,9 @@ def get_search(search_tool=None, llm_instance=None):)# Create search engine- search_engine = factory_get_search(**params)+ search_engine = factory_get_search(+ settings_snapshot=settings_snapshot, **params+ )# Log the created engine typeif search_engine:diff --git a/src/local_deep_research/config/thread_settings.py b/src/local_deep_research/config/thread_settings.pynew file mode 100644index 0000000000..59949ba44a--- /dev/null+++ b/src/local_deep_research/config/thread_settings.py@@ -0,0 +1,22 @@+"""Shared thread-local storage for settings context++This module provides a single thread-local storage instance that can be+shared across different modules to maintain settings context in threads.+"""++import threading++# Shared thread-local storage for settings context+_thread_local = threading.local()+++def set_settings_context(settings_context):+ """Set a settings context for the current thread."""+ _thread_local.settings_context = settings_context+++def get_settings_context():+ """Get the settings context for the current thread."""+ if hasattr(_thread_local, "settings_context"):+ return _thread_local.settings_context+ return Nonediff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 810b1e9825..67af76af80 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -33,7 +33,7 @@ class DatabaseManager:import os as os_moduleimport tempfile- import pysqlcipher3+ import sqlcipher3# Test if SQLCipher actually works, not just if it importswith tempfile.NamedTemporaryFile(delete=False) as tmp:@@ -41,13 +41,21 @@ class DatabaseManager:try:# Try to create a test encrypted database- test_engine = create_engine(- f"sqlite+pysqlcipher://:testpass@/{tmp_path}",- connect_args={"check_same_thread": False},- )- with test_engine.connect() as conn:- conn.execute(text("SELECT 1"))- test_engine.dispose()+ # Import sqlcipher3 to ensure it's available+ import sqlcipher3++ # Use raw sqlcipher3 connection to test+ from sqlcipher3 import dbapi2 as sqlcipher++ conn = sqlcipher.connect(tmp_path)+ conn.execute("PRAGMA key = 'testpass'")+ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY)")+ conn.execute("INSERT INTO test VALUES (1)")+ result = conn.execute("SELECT * FROM test").fetchone()+ conn.close()++ if result != (1,):+ raise Exception("SQLCipher encryption test failed")logger.info("SQLCipher available and working - databases will be encrypted")@@ -120,7 +128,7 @@ class DatabaseManager:pragmas.extend(["PRAGMA kdf_iter = 64000", # Reduced from default 256000 for better performance- "PRAGMA cipher_page_size = 8192", # Larger pages for better performance+ "PRAGMA cipher_page_size = 4096", # Use 4096 to reduce memory usage])else:@@ -133,8 +141,9 @@ class DatabaseManager:try:# Use raw execute on DBAPI connection (not SQLAlchemy's text())connection.execute(pragma)- except Exception as e:- logger.debug(f"Pragma '{pragma}' not supported: {e}")+ except Exception:+ # Don't log here to avoid deadlock with loguru database handler+ passdef create_user_database(self, username: str, password: str) -> Engine:"""Create a new encrypted database for a user."""@@ -145,49 +154,123 @@ class DatabaseManager:# Create connection string - use regular SQLite when SQLCipher not availableif self.has_encryption:- connection_string = f"sqlite+pysqlcipher://:{password}@/{db_path}"+ # Create directory if it doesn't exist+ db_path.parent.mkdir(parents=True, exist_ok=True)++ # SOLUTION: Create database structure using raw SQLCipher outside SQLAlchemy+ # This bypasses the SQLAlchemy DDL execution that causes MemoryError in Flask+ try:+ import sqlcipher3++ # Create tables directly with SQLCipher, bypassing SQLAlchemy DDL+ conn = sqlcipher3.connect(str(db_path))+ conn.execute(f"PRAGMA key = '{password}'")+ conn.execute("PRAGMA cipher_page_size = 4096")+ conn.execute("PRAGMA kdf_iter = 64000")+ # Critical for memory issues as per research+ conn.execute("PRAGMA cipher_memory_security = OFF")++ # Get the CREATE TABLE statements from SQLAlchemy models+ from sqlalchemy.dialects import sqlite+ from sqlalchemy.schema import CreateTable++ from .models import Base++ # Create tables one by one+ sqlite_dialect = sqlite.dialect()+ for table in Base.metadata.sorted_tables:+ if table.name != "users":+ # Get the SQL for this table with SQLite dialect+ create_sql = str(+ CreateTable(table).compile(dialect=sqlite_dialect)+ )+ logger.debug(f"Creating table {table.name}")+ conn.execute(create_sql)++ conn.commit()+ conn.close()++ logger.info(+ f"Database structure created successfully for {username}"+ )++ except Exception:+ logger.exception("Error creating database structure")+ raise++ # Small delay to ensure file is fully written+ import time++ time.sleep(0.1)++ # Now create SQLAlchemy engine using custom connection creator+ # This ensures encryption is properly initialized for every connection+ import sqlcipher3++ def create_sqlcipher_connection():+ """Create a properly initialized SQLCipher connection."""+ conn = sqlcipher3.connect(str(db_path))+ cursor = conn.cursor()++ # Set the encryption key+ cursor.execute(f"PRAGMA key = '{password}'")++ # CRITICAL: Force key derivation with test query immediately+ cursor.execute("SELECT 1")+ cursor.fetchone()++ # Apply SQLCipher-specific pragmas after successful key validation+ cursor.execute("PRAGMA cipher_memory_security = OFF")+ cursor.execute("PRAGMA cipher_page_size = 4096")+ cursor.execute("PRAGMA kdf_iter = 64000")+ cursor.execute("PRAGMA cipher_hmac_algorithm = HMAC_SHA512")+ cursor.execute(+ "PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA512"+ )+ cursor.execute("PRAGMA journal_mode = WAL")+ cursor.execute("PRAGMA synchronous = NORMAL")++ cursor.close()+ return conn++ # Create engine with custom creator function+ engine = create_engine(+ "sqlite://",+ creator=create_sqlcipher_connection,+ poolclass=StaticPool, # Use StaticPool with custom creator+ connect_args={+ "check_same_thread": False,+ },+ echo=False,+ )else:logger.warning(f"SQLCipher not available - creating UNENCRYPTED database for user {username}")# Fall back to regular SQLite- connection_string = f"sqlite:///{db_path}"+ engine = create_engine(+ f"sqlite:///{db_path}",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ echo=False,+ )- # Create engine - adjust connect_args based on whether we're using SQLCipher- if "pysqlcipher" in connection_string:- connect_args = {"check_same_thread": False, "timeout": 30.0}- else:- # Regular SQLite doesn't support the timeout parameter in the same way- connect_args = {"check_same_thread": False}-- engine = create_engine(- connection_string,- connect_args=connect_args,- poolclass=StaticPool, # Single connection per database- echo=False,- )-- # Apply pragmas on connect- event.listen(engine, "connect", self._apply_pragmas)-- # Create all tables except User (which belongs in auth database)- from .models import Base-- # Get all tables except User table- tables_to_create = [- table- for table in Base.metadata.sorted_tables- if table.name != "users"- ]+ # For unencrypted databases, just apply pragmas+ event.listen(engine, "connect", self._apply_pragmas)- # Create only the user-specific tables- Base.metadata.create_all(engine, tables=tables_to_create)+ # Tables have already been created using raw SQLCipher above+ # No need to create them again with SQLAlchemy# Store connectionself.connections[username] = engine# Initialize default settings for the user- self._initialize_user_settings(username)+ # Wrap in try/except to avoid registration failure+ try:+ self._initialize_user_settings(username)+ except Exception as e:+ logger.warning(f"Settings initialization will be deferred: {e}")+ # Settings will be initialized on first login insteadlogger.info(f"Created encrypted database for user {username}")return engine@@ -208,32 +291,61 @@ class DatabaseManager:# Create connection string - use regular SQLite when SQLCipher not availableif self.has_encryption:- connection_string = f"sqlite+pysqlcipher://:{password}@/{db_path}"+ # Use the same custom connection creator approach as create_user_database+ import sqlcipher3++ def create_sqlcipher_connection():+ """Create a properly initialized SQLCipher connection."""+ conn = sqlcipher3.connect(str(db_path))+ cursor = conn.cursor()++ # Set the encryption key+ cursor.execute(f"PRAGMA key = '{password}'")++ # CRITICAL: Force key derivation with test query immediately+ cursor.execute("SELECT 1")+ cursor.fetchone()++ # Apply SQLCipher-specific pragmas after successful key validation+ cursor.execute("PRAGMA cipher_memory_security = OFF")+ cursor.execute("PRAGMA cipher_page_size = 4096")+ cursor.execute("PRAGMA kdf_iter = 64000")+ cursor.execute("PRAGMA cipher_hmac_algorithm = HMAC_SHA512")+ cursor.execute(+ "PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA512"+ )+ cursor.execute("PRAGMA journal_mode = WAL")+ cursor.execute("PRAGMA synchronous = NORMAL")++ cursor.close()+ return conn++ # Create engine with custom creator function+ engine = create_engine(+ "sqlite://",+ creator=create_sqlcipher_connection,+ poolclass=StaticPool, # Use StaticPool with custom creator+ connect_args={+ "check_same_thread": False,+ },+ echo=False,+ )else:logger.warning(f"SQLCipher not available - opening UNENCRYPTED database for user {username}")# Fall back to regular SQLite (no password protection!)- connection_string = f"sqlite:///{db_path}"-- try:- # Create engine - adjust connect_args based on whether we're using SQLCipher- if "pysqlcipher" in connection_string:- connect_args = {"check_same_thread": False, "timeout": 30.0}- else:- # Regular SQLite doesn't support the timeout parameter in the same way- connect_args = {"check_same_thread": False}-engine = create_engine(- connection_string,- connect_args=connect_args,+ f"sqlite:///{db_path}",+ connect_args={"check_same_thread": False},poolclass=StaticPool,echo=False,)- # Apply pragmas on connect+ # For unencrypted databases, just apply pragmasevent.listen(engine, "connect", self._apply_pragmas)+ try:# Test connection by running a simple querywith engine.connect() as conn:conn.execute(text("SELECT 1"))@@ -251,8 +363,8 @@ class DatabaseManager:if table.name != "users"]- # Create any missing tables- Base.metadata.create_all(engine, tables=tables_to_create)+ # Don't create tables when opening existing database+ # Tables should already exist from create_user_databaselogger.info(f"Opened encrypted database for user {username}")return engine@@ -358,11 +470,20 @@ class DatabaseManager:def _initialize_user_settings(self, username: str):"""Initialize default settings for a new user."""+ session = Nonetry:- session = self.get_session(username)- if not session:+ # Get engine directly to ensure we're in the same thread+ engine = self.connections.get(username)+ if not engine:+ logger.error(f"No engine found for {username}")return+ # Create a new session from the engine+ from sqlalchemy.orm import sessionmaker++ SessionLocal = sessionmaker(bind=engine)+ session = SessionLocal()+# Load comprehensive default settings from the defaults filefrom ..web.services.settings_manager import SettingsManager@@ -372,14 +493,20 @@ class DatabaseManager:settings_manager = SettingsManager(session)settings_manager.load_from_defaults_file(commit=True)+ # Explicitly commit to ensure settings are saved+ session.commit()+logger.info(f"Initialized default settings for user {username}")except Exception as e:- logger.error(+ logger.exception(f"Failed to initialize settings for user {username}: {e}")if session:session.rollback()+ finally:+ if session:+ session.close()def get_memory_usage(self) -> Dict[str, Any]:"""Get memory usage statistics."""diff --git a/src/local_deep_research/database/service_db.py b/src/local_deep_research/database/service_db.pynew file mode 100644index 0000000000..ccb53f173e--- /dev/null+++ b/src/local_deep_research/database/service_db.py@@ -0,0 +1,240 @@+"""+Service database for background operations.+Stores non-sensitive metadata to avoid accessing encrypted user databases from background services.+"""++from datetime import datetime, timedelta+from typing import Any, Dict, Optional++from loguru import logger+from sqlalchemy import Boolean, Column, DateTime, Integer, String, create_engine+from sqlalchemy.ext.declarative import declarative_base+from sqlalchemy.orm import Session, sessionmaker+from sqlalchemy.pool import StaticPool++from ..config.paths import get_data_directory++Base = declarative_base()+++class QueueStatus(Base):+ """Track queue status for each user without accessing their encrypted database."""++ __tablename__ = "queue_status"++ username = Column(String, primary_key=True)+ active_tasks = Column(Integer, default=0)+ queued_tasks = Column(Integer, default=0)+ last_checked = Column(DateTime, default=datetime.utcnow)+ last_task_id = Column(String, nullable=True)+++class TaskMetadata(Base):+ """Store task metadata for background processing."""++ __tablename__ = "task_metadata"++ task_id = Column(String, primary_key=True)+ username = Column(String, nullable=False, index=True)+ status = Column(+ String, nullable=False+ ) # queued, processing, completed, failed+ task_type = Column(String, nullable=False) # research, benchmark, etc+ created_at = Column(DateTime, default=datetime.utcnow)+ started_at = Column(DateTime, nullable=True)+ completed_at = Column(DateTime, nullable=True)+ error_message = Column(String, nullable=True)+ requires_db_access = Column(Boolean, default=True)+++class ServiceDatabase:+ """Manages the unencrypted service database for background operations."""++ def __init__(self):+ self.data_dir = get_data_directory()+ self.db_path = self.data_dir / "service.db"+ self.engine = None+ self.SessionLocal = None+ self._initialize()++ def _initialize(self):+ """Initialize the service database."""+ logger.info(f"Initializing service database at {self.db_path}")++ # Create engine for unencrypted service database+ self.engine = create_engine(+ f"sqlite:///{self.db_path}",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ echo=False,+ )++ # Create tables+ Base.metadata.create_all(self.engine)++ # Create session factory+ self.SessionLocal = sessionmaker(bind=self.engine)++ logger.info("Service database initialized successfully")++ def get_session(self) -> Session:+ """Get a new database session."""+ return self.SessionLocal()++ def update_queue_status(+ self, username: str, active_tasks: int, queued_tasks: int+ ) -> None:+ """Update queue status for a user."""+ with self.get_session() as session:+ status = (+ session.query(QueueStatus).filter_by(username=username).first()+ )++ if status:+ status.active_tasks = active_tasks+ status.queued_tasks = queued_tasks+ status.last_checked = datetime.utcnow()+ else:+ status = QueueStatus(+ username=username,+ active_tasks=active_tasks,+ queued_tasks=queued_tasks,+ )+ session.add(status)++ session.commit()++ def get_queue_status(self, username: str) -> Optional[Dict[str, Any]]:+ """Get queue status for a user."""+ with self.get_session() as session:+ status = (+ session.query(QueueStatus).filter_by(username=username).first()+ )++ if status:+ return {+ "active_tasks": status.active_tasks,+ "queued_tasks": status.queued_tasks,+ "last_checked": status.last_checked,+ "last_task_id": status.last_task_id,+ }+ return None++ def add_task_metadata(+ self,+ task_id: str,+ username: str,+ task_type: str,+ requires_db_access: bool = True,+ ) -> None:+ """Add metadata for a new task."""+ with self.get_session() as session:+ task = TaskMetadata(+ task_id=task_id,+ username=username,+ status="queued",+ task_type=task_type,+ requires_db_access=requires_db_access,+ )+ session.add(task)++ # Update queue status+ status = (+ session.query(QueueStatus).filter_by(username=username).first()+ )+ if status:+ status.queued_tasks += 1+ status.last_task_id = task_id+ else:+ status = QueueStatus(+ username=username, queued_tasks=1, last_task_id=task_id+ )+ session.add(status)++ session.commit()++ def update_task_status(+ self, task_id: str, status: str, error_message: str = None+ ) -> None:+ """Update task status."""+ with self.get_session() as session:+ task = (+ session.query(TaskMetadata).filter_by(task_id=task_id).first()+ )++ if task:+ old_status = task.status+ task.status = status+ task.error_message = error_message++ if status == "processing" and old_status == "queued":+ task.started_at = datetime.utcnow()+ # Update queue counts+ queue_status = (+ session.query(QueueStatus)+ .filter_by(username=task.username)+ .first()+ )+ if queue_status:+ queue_status.queued_tasks = max(+ 0, queue_status.queued_tasks - 1+ )+ queue_status.active_tasks += 1++ elif status in ["completed", "failed"]:+ task.completed_at = datetime.utcnow()+ # Update queue counts+ queue_status = (+ session.query(QueueStatus)+ .filter_by(username=task.username)+ .first()+ )+ if queue_status:+ queue_status.active_tasks = max(+ 0, queue_status.active_tasks - 1+ )++ session.commit()++ def get_pending_tasks(self, username: str, limit: int = 5) -> list:+ """Get pending tasks for a user that don't require database access."""+ with self.get_session() as session:+ tasks = (+ session.query(TaskMetadata)+ .filter_by(+ username=username, status="queued", requires_db_access=False+ )+ .order_by(TaskMetadata.created_at)+ .limit(limit)+ .all()+ )++ return [+ {+ "task_id": t.task_id,+ "task_type": t.task_type,+ "created_at": t.created_at,+ }+ for t in tasks+ ]++ def cleanup_old_tasks(self, days: int = 7) -> int:+ """Clean up old completed/failed tasks."""+ with self.get_session() as session:+ cutoff_date = datetime.utcnow() - timedelta(days=days)++ deleted = (+ session.query(TaskMetadata)+ .filter(+ TaskMetadata.status.in_(["completed", "failed"]),+ TaskMetadata.completed_at < cutoff_date,+ )+ .delete()+ )++ session.commit()+ return deleted+++# Global instance+service_db = ServiceDatabase()diff --git a/src/local_deep_research/database/session_context.py b/src/local_deep_research/database/session_context.pynew file mode 100644index 0000000000..3e39a69bff--- /dev/null+++ b/src/local_deep_research/database/session_context.py@@ -0,0 +1,200 @@+"""+Database session context manager and decorator for encrypted databases.+Ensures all database access has proper encryption context.+"""++import functools+from contextlib import contextmanager+from typing import Callable, Optional++from flask import g, has_app_context, session as flask_session+from loguru import logger+from sqlalchemy.orm import Session++from .encrypted_db import db_manager+++class DatabaseSessionError(Exception):+ """Raised when database session cannot be established."""++ pass+++@contextmanager+def get_user_db_session(+ username: Optional[str] = None, password: Optional[str] = None+):+ """+ Context manager that ensures proper database session with encryption.++ Args:+ username: Username (if not provided, gets from Flask session)+ password: Password for encrypted database (required for first access)++ Yields:+ Database session for the user++ Raises:+ DatabaseSessionError: If session cannot be established+ """+ session = None+ needs_close = False++ try:+ # Get username from Flask session if not provided (only in Flask context)+ if not username and has_app_context():+ username = flask_session.get("username")++ if not username:+ raise DatabaseSessionError("No authenticated user")++ # Check if we already have a session in Flask context+ # IMPORTANT: Always create a fresh session to avoid thread safety issues+ # SQLite doesn't support cross-thread session sharing+ if has_app_context() and hasattr(g, "db_session") and g.db_session:+ # Close existing session if any+ try:+ g.db_session.close()+ except:+ pass+ g.db_session = None++ # Always create a fresh session+ if True:+ # Check if database connection exists+ if username in db_manager.connections:+ session = db_manager.get_session(username)+ needs_close = True+ elif password:+ # Try to open database with password+ engine = db_manager.open_user_database(username, password)+ if engine:+ session = db_manager.get_session(username)+ needs_close = True+ else:+ raise DatabaseSessionError(+ f"Failed to open database for {username}"+ )+ else:+ # For encrypted databases, we need a password+ if db_manager.has_encryption:+ raise DatabaseSessionError(+ f"Encrypted database for {username} requires password"+ )+ else:+ # Try to open unencrypted database+ engine = db_manager.open_user_database(username, "dummy")+ if engine:+ session = db_manager.get_session(username)+ needs_close = True++ if not session:+ raise DatabaseSessionError(+ f"Could not establish session for {username}"+ )++ yield session++ finally:+ # Only close if we created a new session+ if session and needs_close:+ try:+ session.close()+ except Exception:+ pass+++def with_user_database(func: Callable) -> Callable:+ """+ Decorator that ensures function has access to user's database.+ Injects 'db_session' as first argument to the decorated function.++ Usage:+ @with_user_database+ def get_user_settings(db_session, setting_key):+ return db_session.query(Setting).filter_by(key=setting_key).first()+ """++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ # Check if username/password provided in kwargs+ username = kwargs.pop("_username", None)+ password = kwargs.pop("_password", None)++ with get_user_db_session(username, password) as db_session:+ return func(db_session, *args, **kwargs)++ return wrapper+++def ensure_db_session(view_func: Callable) -> Callable:+ """+ Flask view decorator that ensures database session is available.+ Sets g.db_session for use in the request.++ Usage:+ @app.route('/my-route')+ @ensure_db_session+ def my_view():+ # g.db_session is available here+ settings = g.db_session.query(Setting).all()+ """++ @functools.wraps(view_func)+ def wrapper(*args, **kwargs):+ username = flask_session.get("username")++ if not username:+ # Let the view handle unauthenticated users+ return view_func(*args, **kwargs)++ try:+ # Try to get or create session+ if username in db_manager.connections:+ g.db_session = db_manager.get_session(username)+ else:+ # Database not open - for encrypted DBs this means user needs to re-login+ if db_manager.has_encryption:+ # Clear session to force re-login+ flask_session.clear()+ from flask import redirect, url_for++ return redirect(url_for("auth.login"))+ else:+ # Try to reopen unencrypted database+ engine = db_manager.open_user_database(username, "dummy")+ if engine:+ g.db_session = db_manager.get_session(username)++ except Exception:+ logger.exception(+ f"Failed to ensure database session for {username}"+ )++ return view_func(*args, **kwargs)++ return wrapper+++class DatabaseAccessMixin:+ """+ Mixin class for services that need database access.+ Provides convenient methods for database operations.+ """++ def get_db_session(+ self, username: Optional[str] = None+ ) -> Optional[Session]:+ """Get database session for user."""+ try:+ with get_user_db_session(username) as session:+ return session+ except DatabaseSessionError:+ return None++ @with_user_database+ def execute_with_db(+ self, db_session: Session, query_func: Callable, *args, **kwargs+ ):+ """Execute a function with database session."""+ return query_func(db_session, *args, **kwargs)diff --git a/src/local_deep_research/database/temp_auth.py b/src/local_deep_research/database/temp_auth.pynew file mode 100644index 0000000000..0ff8b63e35--- /dev/null+++ b/src/local_deep_research/database/temp_auth.py@@ -0,0 +1,108 @@+"""+Temporary authentication storage for handling post-registration flow.+Stores encrypted passwords briefly to allow database access after redirect.+"""++import secrets+import time+from typing import Dict, Optional++from cryptography.fernet import Fernet+from loguru import logger+++class TemporaryAuthStore:+ """+ Stores authentication temporarily for post-registration/login flow.+ Passwords are encrypted in memory and expire after a short time.+ """++ def __init__(self, ttl_seconds: int = 30):+ """+ Initialize the temporary auth store.++ Args:+ ttl_seconds: How long to keep auth data (default 30 seconds)+ """+ self.ttl = ttl_seconds+ self._store: Dict[str, Dict] = {}+ self._master_key = Fernet.generate_key()+ self._cipher = Fernet(self._master_key)++ def store_auth(self, username: str, password: str) -> str:+ """+ Store authentication temporarily.++ Args:+ username: Username+ password: Password to store++ Returns:+ Token to retrieve the auth data+ """+ token = secrets.token_urlsafe(32)++ # Encrypt password+ encrypted_password = self._cipher.encrypt(password.encode())++ # Store with expiration+ self._store[token] = {+ "username": username,+ "password": encrypted_password,+ "expires_at": time.time() + self.ttl,+ }++ # Clean up expired entries+ self._cleanup_expired()++ logger.debug(f"Stored temporary auth for {username}")+ return token++ def retrieve_auth(self, token: str) -> Optional[tuple[str, str]]:+ """+ Retrieve and remove authentication data.++ Args:+ token: Token from store_auth++ Returns:+ Tuple of (username, password) or None if expired/not found+ """+ if token not in self._store:+ return None++ entry = self._store[token]++ # Check expiration+ if time.time() > entry["expires_at"]:+ del self._store[token]+ return None++ # Get data and remove from store (one-time use)+ username = entry["username"]+ encrypted_password = entry["password"]+ del self._store[token]++ # Decrypt password+ try:+ password = self._cipher.decrypt(encrypted_password).decode()+ logger.debug(f"Retrieved temporary auth for {username}")+ return username, password+ except Exception:+ logger.exception("Failed to decrypt temporary auth")+ return None++ def _cleanup_expired(self):+ """Remove expired entries."""+ current_time = time.time()+ expired_tokens = [+ token+ for token, entry in self._store.items()+ if current_time > entry["expires_at"]+ ]+ for token in expired_tokens:+ del self._store[token]+++# Global instance+temp_auth_store = TemporaryAuthStore()diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 78350e3c6d..7920443395 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -300,6 +300,16 @@ class TokenCountingCallback(BaseCallbackHandler):def _save_to_db(self, prompt_tokens: int, completion_tokens: int):"""Save token usage to the database."""+ # Check if we're in a thread - if so, skip database access+ import threading++ if threading.current_thread().name != "MainThread":+ logger.debug(+ f"Skipping token metrics save - in thread {threading.current_thread().name}. "+ f"Token usage: prompt={prompt_tokens}, completion={completion_tokens}"+ )+ return+try:db = get_metrics_db()with db.get_session() as session:diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex 3a32bffd99..507be9ccf3 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -71,6 +71,8 @@ class AdvancedSearchSystem:max_iterations: int | None = None,questions_per_iteration: int | None = None,use_atomic_facts: bool = False,+ username: str | None = None,+ settings_snapshot: dict | None = None,):"""Initialize the advanced search system.@@ -115,17 +117,39 @@ class AdvancedSearchSystem:self.model = get_llm()self.search = searchif search is None:- self.search = get_search(llm_instance=self.model)+ self.search = get_search(+ llm_instance=self.model,+ username=username,+ settings_snapshot=settings_snapshot,+ )++ # Store settings snapshot+ self.settings_snapshot = settings_snapshot or {}# Get iterations settingself.max_iterations = max_iterationsif self.max_iterations is None:- self.max_iterations = get_db_setting("search.iterations", 1)+ # Use settings from snapshot+ if "search.iterations" in self.settings_snapshot:+ value = self.settings_snapshot["search.iterations"]+ if isinstance(value, dict) and "value" in value:+ self.max_iterations = value["value"]+ else:+ self.max_iterations = value+ else:+ self.max_iterations = 1 # Default+self.questions_per_iteration = questions_per_iterationif self.questions_per_iteration is None:- self.questions_per_iteration = get_db_setting(- "search.questions_per_iteration", 3- )+ # Use settings from snapshot+ if "search.questions_per_iteration" in self.settings_snapshot:+ value = self.settings_snapshot["search.questions_per_iteration"]+ if isinstance(value, dict) and "value" in value:+ self.questions_per_iteration = value["value"]+ else:+ self.questions_per_iteration = value+ else:+ self.questions_per_iteration = 3 # Default# Log the strategy name that's being usedlogger.info(@@ -133,7 +157,9 @@ class AdvancedSearchSystem:)# Initialize components- self.citation_handler = CitationHandler(self.model)+ self.citation_handler = CitationHandler(+ self.model, settings_snapshot=self.settings_snapshot+ )self.question_generator = StandardQuestionGenerator(self.model)self.findings_repository = FindingsRepository(self.model)# For backward compatibility@@ -148,6 +174,7 @@ class AdvancedSearchSystem:model=self.model,search=self.search,all_links_of_system=self.all_links_of_system,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["source-based", "source_based"]:logger.info("Creating SourceBasedSearchStrategy instance")@@ -158,6 +185,7 @@ class AdvancedSearchSystem:use_cross_engine_filter=use_cross_engine_filter,all_links_of_system=self.all_links_of_system,use_atomic_facts=use_atomic_facts,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "parallel":logger.info("Creating ParallelSearchStrategy instance")@@ -167,6 +195,7 @@ class AdvancedSearchSystem:include_text_content=include_text_content,use_cross_engine_filter=use_cross_engine_filter,all_links_of_system=self.all_links_of_system,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "rapid":logger.info("Creating RapidSearchStrategy instance")@@ -174,6 +203,7 @@ class AdvancedSearchSystem:model=self.model,search=self.search,all_links_of_system=self.all_links_of_system,+ settings_snapshot=self.settings_snapshot,)elif (strategy_name.lower() == "recursive"@@ -184,6 +214,7 @@ class AdvancedSearchSystem:model=self.model,search=self.search,all_links_of_system=self.all_links_of_system,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "iterative":logger.info("Creating IterativeReasoningStrategy instance")@@ -198,6 +229,7 @@ class AdvancedSearchSystem:search_iterations_per_round=self.max_iterationsor 1, # Search iterations from settingsquestions_per_search=self.questions_per_iteration,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "adaptive":logger.info("Creating AdaptiveDecompositionStrategy instance")@@ -209,6 +241,7 @@ class AdvancedSearchSystem:min_confidence=0.8,source_search_iterations=2,source_questions_per_iteration=self.questions_per_iteration,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "smart":logger.info("Creating SmartDecompositionStrategy instance")@@ -219,6 +252,7 @@ class AdvancedSearchSystem:max_iterations=self.max_iterations,source_search_iterations=2,source_questions_per_iteration=self.questions_per_iteration,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "browsecomp":logger.info("Creating BrowseCompOptimizedStrategy instance")@@ -230,6 +264,7 @@ class AdvancedSearchSystem:confidence_threshold=0.9,max_iterations=self.max_iterations, # Source-based sub-searchesquestions_per_iteration=self.questions_per_iteration, # Source-based sub-searches+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "evidence":logger.info("Creating EnhancedEvidenceBasedStrategy instance")@@ -245,6 +280,7 @@ class AdvancedSearchSystem:questions_per_iteration=self.questions_per_iteration,min_candidates_threshold=10, # Increased from 3enable_pattern_learning=True,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() == "constrained":logger.info("Creating ConstrainedSearchStrategy instance")@@ -259,6 +295,7 @@ class AdvancedSearchSystem:max_search_iterations=self.max_iterations,questions_per_iteration=self.questions_per_iteration,min_candidates_per_stage=20, # Increased from 5+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["parallel-constrained",@@ -277,6 +314,7 @@ class AdvancedSearchSystem:questions_per_iteration=self.questions_per_iteration,min_candidates_per_stage=20, # Correct parameter name for parent classparallel_workers=100, # Run up to 100 searches in parallel+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["early-stop-constrained",@@ -297,6 +335,7 @@ class AdvancedSearchSystem:parallel_workers=100, # Increased parallelism as requestedearly_stop_threshold=0.99, # Stop when we find 99%+ confidenceconcurrent_evaluation=True, # Evaluate candidates as we find them+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["smart-query", "smart_query"]:from .advanced_search_system.strategies.smart_query_strategy import (@@ -320,6 +359,7 @@ class AdvancedSearchSystem:concurrent_evaluation=True, # Evaluate candidates as we find themuse_llm_query_generation=True, # Use smart query generationqueries_per_combination=3, # Generate multiple queries+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["dual-confidence", "dual_confidence"]:from .advanced_search_system.strategies.dual_confidence_strategy import (@@ -347,6 +387,7 @@ class AdvancedSearchSystem:use_direct_property_search=True,uncertainty_penalty=0.2, # Penalty for uncertain evidencenegative_weight=0.5, # How much negative evidence counts against+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["dual-confidence-with-rejection",@@ -380,6 +421,7 @@ class AdvancedSearchSystem:rejection_threshold=0.3, # Reject if negative confidence > 30%positive_threshold=0.2, # Unless positive confidence > 20%critical_constraint_rejection=0.2, # Stricter for critical constraints+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["concurrent-dual-confidence",@@ -422,6 +464,7 @@ class AdvancedSearchSystem:quality_plateau_threshold=0.1,max_search_time=30.0,max_evaluations=30,+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["modular", "modular-strategy"]:from .advanced_search_system.strategies.modular_strategy import (@@ -439,6 +482,7 @@ class AdvancedSearchSystem:early_stopping=True, # Enable early stoppingllm_constraint_processing=True, # Enable LLM-driven constraint processingimmediate_evaluation=True, # Enable immediate candidate evaluation+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["modular-parallel", "modular_parallel"]:from .advanced_search_system.strategies.modular_strategy import (@@ -454,6 +498,7 @@ class AdvancedSearchSystem:all_links_of_system=self.all_links_of_system,constraint_checker_type="dual_confidence", # Concurrent evaluation with +/-/? scoringexploration_strategy="parallel", # Parallel constraint searches+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["focused-iteration",@@ -472,6 +517,7 @@ class AdvancedSearchSystem:max_iterations=self.max_iterations, # Use database settingquestions_per_iteration=self.questions_per_iteration, # Use database settinguse_browsecomp_optimization=True, # Enable BrowseComp optimizations for 95% accuracy+ settings_snapshot=self.settings_snapshot,)elif strategy_name.lower() in ["browsecomp-entity",diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex b100d03dda..1b922774c9 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -2,7 +2,7 @@ import functoolsfrom typing import Any, Callable, Dictfrom cachetools import LRUCache-from flask import g, session as flask_session+from flask import g, has_app_context, session as flask_sessionfrom loguru import loggerfrom sqlalchemy.orm import Session@@ -33,6 +33,24 @@ def get_db_session(Returns:The database session for the current user/context."""+ # CRITICAL: Detect if we're in a background thread and raise an error+ # This helps identify code that's trying to access the database from threads+ import threading++ # Check if we're in a background thread (not in Flask request context)+ # We check for request context specifically because app context might exist+ # during startup but we still shouldn't access the database from background threads+ thread_name = threading.current_thread().name++ # Allow MainThread during startup, but not other threads+ if not has_app_context() and thread_name != "MainThread":+ thread_id = threading.get_ident()+ raise RuntimeError(+ f"Database access attempted from background thread '{thread_name}' (ID: {thread_id}). "+ f"Database access from threads is not allowed due to SQLite thread safety constraints. "+ f"Use settings_snapshot or pass all required data to the thread at creation time."+ )+# If username is explicitly provided (e.g., from background thread)if username:user_session = db_manager.get_session(username)@@ -52,14 +70,15 @@ def get_db_session(user_session = db_manager.get_session(username)if user_session:return user_session- except RuntimeError:- # Not in a Flask request context+ except Exception:+ # Error accessing Flask contextpass- # No shared database - require authenticated user- raise RuntimeError(- "No authenticated user found. Database access requires authentication."+ # No shared database - return None to allow SettingsManager to work without DB+ logger.warning(+ "get_db_session() is deprecated. Use get_user_db_session() from database.session_context")+ return Nonedef get_settings_manager(username: str | None = None) -> SettingsManager:@@ -126,11 +145,37 @@ def get_db_setting(The setting value."""- try:- # Get settings manager which handles database access- return get_settings_manager(username).get_setting(- key, default=default_value+ # CRITICAL: Detect if we're in a background thread and raise an error+ import threading++ # Check if we're in a background thread+ thread_name = threading.current_thread().name++ # Allow MainThread during startup, but not other threads+ if not has_app_context() and thread_name != "MainThread":+ thread_id = threading.get_ident()+ raise RuntimeError(+ f"get_db_setting('{key}') called from background thread '{thread_name}' (ID: {thread_id}). "+ f"Database access from threads is not allowed. Use settings_snapshot or thread-local settings context.")++ try:+ # Use the new session context to ensure proper database access+ from ..database.session_context import get_user_db_session++ try:+ with get_user_db_session(username) as db_session:+ if db_session:+ from ..web.services.settings_manager import SettingsManager++ settings_manager = SettingsManager(db_session)+ return settings_manager.get_setting(+ key, default=default_value+ )+ except Exception:+ # If we can't get a session, fall back to default+ pass+except Exception:logger.exception(f"Error getting setting {key} from database")diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 8497157549..a613727e52 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -7,22 +7,27 @@ from __future__ import annotationsimport inspectimport logging+import queueimport sys+import threadingfrom functools import wrapsfrom typing import Any, Callableimport logurufrom flask import g, has_app_contextfrom loguru import logger-from sqlalchemy.exc import OperationalErrorfrom ..config.paths import get_logs_directoryfrom ..database.models import ResearchLogfrom ..web.services.socket_service import SocketIOService-from .db_utils import get_db_session_LOG_DIR = get_logs_directory()_LOG_DIR.mkdir(parents=True, exist_ok=True)++# Thread-safe queue for database logs from background threads+_log_queue = queue.Queue(maxsize=1000)+_queue_processor_thread = None+_stop_queue = threading.Event()"""Default log directory to use."""@@ -105,9 +110,68 @@ def _get_research_id(record=None) -> str | None:return research_id+def _process_log_queue():+ """+ Process logs from the queue in a dedicated thread with app context.+ This runs in the main thread context to avoid SQLite thread safety issues.+ """+ while not _stop_queue.is_set():+ try:+ # Wait for logs with timeout to check stop flag+ log_entry = _log_queue.get(timeout=0.1)++ # Skip if no entry+ if log_entry is None:+ continue++ # Write to database if we have app context+ if has_app_context():+ _write_log_to_database(log_entry)+ else:+ # If no app context, put it back in queue for later+ try:+ _log_queue.put_nowait(log_entry)+ except queue.Full:+ pass # Drop log if queue is full++ except queue.Empty:+ continue+ except Exception:+ # Don't let logging errors crash the processor+ pass+++def _write_log_to_database(log_entry: dict) -> None:+ """+ Write a log entry to the database. Should only be called from main thread.+ """+ from ..database.session_context import get_user_db_session++ try:+ username = log_entry.get("username")++ with get_user_db_session(username) as db_session:+ if db_session:+ db_log = ResearchLog(+ timestamp=log_entry["timestamp"],+ message=log_entry["message"],+ module=log_entry["module"],+ function=log_entry["function"],+ line_no=log_entry["line_no"],+ level=log_entry["level"],+ research_id=log_entry["research_id"],+ )+ db_session.add(db_log)+ db_session.commit()+ except Exception:+ # Ignore database errors in logging+ pass++def database_sink(message: loguru.Message) -> None:"""Sink that saves messages to the database.+ Queues logs from background threads for later processing.Args:message: The log message to save.@@ -116,34 +180,30 @@ def database_sink(message: loguru.Message) -> None:record = message.recordresearch_id = _get_research_id(record)- # Create a new database entry.- db_log = ResearchLog(- timestamp=record["time"],- message=record[- "message"- ], # Use raw message to avoid formatting artifacts in web UI- module=record["name"],- function=record["function"],- line_no=int(record["line"]),- level=record["level"].name, # Keep original case- research_id=research_id,- )-- # Save the entry to the database.- try:- db_session = get_db_session("log_utils.database_sink")- except RuntimeError:- # No authenticated user yet, skip database logging- return-- try:- db_session.add(db_log)- db_session.commit()- except OperationalError:- # Something else is probably using the DB and we can't write to it- # right now. Ignore this.- db_session.rollback()- return+ # Create log entry dict+ log_entry = {+ "timestamp": record["time"],+ "message": record["message"],+ "module": record["name"],+ "function": record["function"],+ "line_no": int(record["line"]),+ "level": record["level"].name,+ "research_id": research_id,+ "username": record.get("extra", {}).get("username"),+ }++ # Check if we're in a background thread+ # Note: Socket.IO handlers run in separate threads even with app context+ if not has_app_context() or threading.current_thread().name != "MainThread":+ # Queue the log for later processing+ try:+ _log_queue.put_nowait(log_entry)+ except queue.Full:+ # Drop log if queue is full to avoid blocking+ pass+ else:+ # We're in the main thread with app context - write directly+ _write_log_to_database(log_entry)def frontend_progress_sink(message: loguru.Message) -> None:@@ -173,6 +233,26 @@ def frontend_progress_sink(message: loguru.Message) -> None:)+def flush_log_queue():+ """+ Flush all pending logs from the queue to the database.+ This should be called from a Flask request context.+ """+ flushed = 0+ while not _log_queue.empty():+ try:+ log_entry = _log_queue.get_nowait()+ _write_log_to_database(log_entry)+ flushed += 1+ except queue.Empty:+ break+ except Exception:+ pass++ if flushed > 0:+ logger.debug(f"Flushed {flushed} queued log entries to database")++def config_logger(name: str) -> None:"""Configures the default logger.diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex f4ab2396d6..fe9cf2a36c 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -1,6 +1,5 @@from loguru import logger-from ..utilities.db_utils import get_db_settingfrom ..utilities.log_utils import config_loggerfrom .app_factory import create_app@@ -15,29 +14,30 @@ def main():config_logger("ldr_web")# Create the Flask app and SocketIO instance- app, socketio = create_app()-- # Get web server settings with defaults- port = get_db_setting("web.port", 5000)- host = get_db_setting("web.host", "0.0.0.0")- debug = get_db_setting("web.debug", True)- use_https = get_db_setting("web.use_https", True) # Default to HTTPS-- with app.app_context():- if use_https:- # For development, use self-signed certificate- logger.info("Starting server with HTTPS (self-signed certificate)")- # Note: SocketIOService doesn't support SSL context directly- # For production, use a reverse proxy like nginx for HTTPS- logger.warning(- "HTTPS requested but not supported directly. Use a reverse proxy for HTTPS."- )- socketio.run(host=host, port=port, debug=debug)- else:- logger.warning(- "Starting server with HTTP (not recommended for authentication)"- )- socketio.run(host=host, port=port, debug=debug)+ app, socket_service = create_app()++ # Get web server settings from environment or use defaults+ # Can't use database here because Flask app context isn't established yet+ import os++ port = int(os.environ.get("LDR_PORT", "5000"))+ host = os.environ.get("LDR_HOST", "0.0.0.0")+ debug = os.environ.get("LDR_DEBUG", "true").lower() == "true"+ use_https = (+ os.environ.get("LDR_USE_HTTPS", "true").lower() == "true"+ ) # Default to HTTPS++ if use_https:+ # For development, use self-signed certificate+ logger.info("Starting server with HTTPS (self-signed certificate)")+ # Note: SocketIOService doesn't support SSL context directly+ # For production, use a reverse proxy like nginx for HTTPS+ logger.warning(+ "HTTPS requested but not supported directly. Use a reverse proxy for HTTPS."+ )++ # Use the SocketIOService's run method which properly runs the socketio server+ socket_service.run(host=host, port=port, debug=debug)if __name__ == "__main__":diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 12a1f0fe52..07a3ce413c 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -62,7 +62,7 @@ def create_app():# Initialize CSRF protectioncsrf = CSRFProtect(app)# Exempt Socket.IO from CSRF protection- csrf.exempt("research.socket_io")+ # Note: Flask-SocketIO handles CSRF internally, so we don't need to exempt specific views# Disable CSRF for API routes@app.before_request@@ -141,12 +141,35 @@ def apply_middleware(app):# Import auth decorators and middlewarefrom .auth.database_middleware import ensure_user_databasefrom .auth.decorators import inject_current_user+ from .auth.queue_middleware import process_pending_queue_operations# Register authentication middleware# First ensure database is open for authenticated usersapp.before_request(ensure_user_database)# Then inject current user into gapp.before_request(inject_current_user)+ # Process any pending queue operations for the user+ app.before_request(process_pending_queue_operations)++ # Flush any queued logs from background threads+ from ..utilities.log_utils import flush_log_queue++ app.before_request(flush_log_queue)++ # Clean up database sessions after each request+ @app.teardown_appcontext+ def cleanup_db_session(exception=None):+ """Clean up database session after each request to avoid cross-thread issues."""+ from flask import g++ if hasattr(g, "db_session"):+ try:+ if g.db_session:+ g.db_session.close()+ except Exception:+ pass # Ignore errors during cleanup+ finally:+ g.db_session = None# Add Content Security Policy headers to allow Socket.IO to function@app.after_request@@ -185,7 +208,7 @@ def apply_middleware(app):# Add a middleware layer to handle abrupt disconnections@app.before_requestdef handle_websocket_requests():- if request.path.startswith("/research/socket.io"):+ if request.path.startswith("/socket.io"):try:if not request.environ.get("werkzeug.socket"):return@@ -194,6 +217,38 @@ def apply_middleware(app):# Return empty response to prevent further processingreturn "", 200+ # Process queued database operations for logged-in users+ @app.before_request+ def process_queued_operations():+ """Process any pending database operations for the current user."""+ from flask import session++ from ..database.session_context import get_user_db_session+ from .queue.processor import queue_processor++ # Only process for authenticated users+ username = session.get("username")+ if username and not request.path.startswith("/static/"):+ try:+ # Get database session for user+ with get_user_db_session(username) as db_session:+ if db_session:+ # Process any pending operations+ count = (+ queue_processor.process_pending_operations_for_user(+ username, db_session+ )+ )+ if count > 0:+ logger.debug(+ f"Processed {count} queued operations for user {username}"+ )+ except Exception:+ # Don't let queue processing errors break the request+ logger.exception(+ f"Error processing queued operations for {username}"+ )+# Handle CORS preflight requests@app.before_requestdef handle_preflight():diff --git a/src/local_deep_research/web/auth/database_middleware.py b/src/local_deep_research/web/auth/database_middleware.pyindex 002655c886..24cadc8525 100644--- a/src/local_deep_research/web/auth/database_middleware.py+++ b/src/local_deep_research/web/auth/database_middleware.py@@ -17,6 +17,28 @@ def ensure_user_database():# User is authenticated but database is not open# This can happen after server restart or in new worker processes+ # Check for temporary auth token (post-registration/login)+ temp_auth_token = session.get("temp_auth_token")+ if temp_auth_token:+ from ...database.temp_auth import temp_auth_store++ auth_data = temp_auth_store.retrieve_auth(temp_auth_token)+ if auth_data:+ stored_username, password = auth_data+ if stored_username == username:+ # Try to open database with retrieved password+ try:+ engine = db_manager.open_user_database(+ username, password+ )+ if engine:+ g.db_session = db_manager.get_session(username)+ # Remove token from session after use+ session.pop("temp_auth_token", None)+ return+ except Exception:+ pass+# For unencrypted databases, we can reopen without passwordif not db_manager.has_encryption:try:diff --git a/src/local_deep_research/web/auth/queue_middleware.py b/src/local_deep_research/web/auth/queue_middleware.pynew file mode 100644index 0000000000..794711c810--- /dev/null+++ b/src/local_deep_research/web/auth/queue_middleware.py@@ -0,0 +1,54 @@+"""+Middleware to process pending queue operations when user has active session.+"""++from flask import g+from loguru import logger++from ...database.encrypted_db import db_manager+from ..queue.processor import queue_processor+++def process_pending_queue_operations():+ """+ Process pending queue operations for the current user.+ This runs in request context where we have access to the encrypted database.+ """+ # Check if user is authenticated and has a database session+ if not hasattr(g, "current_user") or not g.current_user:+ return++ # g.current_user might be a string (username) or an object+ username = (+ g.current_user+ if isinstance(g.current_user, str)+ else g.current_user.username+ )++ # Check if user has an open database connection+ if username not in db_manager.connections:+ return++ # Get database session+ db_session = db_manager.get_session(username)+ if not db_session:+ return++ try:+ # Process any pending operations for this user+ started_count = queue_processor.process_pending_operations_for_user(+ username, db_session+ )++ if started_count > 0:+ logger.info(+ f"Started {started_count} queued researches for {username}"+ )++ except Exception:+ logger.exception(+ f"Error processing pending queue operations for {username}"+ )+ finally:+ if db_session:+ db_session.close()diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex 5e54cb5cd0..6e76d8e2ae 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -93,6 +93,12 @@ def login():session["username"] = usernamesession.permanent = remember+ # Store password temporarily for post-login database access+ from ...database.temp_auth import temp_auth_store++ auth_token = temp_auth_store.store_auth(username, password)+ session["temp_auth_token"] = auth_token+# Update last login in auth databaseauth_db = get_auth_db_session()user = auth_db.query(User).filter_by(username=username).first()@@ -177,6 +183,12 @@ def register():session["session_id"] = session_idsession["username"] = username+ # Store password temporarily for post-registration database access+ from ...database.temp_auth import temp_auth_store++ auth_token = temp_auth_store.store_auth(username, password)+ session["temp_auth_token"] = auth_token+logger.info(f"New user registered: {username}")flash("Registration successful! Your encrypted database has been created.",@@ -185,8 +197,8 @@ def register():return redirect(url_for("index"))- except Exception as e:- logger.error(f"Registration failed for {username}: {e}")+ except Exception:+ logger.exception(f"Registration failed for {username}")# Rollback user creation if database creation failedauth_db.rollback()diff --git a/src/local_deep_research/web/queue/manager.py b/src/local_deep_research/web/queue/manager.pyindex 5cb4368562..e2e7d748a0 100644--- a/src/local_deep_research/web/queue/manager.py+++ b/src/local_deep_research/web/queue/manager.py@@ -6,6 +6,7 @@ from sqlalchemy.orm import sessionmakerfrom ...database.encrypted_db import db_managerfrom ...database.models import QueuedResearch, ResearchHistory+from .processor import queue_processorclass QueueManager:@@ -56,6 +57,10 @@ class QueueManager:logger.info(f"Added research {research_id} to queue at position {max_position + 1}")++ # Notify queue processor about the new queued research+ queue_processor.notify_research_queued(username, research_id)+return max_position + 1finally:diff --git a/src/local_deep_research/web/queue/processor.py b/src/local_deep_research/web/queue/processor.pyindex ed0563a232..2c144020de 100644--- a/src/local_deep_research/web/queue/processor.py+++ b/src/local_deep_research/web/queue/processor.py@@ -2,16 +2,18 @@import threadingimport time+import uuid+from typing import Any, Dict, Optionalfrom loguru import logger-from sqlalchemy.orm import sessionmaker+from sqlalchemy import text-from ...database.encrypted_db import db_managerfrom ...database.models import (QueuedResearch,ResearchHistory,UserActiveResearch,)+from ...database.service_db import service_dbfrom ..routes.globals import active_research, termination_flagsfrom ..services.research_service import (run_research_process,@@ -33,6 +35,7 @@ class QueueProcessor:self.running = Falseself.thread = Noneself.max_concurrent_per_user = 3+ self.pending_operations = {} # Store operations that need DB accessdef start(self):"""Start the queue processor thread"""@@ -66,36 +69,121 @@ class QueueProcessor:def _check_and_process_queue(self):"""Check for available slots and process queued researches"""- # Get all users with queued researches- for username in db_manager.connections:+ # Get all users from service database+ with service_db.get_session() as session:+ users = session.execute(+ text(+ "SELECT DISTINCT username FROM task_metadata WHERE status = 'queued'"+ )+ ).fetchall()++ for (username,) in users:try:self._process_user_queue(username)except Exception:logger.exception(f"Error processing queue for user {username}")- def _process_user_queue(self, username):- """Process the queue for a specific user"""- engine = db_manager.connections.get(username)- if not engine:+ def _process_user_queue(self, username: str):+ """Process the queue for a specific user using service database"""+ # Get queue status from service database+ queue_status = service_db.get_queue_status(username) or {+ "active_tasks": 0,+ "queued_tasks": 0,+ }++ # Calculate available slots+ available_slots = (+ self.max_concurrent_per_user - queue_status["active_tasks"]+ )++ if available_slots <= 0:return- SessionLocal = sessionmaker(bind=engine)- session = SessionLocal()+ # Get pending tasks that don't require DB access+ pending_tasks = service_db.get_pending_tasks(+ username, limit=available_slots+ )- try:- # Count active researches for this user- active_count = (- session.query(UserActiveResearch)- .filter_by(username=username, status="in_progress")- .count()- )+ # For tasks requiring DB access, we need to use a different approach+ if queue_status["queued_tasks"] > len(pending_tasks):+ # There are tasks that require DB access+ # These will be processed when the user makes a request (event-driven)+ self._register_pending_db_operation(username, available_slots)++ def _register_pending_db_operation(+ self, username: str, available_slots: int+ ):+ """Register that we need to access user's encrypted database"""+ operation_id = str(uuid.uuid4())+ self.pending_operations[operation_id] = {+ "username": username,+ "available_slots": available_slots,+ "timestamp": time.time(),+ }++ # This will be processed when user makes a request+ logger.debug(+ f"Registered pending operation {operation_id} for {username}"+ )- # Calculate available slots- available_slots = self.max_concurrent_per_user - active_count+ def process_pending_operations_for_user(+ self, username: str, db_session+ ) -> int:+ """+ Process pending operations for a user when we have database access.+ Called from request context where encrypted database is accessible.- if available_slots <= 0:- return+ Returns number of researches started.+ """+ started_count = 0++ # Find pending operations for this user+ operations_to_process = []+ for op_id, op_data in list(self.pending_operations.items()):+ if op_data["username"] == username:+ operations_to_process.append((op_id, op_data))++ if not operations_to_process:+ return 0++ for op_id, op_data in operations_to_process:+ try:+ operation_type = op_data.get("operation_type", "queue_process")+ if operation_type == "queue_process":+ # Process queued researches with database access+ count = self._process_queued_researches_with_db(+ db_session, username, op_data["available_slots"]+ )+ started_count += count++ elif operation_type == "cleanup":+ # Process cleanup operation+ self._process_cleanup_operation(db_session, op_data)++ elif operation_type == "error_update":+ # Process error update+ self._process_error_update(db_session, op_data)++ elif operation_type == "progress_update":+ # Process progress update+ self._process_progress_update(db_session, op_data)++ # Remove processed operation+ del self.pending_operations[op_id]++ except Exception:+ logger.exception(f"Error processing operation {op_id}")++ return started_count++ def _process_queued_researches_with_db(+ self, session, username: str, available_slots: int+ ) -> int:+ """Process queued researches when we have database access"""+ started_count = 0++ try:# Get queued researches ordered by positionqueued = (session.query(QueuedResearch)@@ -120,9 +208,15 @@ class QueueProcessor:session.delete(queued_research)session.commit()+ # Update service database+ service_db.update_task_status(+ queued_research.research_id, "processing"+ )+logger.info(f"Started queued research {queued_research.research_id} for user {username}")+ started_count += 1except Exception:logger.exception(@@ -132,8 +226,19 @@ class QueueProcessor:queued_research.is_processing = Falsesession.commit()- finally:- session.close()+ # Update service database+ service_db.update_task_status(+ queued_research.research_id,+ "failed",+ error_message="Failed to start research",+ )++ except Exception:+ logger.exception(+ f"Error accessing encrypted database for {username}"+ )++ return started_countdef _start_queued_research(self, session, username, queued_research):"""Start a queued research"""@@ -212,6 +317,279 @@ class QueueProcessor:f"Research {queued_research.research_id} started from queue")+ def notify_research_queued(self, username: str, research_id: str):+ """+ Notify the queue processor that a new research was queued.+ Updates the service database.+ """+ service_db.add_task_metadata(+ task_id=research_id,+ username=username,+ task_type="research",+ requires_db_access=True,+ )++ def notify_research_completed(self, username: str, research_id: str):+ """+ Notify the queue processor that a research completed.+ Updates the service database.+ """+ service_db.update_task_status(research_id, "completed")++ # Update queue counts+ with service_db.get_session() as session:+ queue_status = session.execute(+ text(+ "SELECT active_tasks, queued_tasks FROM queue_status WHERE username = :username"+ ),+ {"username": username},+ ).fetchone()++ if queue_status:+ active = max(0, queue_status[0] - 1)+ queued = queue_status[1]+ service_db.update_queue_status(username, active, queued)++ def queue_cleanup_operation(+ self, username: str, research_id: str, operation_type: str = "cleanup"+ ):+ """+ Queue a cleanup operation that needs database access.+ This will be processed when the user makes their next request.++ Args:+ username: The username+ research_id: The research ID+ operation_type: Type of operation (cleanup, error_update, etc.)+ """+ operation_id = str(uuid.uuid4())+ self.pending_operations[operation_id] = {+ "username": username,+ "operation_type": operation_type,+ "research_id": research_id,+ "timestamp": time.time(),+ }+ logger.info(+ f"Queued {operation_type} operation for research {research_id}"+ )++ def queue_error_update(+ self,+ username: str,+ research_id: str,+ status: str,+ error_message: str,+ metadata: Dict[str, Any],+ completed_at: str,+ report_path: Optional[str] = None,+ ):+ """+ Queue an error status update that needs database access.++ Args:+ username: The username+ research_id: The research ID+ status: The status to set (failed, suspended, etc.)+ error_message: The error message+ metadata: Research metadata+ completed_at: Completion timestamp+ report_path: Optional path to error report+ """+ operation_id = str(uuid.uuid4())+ self.pending_operations[operation_id] = {+ "username": username,+ "operation_type": "error_update",+ "research_id": research_id,+ "status": status,+ "error_message": error_message,+ "metadata": metadata,+ "completed_at": completed_at,+ "report_path": report_path,+ "timestamp": time.time(),+ }+ logger.info(+ f"Queued error update for research {research_id} with status {status}"+ )++ def queue_progress_update(+ self, username: str, research_id: str, progress: float+ ):+ """+ Queue a progress update that needs database access.++ Args:+ username: The username+ research_id: The research ID+ progress: The progress value (0-100)+ """+ operation_id = str(uuid.uuid4())+ self.pending_operations[operation_id] = {+ "username": username,+ "operation_type": "progress_update",+ "research_id": research_id,+ "progress": progress,+ "timestamp": time.time(),+ }+ logger.debug(+ f"Queued progress update for research {research_id}: {progress}%"+ )++ def _process_cleanup_operation(self, db_session, op_data: Dict[str, Any]):+ """+ Process a cleanup operation with database access.++ Args:+ db_session: The database session+ op_data: The operation data+ """+ research_id = op_data["research_id"]+ username = op_data["username"]++ try:+ # Get the current status from the database+ research = (+ db_session.query(ResearchHistory)+ .filter(ResearchHistory.id == research_id)+ .first()+ )++ if not research:+ logger.error(+ f"Research with ID {research_id} not found during cleanup"+ )+ return++ current_status = research.status++ # Clean up UserActiveResearch record+ from ...database.models import UserActiveResearch++ active_record = (+ db_session.query(UserActiveResearch)+ .filter_by(username=username, research_id=research_id)+ .first()+ )++ if active_record:+ logger.info(+ f"Cleaning up active research {research_id} for user {username} "+ f"(was started at {active_record.started_at})"+ )+ db_session.delete(active_record)+ db_session.commit()+ logger.info(+ f"Cleaned up active research record for user {username}"+ )+ else:+ logger.warning(+ f"No active research record found to clean up for {research_id} / {username}"+ )++ # Notify service database that research completed+ self.notify_research_completed(username, research_id)++ except Exception:+ logger.exception(+ f"Error processing cleanup operation for research {research_id}"+ )+ db_session.rollback()++ def _process_error_update(self, db_session, op_data: Dict[str, Any]):+ """+ Process an error update operation with database access.++ Args:+ db_session: The database session+ op_data: The operation data+ """+ research_id = op_data["research_id"]++ try:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )++ if not research:+ logger.error(+ f"Research with ID {research_id} not found for error update"+ )+ return++ # Calculate duration+ from ..models.database import calculate_duration++ duration_seconds = calculate_duration(research.created_at)++ # Update the ResearchHistory object+ research.status = op_data["status"]+ research.completed_at = op_data["completed_at"]+ research.duration_seconds = duration_seconds+ research.research_meta = op_data["metadata"]++ # Add error report path if available+ if op_data.get("report_path"):+ research.report_path = op_data["report_path"]++ db_session.commit()++ logger.info(+ f"Updated research {research_id} with status '{op_data['status']}' "+ f"and error: {op_data['error_message']}"+ )++ # Update service database+ service_db.update_task_status(+ research_id,+ op_data["status"],+ error_message=op_data["error_message"],+ )++ except Exception:+ logger.exception(+ f"Error processing error update for research {research_id}"+ )+ db_session.rollback()++ def _process_progress_update(self, db_session, op_data: Dict[str, Any]):+ """+ Process a progress update operation with database access.++ Args:+ db_session: The database session+ op_data: The operation data+ """+ research_id = op_data["research_id"]+ progress = op_data["progress"]++ try:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )++ if not research:+ logger.error(+ f"Research with ID {research_id} not found for progress update"+ )+ return++ # Update progress+ research.progress = progress+ db_session.commit()++ logger.debug(+ f"Updated research {research_id} progress to {progress}%"+ )++ except Exception:+ logger.exception(+ f"Error processing progress update for research {research_id}"+ )+ db_session.rollback()+# Global queue processor instancequeue_processor = QueueProcessor()diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 142e0b86a9..eb96f0b794 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -18,14 +18,13 @@ from loguru import loggerfrom sqlalchemy import funcfrom ...config.paths import get_research_outputs_directory-from ...database.encrypted_db import db_managerfrom ...database.models import (QueuedResearch,ResearchHistory,ResearchLog,UserActiveResearch,)-from ...utilities.db_utils import get_db_session+from ...database.session_context import get_user_db_sessionfrom ..auth.decorators import login_requiredfrom ..models.database import calculate_durationfrom ..services.research_service import (@@ -183,38 +182,40 @@ def start_research():3 # Allow up to 3 concurrent researches per user)- # Get a fresh session to check active researches- from sqlalchemy.orm import sessionmaker+ # Get a fresh session to check active researches using centralized pattern+ from ...database.session_context import get_user_db_session- check_session = sessionmaker(bind=db_manager.connections[username])()try:- # Count active researches for this user- active_count = (- check_session.query(UserActiveResearch)- .filter_by(username=username, status="in_progress")- .count()- )-- # Debug logging- logger.info(- f"Active research count for {username}: {active_count}/{max_concurrent_researches}"- )+ with get_user_db_session(username) as check_session:+ # Count active researches for this user+ active_count = (+ check_session.query(UserActiveResearch)+ .filter_by(username=username, status="in_progress")+ .count()+ )- # Also log all active researches- active_researches = (- check_session.query(UserActiveResearch)- .filter_by(username=username, status="in_progress")- .all()- )- for ar in active_researches:+ # Debug logginglogger.info(- f" - Active: {ar.research_id} (started: {ar.started_at})"+ f"Active research count for {username}: {active_count}/{max_concurrent_researches}")- should_queue = active_count >= max_concurrent_researches- logger.info(f"Should queue new research: {should_queue}")- finally:- check_session.close()+ # Also log all active researches+ active_researches = (+ check_session.query(UserActiveResearch)+ .filter_by(username=username, status="in_progress")+ .all()+ )+ for ar in active_researches:+ logger.info(+ f" - Active: {ar.research_id} (started: {ar.started_at})"+ )++ should_queue = active_count >= max_concurrent_researches+ logger.info(f"Should queue new research: {should_queue}")+ except Exception as e:+ logger.exception(f"Failed to check active researches: {e}")+ # Default to not queueing if we can't check+ should_queue = False# Create a record in the database with explicit UTC timestampimport uuid@@ -246,184 +247,201 @@ def start_research():# Get complete settings snapshot for this researchtry:- from ...utilities.db_utils import get_db_session- from ..services.settings_service import get_all_settings-- # Get a fresh session for settings retrieval- settings_session = get_db_session()- try:- # Get all current settings as a snapshot- all_settings = get_all_settings(db_session=settings_session)+ from ...database.session_context import get_user_db_session+ from ..services.settings_manager import SettingsManager++ # Use centralized session context for settings retrieval+ username = session.get("username")+ if username:+ with get_user_db_session(username) as settings_session:+ if settings_session:+ # Create SettingsManager with the fresh session+ settings_manager = SettingsManager(+ db_session=settings_session+ )+ # Get all current settings as a snapshot+ all_settings = settings_manager.get_all_settings()- # Add settings snapshot to metadata- research_meta["settings_snapshot"] = all_settings- logger.info(- f"Captured {len(all_settings)} settings for research {research_id}"- )- finally:- settings_session.close()+ # Add settings snapshot to metadata+ research_meta["settings_snapshot"] = all_settings+ logger.info(+ f"Captured {len(all_settings)} settings for research {research_id}"+ )+ else:+ logger.warning(+ "Could not get database session for settings snapshot"+ )+ else:+ logger.warning("No username in session for settings snapshot")except Exception as e:logger.warning(f"Could not capture settings snapshot: {e}")# Continue without snapshot - submission parameters are still saved- # Get a fresh database session for the current user- # Don't use g.db_session to avoid transaction conflicts+ # Get a fresh database session for the current user using centralized patternusername = session.get("username")if not username:return jsonify({"status": "error", "message": "Not authenticated"}), 401- # Get the engine and create a fresh session- if username not in db_manager.connections:- return jsonify(- {"status": "error", "message": "Database connection not available"}- ), 500-- engine = db_manager.connections[username]- from sqlalchemy.orm import sessionmaker-- SessionLocal = sessionmaker(bind=engine)- db_session = SessionLocal()-try:- # Determine initial status based on whether we need to queue- initial_status = "queued" if should_queue else "in_progress"-- research = ResearchHistory(- id=research_id, # Set UUID as primary key- query=query,- mode=mode,- status=initial_status,- created_at=created_at,- progress_log=[{"time": created_at, "progress": 0}],- research_meta=research_meta,- )- db_session.add(research)- db_session.commit()- logger.info(- f"Created research entry with UUID: {research_id}, status: {initial_status}"- )-- if should_queue:- # Add to queue instead of starting immediately- # Get the next position in queue for this user- max_position = (- db_session.query(func.max(QueuedResearch.position))- .filter_by(username=username)- .scalar()- or 0- )+ # Use context manager to ensure proper session handling+ with get_user_db_session(username) as db_session:+ # Determine initial status based on whether we need to queue+ initial_status = "queued" if should_queue else "in_progress"- queued_record = QueuedResearch(- username=username,- research_id=research_id,+ research = ResearchHistory(+ id=research_id, # Set UUID as primary keyquery=query,mode=mode,- settings_snapshot=research_meta,- position=max_position + 1,+ status=initial_status,+ created_at=created_at,+ progress_log=[{"time": created_at, "progress": 0}],+ research_meta=research_meta,)- db_session.add(queued_record)+ db_session.add(research)db_session.commit()logger.info(- f"Queued research {research_id} at position {max_position + 1} for user {username}"+ f"Created research entry with UUID: {research_id}, status: {initial_status}")- # Return queued status- return jsonify(- {- "status": "queued",- "research_id": research_id,- "queue_position": max_position + 1,- "message": f"Your research has been queued. Position in queue: {max_position + 1}",- }- )- else:- # Start immediately- # Create active research tracking record- import threading-- active_record = UserActiveResearch(- username=username,- research_id=research_id,- status="in_progress",- thread_id=str(threading.current_thread().ident),- settings_snapshot=research_meta,- )- db_session.add(active_record)- db_session.commit()- logger.info(f"Created active research record for user {username}")+ if should_queue:+ # Add to queue instead of starting immediately+ # Get the next position in queue for this user+ max_position = (+ db_session.query(func.max(QueuedResearch.position))+ .filter_by(username=username)+ .scalar()+ or 0+ )- # Double-check the count after committing to handle race conditions- recheck_session = SessionLocal()- try:- final_count = (- recheck_session.query(UserActiveResearch)- .filter_by(username=username, status="in_progress")- .count()+ queued_record = QueuedResearch(+ username=username,+ research_id=research_id,+ query=query,+ mode=mode,+ settings_snapshot=research_meta,+ position=max_position + 1,)+ db_session.add(queued_record)+ db_session.commit()logger.info(- f"Final active count after commit: {final_count}/{max_concurrent_researches}"+ f"Queued research {research_id} at position {max_position + 1} for user {username}")- if final_count > max_concurrent_researches:- # We exceeded the limit due to a race condition- # Remove this record and queue instead- logger.warning(- f"Race condition detected: {final_count} > {max_concurrent_researches}, moving to queue"- )- db_session.delete(active_record)- db_session.commit()+ # Return queued status+ return jsonify(+ {+ "status": "queued",+ "research_id": research_id,+ "queue_position": max_position + 1,+ "message": f"Your research has been queued. Position in queue: {max_position + 1}",+ }+ )+ else:+ # Start immediately+ # Create active research tracking record+ import threading++ active_record = UserActiveResearch(+ username=username,+ research_id=research_id,+ status="in_progress",+ thread_id=str(threading.current_thread().ident),+ settings_snapshot=research_meta,+ )+ db_session.add(active_record)+ db_session.commit()+ logger.info(+ f"Created active research record for user {username}"+ )- # Add to queue- max_position = (- db_session.query(- func.max(QueuedResearch.position)+ # Double-check the count after committing to handle race conditions+ # Use another context manager for the recheck+ try:+ with get_user_db_session(username) as recheck_session:+ final_count = (+ recheck_session.query(UserActiveResearch)+ .filter_by(username=username, status="in_progress")+ .count()+ )+ logger.info(+ f"Final active count after commit: {final_count}/{max_concurrent_researches}")- .filter_by(username=username)- .scalar()- or 0- )-- queued_record = QueuedResearch(- username=username,- research_id=research_id,- query=query,- mode=mode,- settings_snapshot=research_meta,- position=max_position + 1,- )- db_session.add(queued_record)- # Update research status to queued- research.status = "queued"- db_session.commit()-- return jsonify(- {- "status": "queued",- "research_id": research_id,- "queue_position": max_position + 1,- "message": f"Your research has been queued due to concurrent limit. Position in queue: {max_position + 1}",- }- )- finally:- recheck_session.close()+ if final_count > max_concurrent_researches:+ # We exceeded the limit due to a race condition+ # Remove this record and queue instead+ logger.warning(+ f"Race condition detected: {final_count} > {max_concurrent_researches}, moving to queue"+ )+ db_session.delete(active_record)+ db_session.commit()++ # Add to queue+ max_position = (+ db_session.query(+ func.max(QueuedResearch.position)+ )+ .filter_by(username=username)+ .scalar()+ or 0+ )++ queued_record = QueuedResearch(+ username=username,+ research_id=research_id,+ query=query,+ mode=mode,+ settings_snapshot=research_meta,+ position=max_position + 1,+ )+ db_session.add(queued_record)++ # Update research status to queued+ research.status = "queued"+ db_session.commit()++ return jsonify(+ {+ "status": "queued",+ "research_id": research_id,+ "queue_position": max_position + 1,+ "message": f"Your research has been queued due to concurrent limit. Position in queue: {max_position + 1}",+ }+ )+ except Exception as e:+ logger.warning(f"Could not recheck active count: {e}")except Exception as e:logger.exception(f"Failed to create research entry: {e}")- try:- db_session.rollback()- except Exception:- # Session might be in invalid state- passreturn jsonify({"status": "error", "message": "Failed to create research entry"}), 500- finally:- # Always close the session- db_session.close()# Only start the research if not queuedif not should_queue:+ # Save the research strategy to the database before starting the thread+ try:+ from ..services.research_service import save_research_strategy++ save_research_strategy(research_id, strategy, username=username)+ except Exception as e:+ logger.warning(f"Could not save research strategy: {e}")++ # Debug logging for settings snapshot+ snapshot_data = research_meta.get("settings_snapshot", {})+ logger.debug(+ f"Settings snapshot being passed to thread: {snapshot_data}"+ )+ logger.debug(+ f"Settings snapshot keys: {list(snapshot_data.keys()) if snapshot_data else 'None'}"+ )+ if "search.tool" in snapshot_data:+ logger.debug(+ f"search.tool in snapshot: {snapshot_data['search.tool']}"+ )+ else:+ logger.debug("search.tool NOT in snapshot")+# Start the research process with the selected parametersresearch_thread = start_research_process(research_id,@@ -442,24 +460,22 @@ def start_research():iterations=iterations,questions_per_iteration=questions_per_iteration,strategy=strategy,- settings_snapshot=research_meta.get(- "settings_snapshot", {}- ), # Pass complete settings+ settings_snapshot=snapshot_data, # Pass complete settings)# Update the active research record with the actual thread ID- thread_session = sessionmaker(bind=db_manager.connections[username])()try:- active_record = (- thread_session.query(UserActiveResearch)- .filter_by(username=username, research_id=research_id)- .first()- )- if active_record:- active_record.thread_id = str(research_thread.ident)- thread_session.commit()- finally:- thread_session.close()+ with get_user_db_session(username) as thread_session:+ active_record = (+ thread_session.query(UserActiveResearch)+ .filter_by(username=username, research_id=research_id)+ .first()+ )+ if active_record:+ active_record.thread_id = str(research_thread.ident)+ thread_session.commit()+ except Exception as e:+ logger.warning(f"Could not update thread ID: {e}")return jsonify({"status": "success", "research_id": research_id})@@ -468,184 +484,213 @@ def start_research():@login_requireddef terminate_research(research_id):"""Terminate an in-progress research process"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401# Check if the research exists and is in progress- db_session = get_db_session()- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )+ try:+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )- if not research:- db_session.close()- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404+ if not research:+ return jsonify(+ {"status": "error", "message": "Research not found"}+ ), 404- status = research.status+ status = research.status- # If it's not in progress, return an error- if status != "in_progress":- db_session.close()- return (- jsonify(- {"status": "error", "message": "Research is not in progress"}- ),- 400,- )+ # If it's not in progress, return an error+ if status != "in_progress":+ return (+ jsonify(+ {+ "status": "error",+ "message": "Research is not in progress",+ }+ ),+ 400,+ )- # Check if it's in the active_research dict- if research_id not in active_research:- # Update the status in the database- research.status = "suspended"- db_session.commit()- db_session.close()- return jsonify({"status": "success", "message": "Research terminated"})-- # Set the termination flag- termination_flags[research_id] = True-- # Log the termination request - using UTC timestamp- timestamp = datetime.utcnow().isoformat()- termination_message = "Research termination requested by user"- current_progress = active_research[research_id]["progress"]-- # Create log entry- log_entry = {- "time": timestamp,- "message": termination_message,- "progress": current_progress,- "metadata": {"phase": "termination"},- }+ # Check if it's in the active_research dict+ if research_id not in active_research:+ # Update the status in the database+ research.status = "suspended"+ db_session.commit()+ return jsonify(+ {"status": "success", "message": "Research terminated"}+ )- # Add to in-memory log- active_research[research_id]["log"].append(log_entry)+ # Set the termination flag+ termination_flags[research_id] = True- # Add to database log- logger.log("MILESTONE", f"Research ended: {termination_message}")+ # Log the termination request - using UTC timestamp+ timestamp = datetime.utcnow().isoformat()+ termination_message = "Research termination requested by user"+ current_progress = active_research[research_id]["progress"]- # Update the log in the database- if research.progress_log:- try:- if isinstance(research.progress_log, str):- current_log = json.loads(research.progress_log)+ # Create log entry+ log_entry = {+ "time": timestamp,+ "message": termination_message,+ "progress": current_progress,+ "metadata": {"phase": "termination"},+ }++ # Add to in-memory log+ active_research[research_id]["log"].append(log_entry)++ # Add to database log+ logger.log("MILESTONE", f"Research ended: {termination_message}")++ # Update the log in the database+ if research.progress_log:+ try:+ if isinstance(research.progress_log, str):+ current_log = json.loads(research.progress_log)+ else:+ current_log = research.progress_log+ except Exception:+ current_log = []else:- current_log = research.progress_log- except Exception:- current_log = []- else:- current_log = []-- current_log.append(log_entry)- research.progress_log = current_log- research.status = "suspended"- db_session.commit()- db_session.close()-- # Emit a socket event for the termination request- try:- event_data = {- "status": "suspended", # Changed from 'terminating' to 'suspended'- "message": "Research was suspended by user request",- }+ current_log = []- from ..services.socket_service import emit_socket_event+ current_log.append(log_entry)+ research.progress_log = current_log+ research.status = "suspended"+ db_session.commit()- emit_socket_event(f"research_progress_{research_id}", event_data)+ # Emit a socket event for the termination request+ try:+ event_data = {+ "status": "suspended", # Changed from 'terminating' to 'suspended'+ "message": "Research was suspended by user request",+ }- except Exception:- logger.exception("Socket emit error (non-critical)")+ from ..services.socket_service import emit_socket_event- return jsonify(- {"status": "success", "message": "Research termination requested"}- )+ emit_socket_event(+ f"research_progress_{research_id}", event_data+ )++ except Exception:+ logger.exception("Socket emit error (non-critical)")++ return jsonify(+ {+ "status": "success",+ "message": "Research termination requested",+ }+ )+ except Exception as e:+ logger.exception(f"Error terminating research: {e}")+ return jsonify(+ {"status": "error", "message": "Failed to terminate research"}+ ), 500@research_bp.route("/api/delete/<string:research_id>", methods=["DELETE"])@login_requireddef delete_research(research_id):"""Delete a research record"""- db_session = get_db_session()- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401- if not research:- db_session.close()- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404+ try:+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )- status = research.status- report_path = research.report_path+ if not research:+ return jsonify(+ {"status": "error", "message": "Research not found"}+ ), 404- # Don't allow deleting research in progress- if status == "in_progress" and research_id in active_research:- db_session.close()- return (- jsonify(- {- "status": "error",- "message": "Cannot delete research that is in progress",- }- ),- 400,- )+ status = research.status+ report_path = research.report_path- # Delete report file if it exists- if report_path and os.path.exists(report_path):- try:- os.remove(report_path)- except Exception:- logger.exception("Error removing report file")+ # Don't allow deleting research in progress+ if status == "in_progress" and research_id in active_research:+ return (+ jsonify(+ {+ "status": "error",+ "message": "Cannot delete research that is in progress",+ }+ ),+ 400,+ )++ # Delete report file if it exists+ if report_path and os.path.exists(report_path):+ try:+ os.remove(report_path)+ except Exception:+ logger.exception("Error removing report file")- # Delete the database record- db_session.delete(research)- db_session.commit()- db_session.close()+ # Delete the database record+ db_session.delete(research)+ db_session.commit()- return jsonify({"status": "success"})+ return jsonify({"status": "success"})+ except Exception as e:+ logger.exception(f"Error deleting research: {e}")+ return jsonify(+ {"status": "error", "message": "Failed to delete research"}+ ), 500@research_bp.route("/api/clear_history", methods=["POST"])@login_requireddef clear_history():"""Clear all research history"""- try:- db_session = get_db_session()-- # Get all research records first to clean up files- research_records = db_session.query(ResearchHistory).all()-- # Clean up report files- for research in research_records:- # Skip active research- if research.id in active_research:- continue-- # Delete report file if it exists- if research.report_path and os.path.exists(research.report_path):- try:- os.remove(research.report_path)- except Exception:- logger.exception("Error removing report file")+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401- # Delete records from the database, except active research- if active_research:- db_session.query(ResearchHistory).filter(- ~ResearchHistory.id.in_(list(active_research.keys()))- ).delete(synchronize_session=False)- else:- db_session.query(ResearchHistory).delete(synchronize_session=False)+ try:+ with get_user_db_session(username) as db_session:+ # Get all research records first to clean up files+ research_records = db_session.query(ResearchHistory).all()++ # Clean up report files+ for research in research_records:+ # Skip active research+ if research.id in active_research:+ continue++ # Delete report file if it exists+ if research.report_path and os.path.exists(+ research.report_path+ ):+ try:+ os.remove(research.report_path)+ except Exception:+ logger.exception("Error removing report file")++ # Delete records from the database, except active research+ if active_research:+ db_session.query(ResearchHistory).filter(+ ~ResearchHistory.id.in_(list(active_research.keys()))+ ).delete(synchronize_session=False)+ else:+ db_session.query(ResearchHistory).delete(+ synchronize_session=False+ )- db_session.commit()- db_session.close()+ db_session.commit()- return jsonify({"status": "success"})+ return jsonify({"status": "success"})except Exception as e:logger.exception("Error clearing history")- if db_session:- db_session.rollback()- db_session.close()return jsonify({"status": "error", "message": str(e)}), 500@@ -725,52 +770,52 @@ def save_raw_config():@login_requireddef get_history():"""Get research history"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401+try:- db_session = get_db_session()+ with get_user_db_session(username) as db_session:+ # Query all research history ordered by created_at+ research_records = (+ db_session.query(ResearchHistory)+ .order_by(ResearchHistory.created_at.desc())+ .all()+ )- # Query all research history ordered by created_at- research_records = (- db_session.query(ResearchHistory)- .order_by(ResearchHistory.created_at.desc())- .all()- )+ history_items = []+ for research in research_records:+ # Calculate duration if completed+ duration_seconds = None+ if research.completed_at and research.created_at:+ try:+ duration_seconds = calculate_duration(+ research.created_at, research.completed_at+ )+ except Exception:+ logger.exception("Error calculating duration")- history_items = []- for research in research_records:- # Calculate duration if completed- duration_seconds = None- if research.completed_at and research.created_at:- try:- duration_seconds = calculate_duration(- research.created_at, research.completed_at- )- except Exception:- logger.exception("Error calculating duration")-- # Create a history item- item = {- "id": research.id,- "query": research.query,- "mode": research.mode,- "status": research.status,- "created_at": research.created_at,- "completed_at": research.completed_at,- "duration_seconds": duration_seconds,- "report_path": research.report_path,- }+ # Create a history item+ item = {+ "id": research.id,+ "query": research.query,+ "mode": research.mode,+ "status": research.status,+ "created_at": research.created_at,+ "completed_at": research.completed_at,+ "duration_seconds": duration_seconds,+ "report_path": research.report_path,+ }- # Add title if it exists- if hasattr(research, "title") and research.title is not None:- item["title"] = research.title+ # Add title if it exists+ if hasattr(research, "title") and research.title is not None:+ item["title"] = research.title- history_items.append(item)+ history_items.append(item)- db_session.close()- return jsonify({"status": "success", "items": history_items})+ return jsonify({"status": "success", "items": history_items})except Exception as e:logger.exception("Error getting history")- if db_session:- db_session.close()return jsonify({"status": "error", "message": str(e)}), 500@@ -778,31 +823,35 @@ def get_history():@login_requireddef get_research_details(research_id):"""Get full details of a research using ORM"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401+try:- db_session = get_db_session()- research = (- db_session.query(ResearchHistory)- .filter(ResearchHistory.id == research_id)- .first()- )+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter(ResearchHistory.id == research_id)+ .first()+ )- if not research:- return jsonify({"error": "Research not found"}), 404+ if not research:+ return jsonify({"error": "Research not found"}), 404- return jsonify(- {- "id": research.id,- "query": research.query,- "status": research.status,- "progress": research.progress,- "progress_percentage": research.progress or 0,- "mode": research.mode,- "created_at": research.created_at,- "completed_at": research.completed_at,- "report_path": research.report_path,- "metadata": research.research_meta,- }- )+ return jsonify(+ {+ "id": research.id,+ "query": research.query,+ "status": research.status,+ "progress": research.progress,+ "progress_percentage": research.progress or 0,+ "mode": research.mode,+ "created_at": research.created_at,+ "completed_at": research.completed_at,+ "report_path": research.report_path,+ "metadata": research.research_meta,+ }+ )except Exception as e:logger.exception(f"Error getting research details: {e!s}")return jsonify({"error": "An internal error has occurred"}), 500@@ -812,10 +861,13 @@ def get_research_details(research_id):@login_requireddef get_research_logs(research_id):"""Get logs for a specific research"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401+try:# First check if the research exists- db_session = get_db_session()- with db_session:+ with get_user_db_session(username) as db_session:research = (db_session.query(ResearchHistory).filter_by(id=research_id)@@ -854,56 +906,62 @@ def get_research_logs(research_id):@login_requireddef get_research_report(research_id):"""Get the research report content"""- session = get_db_session()+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401+try:- # Query using ORM- research = (- session.query(ResearchHistory).filter_by(id=research_id).first()- )+ with get_user_db_session(username) as db_session:+ # Query using ORM+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )- if research is None:- return jsonify({"error": "Research not found"}), 404+ if research is None:+ return jsonify({"error": "Research not found"}), 404- # Parse metadata if it exists- metadata = research.research_meta- # Check if report file exists- if not research.report_path or not os.path.exists(research.report_path):- return jsonify({"error": "Report file not found"}), 404+ # Parse metadata if it exists+ metadata = research.research_meta+ # Check if report file exists+ if not research.report_path or not os.path.exists(+ research.report_path+ ):+ return jsonify({"error": "Report file not found"}), 404- # Read the report content- try:- with open(research.report_path, "r", encoding="utf-8") as f:- content = f.read()- except Exception as e:- logger.exception(- f"Error reading report file {research.report_path}: {e}"- )- return jsonify({"error": "Error reading report file"}), 500+ # Read the report content+ try:+ with open(research.report_path, "r", encoding="utf-8") as f:+ content = f.read()+ except Exception as e:+ logger.exception(+ f"Error reading report file {research.report_path}: {e}"+ )+ return jsonify({"error": "Error reading report file"}), 500- # Return the report data- return jsonify(- {- "content": content,- "metadata": {- "query": research.query,- "mode": research.mode if research.mode else None,- "created_at": research.created_at- if research.created_at- else None,- "completed_at": research.completed_at- if research.completed_at- else None,- "report_path": research.report_path,- **metadata,- },- }- )+ # Return the report data+ return jsonify(+ {+ "content": content,+ "metadata": {+ "query": research.query,+ "mode": research.mode if research.mode else None,+ "created_at": research.created_at+ if research.created_at+ else None,+ "completed_at": research.completed_at+ if research.completed_at+ else None,+ "report_path": research.report_path,+ **metadata,+ },+ }+ )except Exception as e:logger.exception(f"Error getting research report: {e!s}")return jsonify({"error": "An internal error has occurred"}), 500- finally:- session.close()@research_bp.route(@@ -919,50 +977,57 @@ def export_research_report(research_id, format):), 400# Get research from database- session = get_db_session()+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401+try:- research = (- session.query(ResearchHistory).filter_by(id=research_id).first()- )- if not research:- return jsonify({"error": "Research not found"}), 404+ with get_user_db_session(username) as db_session:+ research = (+ db_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+ # 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+ 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: {e!s}")- return jsonify(- {- "error": f"Failed to export to {format}. Please try again later."- }- ), 500+ # 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: {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: {e!s}")+ return jsonify({"error": "An internal error has occurred"}), 500except Exception as e:- logger.exception(f"Error in export endpoint: {e!s}")+ logger.exception(f"Unexpected error in export endpoint: {e!s}")return jsonify({"error": "An internal error has occurred"}), 500@@ -970,131 +1035,137 @@ def export_research_report(research_id, format):@login_requireddef get_research_status(research_id):"""Get the status of a research process"""- db_session = get_db_session()- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )-- if research is None:- db_session.close()- return jsonify({"error": "Research not found"}), 404-- 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 display- error_info = {}- if metadata and "error" in metadata:- error_msg = metadata["error"]- error_type = "unknown"-- # Detect specific error types- if "timeout" in error_msg.lower():- error_type = "timeout"- error_info = {- "type": "timeout",- "message": "LLM service timed out during synthesis. This may be due to high server load or connectivity issues.",- "suggestion": "Try again later or use a smaller query scope.",- }- elif (- "token limit" in error_msg.lower()- or "context length" in error_msg.lower()- ):- error_type = "token_limit"- error_info = {- "type": "token_limit",- "message": "The research query exceeded the AI model's token limit during synthesis.",- "suggestion": "Try using a more specific query or reduce the research scope.",- }- elif (- "final answer synthesis fail" in error_msg.lower()- or "llm error" in error_msg.lower()- ):- error_type = "llm_error"- error_info = {- "type": "llm_error",- "message": "The AI model encountered an error during final answer synthesis.",- "suggestion": "Check that your LLM service is running correctly or try a different model.",- }- elif "ollama" in error_msg.lower():- error_type = "ollama_error"- error_info = {- "type": "ollama_error",- "message": "The Ollama service is not responding properly.",- "suggestion": "Make sure Ollama is running with 'ollama serve' and the model is downloaded.",- }- elif "connection" in error_msg.lower():- error_type = "connection"- error_info = {- "type": "connection",- "message": "Connection error with the AI service.",- "suggestion": "Check your internet connection and AI service status.",- }- elif metadata.get("solution"):- # Use the solution provided in metadata if available- error_info = {- "type": error_type,- "message": error_msg,- "suggestion": metadata.get("solution"),- }- else:- # Generic error with the original message- error_info = {- "type": error_type,- "message": error_msg,- "suggestion": "Try again with a different query or check the application logs.",- }-- # Add error_info to the response if it exists- if error_info:- metadata["error_info"] = error_info+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401- # Get the latest milestone log for this research- latest_milestone = Nonetry:- db_session = get_db_session()- with db_session:- milestone_log = (- db_session.query(ResearchLog)- .filter_by(research_id=research_id, level="MILESTONE")- .order_by(ResearchLog.timestamp.desc())+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id).first())- if milestone_log:- latest_milestone = {- "message": milestone_log.message,- "time": milestone_log.timestamp.isoformat()- if milestone_log.timestamp- else None,- "type": "MILESTONE",- }- logger.debug(- f"Found latest milestone for research {research_id}: {milestone_log.message}"- )- else:- logger.debug(- f"No milestone logs found for research {research_id}"++ if research is None:+ return jsonify({"error": "Research not found"}), 404++ 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 display+ error_info = {}+ if metadata and "error" in metadata:+ error_msg = metadata["error"]+ error_type = "unknown"++ # Detect specific error types+ if "timeout" in error_msg.lower():+ error_type = "timeout"+ error_info = {+ "type": "timeout",+ "message": "LLM service timed out during synthesis. This may be due to high server load or connectivity issues.",+ "suggestion": "Try again later or use a smaller query scope.",+ }+ elif (+ "token limit" in error_msg.lower()+ or "context length" in error_msg.lower()+ ):+ error_type = "token_limit"+ error_info = {+ "type": "token_limit",+ "message": "The research query exceeded the AI model's token limit during synthesis.",+ "suggestion": "Try using a more specific query or reduce the research scope.",+ }+ elif (+ "final answer synthesis fail" in error_msg.lower()+ or "llm error" in error_msg.lower()+ ):+ error_type = "llm_error"+ error_info = {+ "type": "llm_error",+ "message": "The AI model encountered an error during final answer synthesis.",+ "suggestion": "Check that your LLM service is running correctly or try a different model.",+ }+ elif "ollama" in error_msg.lower():+ error_type = "ollama_error"+ error_info = {+ "type": "ollama_error",+ "message": "The Ollama service is not responding properly.",+ "suggestion": "Make sure Ollama is running with 'ollama serve' and the model is downloaded.",+ }+ elif "connection" in error_msg.lower():+ error_type = "connection"+ error_info = {+ "type": "connection",+ "message": "Connection error with the AI service.",+ "suggestion": "Check your internet connection and AI service status.",+ }+ elif metadata.get("solution"):+ # Use the solution provided in metadata if available+ error_info = {+ "type": error_type,+ "message": error_msg,+ "suggestion": metadata.get("solution"),+ }+ else:+ # Generic error with the original message+ error_info = {+ "type": error_type,+ "message": error_msg,+ "suggestion": "Try again with a different query or check the application logs.",+ }++ # Add error_info to the response if it exists+ if error_info:+ metadata["error_info"] = error_info++ # Get the latest milestone log for this research+ latest_milestone = None+ try:+ milestone_log = (+ db_session.query(ResearchLog)+ .filter_by(research_id=research_id, level="MILESTONE")+ .order_by(ResearchLog.timestamp.desc())+ .first())- except Exception as e:- logger.warning(f"Error fetching latest milestone: {e!s}")-- db_session.close()- response_data = {- "status": status,- "progress": progress,- "completed_at": completed_at,- "report_path": report_path,- "metadata": metadata,- }+ if milestone_log:+ latest_milestone = {+ "message": milestone_log.message,+ "time": milestone_log.timestamp.isoformat()+ if milestone_log.timestamp+ else None,+ "type": "MILESTONE",+ }+ logger.debug(+ f"Found latest milestone for research {research_id}: {milestone_log.message}"+ )+ else:+ logger.debug(+ f"No milestone logs found for research {research_id}"+ )+ except Exception as e:+ logger.warning(f"Error fetching latest milestone: {e!s}")++ response_data = {+ "status": status,+ "progress": progress,+ "completed_at": completed_at,+ "report_path": report_path,+ "metadata": metadata,+ }- # Include latest milestone as a log_entry for frontend compatibility- if latest_milestone:- response_data["log_entry"] = latest_milestone+ # Include latest milestone as a log_entry for frontend compatibility+ if latest_milestone:+ response_data["log_entry"] = latest_milestone- return jsonify(response_data)+ return jsonify(response_data)+ except Exception as e:+ logger.exception(f"Error getting research status: {e}")+ return jsonify({"error": "Error checking research status"}), 500@research_bp.route("/api/queue/status", methods=["GET"])diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex eac066485b..07c11ecfe2 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -11,6 +11,7 @@ from flask import (jsonify,redirect,request,+ session,url_for,)from flask_wtf.csrf import generate_csrf@@ -18,8 +19,8 @@ from loguru import loggerfrom ...config.paths import get_data_directory, get_database_pathfrom ...database.models import Setting, SettingType+from ...database.session_context import get_user_db_sessionfrom ...utilities.db_utils import (- get_db_session,get_db_setting,get_settings_manager,)@@ -163,331 +164,341 @@ def settings_page():@login_requireddef save_all_settings():"""Handle saving all settings at once from the unified settings page"""- db_session = get_db_session()- # Get the settings manager but we don't need to assign it to a variable right now- # get_db_settings_manager(db_session)+ username = session.get("username")- 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 = {}+ with get_user_db_session(username) as db_session:+ # Get the settings manager but we don't need to assign it to a variable right now+ # get_db_settings_manager(db_session)- # Track changes for logging- updated_settings = []- created_settings = []+ try:+ # Process JSON data+ form_data = request.get_json()+ if not form_data:+ return (+ jsonify(+ {+ "status": "error",+ "message": "No settings data provided",+ }+ ),+ 400,+ )- # Store original values for better messaging- original_values = {}+ # Track validation errors+ validation_errors = []+ settings_by_type = {}- # 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+ # Track changes for logging+ updated_settings = []+ created_settings = []- # Get the original value- current_setting = (- db_session.query(Setting).filter(Setting.key == key).first()- )- if current_setting:- original_values[key] = current_setting.value+ # Store original values for better messaging+ original_values = {}- # Determine setting type and category- 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:- setting_type = None- category = None+ # 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- # Special handling for corrupted or empty values- if value == "[object Object]" or (- isinstance(value, str)- and value.strip() in ["{}", "[]", "{", "["]- ):- if key.startswith("report."):- value = {}+ # 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+ 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:- # 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+ setting_type = None+ category = 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("[")+ # Special handling for corrupted or empty values+ if value == "[object Object]" or (+ isinstance(value, str)+ and value.strip() in ["{}", "[]", "{", "["]):- 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 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- if is_valid:- # Save the setting using the same session- success = set_setting(key, value, db_session=db_session)- 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+ logger.warning(+ f"Corrected corrupted value for {key}: {value}")- else:- # Add to validation errors- validation_errors.append(- {- "key": key,- "name": current_setting.name,- "error": error_message,- }++ # 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)- 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"+ if is_valid:+ # Save the setting using the same session+ success = 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+ }- # Create the setting- db_setting = create_or_update_setting(new_setting)+ # 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 = 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",+ }+ )- 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(+ # Report validation errors if any+ if validation_errors:+ return (+ jsonify({- "key": key,- "name": new_setting["name"],- "error": "Failed to create setting",+ "status": "error",+ "message": "Validation errors",+ "errors": validation_errors,}- )+ ),+ 400,+ )- # Report validation errors if any- if validation_errors:- return (- jsonify(+ # 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({- "status": "error",- "message": "Validation errors",- "errors": validation_errors,+ "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,}- ),- 400,- )-- # 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()- )+ # 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:- # Get original value but comment out if not used- # old_value = original_values[key]- new_value = updated_setting.value if updated_setting else None+ # Format the message+ if key in original_values:+ # Get original value but comment out if not used+ # 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"+ # 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:- success_message = f"{name} updated"+ # 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:- 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)"-- # Check if any warning-affecting settings were changed and include warnings- response_data = {- "status": "success",- "message": success_message,- "updated": updated_settings,- "created": created_settings,- "settings": all_settings,- }+ # Multiple settings or generic message+ success_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"- warning_affecting_keys = [- "llm.provider",- "search.tool",- "search.iterations",- "search.questions_per_iteration",- "llm.local_context_window_size",- "llm.context_window_unrestricted",- "llm.context_window_size",- ]+ # Check if any warning-affecting settings were changed and include warnings+ response_data = {+ "status": "success",+ "message": success_message,+ "updated": updated_settings,+ "created": created_settings,+ "settings": all_settings,+ }- # Check if any warning-affecting settings were changed- if any(- key in warning_affecting_keys- for key in updated_settings + created_settings- ):- warnings = calculate_warnings()- response_data["warnings"] = warnings- logger.info(- f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"- )+ warning_affecting_keys = [+ "llm.provider",+ "search.tool",+ "search.iterations",+ "search.questions_per_iteration",+ "llm.local_context_window_size",+ "llm.context_window_unrestricted",+ "llm.context_window_size",+ ]- return jsonify(response_data)+ # Check if any warning-affecting settings were changed+ if any(+ key in warning_affecting_keys+ for key in updated_settings + created_settings+ ):+ warnings = calculate_warnings()+ response_data["warnings"] = warnings+ logger.info(+ f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"+ )- except Exception:- logger.exception("Error saving settings")- return (- jsonify(- {- "status": "error",- "message": "An internal error occurred while saving settings.",- }- ),- 500,- )+ return jsonify(response_data)++ except Exception:+ logger.exception("Error saving settings")+ return (+ jsonify(+ {+ "status": "error",+ "message": "An internal error occurred while saving settings.",+ }+ ),+ 500,+ )@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()+ username = session.get("username")- # Import default settings from files- try:- # Create settings manager for the temporary config- settings_mgr = get_settings_manager()- # Import settings from default files- settings_mgr.load_from_defaults_file()+ with get_user_db_session(username) as db_session:+ # Import default settings from files+ try:+ # Create settings manager for the temporary config+ settings_mgr = get_settings_manager()+ # Import settings from default files+ settings_mgr.load_from_defaults_file()- logger.info("Successfully imported settings from default files")+ logger.info("Successfully imported settings from default files")- except Exception:- logger.exception("Error importing default settings")+ except Exception:+ logger.exception("Error importing default settings")- # Fallback to predefined settings if file import fails- logger.info("Falling back to predefined settings")- # Import here to avoid circular imports- from ..database.migrations import (- setup_predefined_settings as setup_settings,- )+ # Fallback to predefined settings if file import fails+ logger.info("Falling back to predefined settings")+ # Import here to avoid circular imports+ from ..database.migrations import (+ setup_predefined_settings as setup_settings,+ )- setup_settings(db_session)+ setup_settings(db_session)- # Return success- return jsonify(- {- "status": "success",- "message": "All settings have been reset to default values",- }- )+ # Return success+ return jsonify(+ {+ "status": "success",+ "message": "All settings have been reset to default values",+ }+ )# API Routes@@ -498,31 +509,32 @@ def api_get_all_settings():try:# Get query parameterscategory = request.args.get("category")+ username = session.get("username")++ with get_user_db_session(username) as db_session:+ # Create settings manager+ settings_manager = get_settings_manager()++ # Get settings+ 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+ ]- # Create settings manager- db_session = get_db_session()- settings_manager = get_settings_manager()-- # Get settings- 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+ # Filter settings by keys+ for key, value in settings.items():+ if key in category_keys:+ filtered_settings[key] = value- settings = filtered_settings+ settings = filtered_settings- return jsonify({"status": "success", "settings": settings})+ return jsonify({"status": "success", "settings": settings})except Exception as e:logger.exception("Error getting settings")return jsonify({"error": str(e)}), 500@@ -533,40 +545,41 @@ def api_get_all_settings():def api_get_db_setting(key):"""Get a specific setting by key"""try:- db_session = get_db_session()+ username = session.get("username")# Get settingvalue = get_db_setting(key)if value is None:return jsonify({"error": f"Setting not found: {key}"}), 404- # Get additional metadata from database using the same session- db_setting = (- db_session.query(Setting).filter(Setting.key == key).first()- )+ with get_user_db_session(username) as db_session:+ # Get additional metadata from database using the same session+ 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}+ 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({"settings": setting_data})+ return jsonify({"settings": setting_data})except Exception as e:logger.exception(f"Error getting setting {key}")return jsonify({"error": str(e)}), 500@@ -586,99 +599,102 @@ def api_update_setting(key):if value is None:return jsonify({"error": "No value provided"}), 400- # Get DB session and settings manager- db_session = get_db_session()- # Only use settings_manager if needed - we don't need to assign if not used- # get_db_settings_manager(db_session)+ username = session.get("username")- # Check if setting exists- db_setting = (- db_session.query(Setting).filter(Setting.key == key).first()- )+ with get_user_db_session(username) as db_session:+ # Only use settings_manager if needed - we don't need to assign if not used+ # get_db_settings_manager(db_session)- if db_setting:- # Check if setting is editable- if not db_setting.editable:- return jsonify({"error": f"Setting {key} is not editable"}), 403+ # Check if setting exists+ db_setting = (+ db_session.query(Setting).filter(Setting.key == key).first()+ )- # Update setting using the same session- success = set_setting(key, value, db_session=db_session)- if success:- response_data = {- "message": f"Setting {key} updated successfully"- }+ 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 using the same session+ success = set_setting(key, value, db_session=db_session)+ if success:+ response_data = {+ "message": f"Setting {key} updated successfully"+ }- # If this is a key that affects warnings, include warning calculations- warning_affecting_keys = [- "llm.provider",- "search.tool",- "search.iterations",- "search.questions_per_iteration",- "llm.local_context_window_size",- "llm.context_window_unrestricted",- "llm.context_window_size",- ]+ # If this is a key that affects warnings, include warning calculations+ warning_affecting_keys = [+ "llm.provider",+ "search.tool",+ "search.iterations",+ "search.questions_per_iteration",+ "llm.local_context_window_size",+ "llm.context_window_unrestricted",+ "llm.context_window_size",+ ]- if key in warning_affecting_keys:- warnings = calculate_warnings()- response_data["warnings"] = warnings- logger.debug(- f"Setting {key} changed to {value}, calculated {len(warnings)} warnings"- )+ if key in warning_affecting_keys:+ warnings = calculate_warnings()+ response_data["warnings"] = warnings+ logger.debug(+ f"Setting {key} changed to {value}, calculated {len(warnings)} warnings"+ )- return jsonify(response_data)+ return jsonify(response_data)+ else:+ return jsonify(+ {"error": f"Failed to update setting {key}"}+ ), 500else:- 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 new setting with default metadata+ setting_dict = {+ "key": key,+ "value": value,+ "name": key.split(".")[-1].replace("_", " ").title(),+ "description": f"Setting for {key}",+ }- # Create setting- db_setting = create_or_update_setting(setting_dict)+ # 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 = 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+ 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}"}+ ), 500except Exception as e:logger.exception(f"Error updating setting {key}")return jsonify({"error": str(e)}), 500@@ -689,22 +705,28 @@ def api_update_setting(key):def api_delete_setting(key):"""Delete a setting"""try:- db_session = get_db_session()- settings_manager = get_settings_manager()+ username = session.get("username")- # 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+ with get_user_db_session(username) as db_session:+ settings_manager = get_settings_manager()- # 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+ # 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}"}+ ), 500except Exception as e:logger.exception(f"Error deleting setting {key}")return jsonify({"error": str(e)}), 500@@ -733,13 +755,14 @@ def api_import_settings():def api_get_categories():"""Get all setting categories"""try:- db_session = get_db_session()+ username = session.get("username")- # 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]+ with get_user_db_session(username) as 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})+ return jsonify({"categories": category_list})except Exception as e:logger.exception("Error getting categories")return jsonify({"error": str(e)}), 500@@ -820,7 +843,8 @@ def api_get_available_models():cache_expiry = datetime.utcnow() - timedelta(hours=24)# Get cached models from database- with get_db_session("settings_routes") as db_session:+ username = session.get("username")+ with get_user_db_session(username) as db_session:cached_models = (db_session.query(ProviderModel).filter(ProviderModel.last_updated > cache_expiry)@@ -1278,7 +1302,8 @@ def api_get_available_models():# Save fetched models to database cacheif force_refresh or providers:# We fetched fresh data, save it to database- with get_db_session("settings_routes") as db_session:+ username = session.get("username")+ with get_user_db_session(username) as db_session:try:from datetime import datetime@@ -1333,69 +1358,74 @@ def api_get_available_search_engines():"""Get available search engines"""try:# Find search engines that are set in the DB.- db_session = get_db_session()- name_settings = (- db_session.query(Setting)- .filter(Setting.type == "SEARCH")- .filter(Setting.key.startswith("search.engine"))- .filter(Setting.key.endswith(".display_name"))- ).all()-- # These should all correspond to different search engines.- engines_dict = {}- for setting in name_settings:- key_parts = setting.key.split(".")- if key_parts[2] == "auto":- # The auto engine is not in the web or local category.- engine_name = "auto"- else:- engine_name = setting.key.split(".")[3]- display_name = setting.value+ # Use centralized session pattern to ensure proper database access+ username = session.get("username")- description = (+ with get_user_db_session(username) as db_session:+ name_settings = (db_session.query(Setting)- .filter(- Setting.key- == f"search.engine.web.{engine_name}.description"- )- .first()+ .filter(Setting.type == "SEARCH")+ .filter(Setting.key.startswith("search.engine"))+ .filter(Setting.key.endswith(".display_name"))+ .all())- if description is None:- description = ""- else:- description = description.value- strengths = (- db_session.query(Setting)- .filter(- Setting.key == f"search.engine.web.{engine_name}.strengths"+ # These should all correspond to different search engines.+ engines_dict = {}+ for setting in name_settings:+ key_parts = setting.key.split(".")+ if key_parts[2] == "auto":+ # The auto engine is not in the web or local category.+ engine_name = "auto"+ else:+ engine_name = setting.key.split(".")[3]+ display_name = setting.value++ description = (+ db_session.query(Setting)+ .filter(+ Setting.key+ == f"search.engine.web.{engine_name}.description"+ )+ .first())- .first()- )- if strengths is None:- # No strengths in DB.- strengths = []- else:- strengths = strengths.value+ if description is None:+ description = ""+ else:+ description = description.value- engines_dict[engine_name] = dict(- display_name=display_name,- strengths=strengths,- description=description,- )+ strengths = (+ db_session.query(Setting)+ .filter(+ Setting.key+ == f"search.engine.web.{engine_name}.strengths"+ )+ .first()+ )+ if strengths is None:+ # No strengths in DB.+ strengths = []+ else:+ strengths = strengths.value- # Format as options for dropdown- engine_options = [- {- "value": key,- "label": engines_dict.get(key, {}).get("display_name", key),- }- for key in engines_dict- ]+ engines_dict[engine_name] = dict(+ display_name=display_name,+ strengths=strengths,+ description=description,+ )- return jsonify(- {"engines": engines_dict, "engine_options": engine_options}- )+ # Format as options for dropdown+ engine_options = [+ {+ "value": key,+ "label": engines_dict.get(key, {}).get("display_name", key),+ }+ for key in engines_dict+ ]++ return jsonify(+ {"engines": engines_dict, "engine_options": engine_options}+ )except Exception as e:logger.exception("Error getting available search engines")@@ -1478,322 +1508,332 @@ def inject_csrf_token():@login_requireddef fix_corrupted_settings():"""Fix corrupted settings in the database"""- db_session = get_db_session()+ username = session.get("username")- 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 as sql_func-- # Find keys with duplicates- duplicate_keys = (- db_session.query(Setting.key)- .group_by(Setting.key)- .having(sql_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())+ with get_user_db_session(username) as 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 as sql_func++ # Find keys with duplicates+ duplicate_keys = (+ db_session.query(Setting.key)+ .group_by(Setting.key)+ .having(sql_func.count(Setting.key) > 1).all())+ duplicate_keys = [key[0] for key in duplicate_keys]- # 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 = (+ # 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 == proper_key)- .first()+ .filter(Setting.key == key)+ .order_by(Setting.updated_at.desc())+ .all())- 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.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()+ # 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 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,+ 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())- 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.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.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.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,+ 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())- db_session.add(new_setting)- # Delete the app one- db_session.delete(setting)- fixed_scoping_issues.append(key)+ 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)- # 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+ # 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- or (- isinstance(setting.value, str)- and setting.value- in [- "{",- "[",- "{}",- "[]",- "[object Object]",- "null",- "undefined",- ]- )- or (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- # Import commented out as it's not directly used- # 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.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"- or 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" or (- setting.key == "app.enable_web"- or setting.key == "app.web_interface"+ setting.value is None+ or (+ isinstance(setting.value, str)+ and setting.value+ in [+ "{",+ "[",+ "{}",+ "[]",+ "[object Object]",+ "null",+ "undefined",+ ]+ )+ or (+ isinstance(setting.value, dict)+ and len(setting.value) == 0+ )):- 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 = {}+ is_corrupted = True++ # Skip if not corrupted+ if not is_corrupted:+ continue++ # Get default value from migrations+ # Import commented out as it's not directly used+ # 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.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"+ or 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" or (+ 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_valuefixed_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:+ # Commit changes+ if (+ fixed_settings+ or removed_duplicate_settings+ or fixed_scoping_issues+ ):+ db_session.commit()logger.info(- f"Removed {len(removed_duplicate_settings)} duplicate settings"+ f"Fixed {len(fixed_settings)} corrupted settings: {', '.join(fixed_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,- }- )+ 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"+ )- except Exception as e:- logger.exception("Error fixing corrupted settings")- db_session.rollback()- return (- jsonify(+ # Return success+ return jsonify({- "status": "error",- "message": f"Error fixing corrupted settings: {e!s}",+ "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,}- ),- 500,- )+ )++ except Exception as e:+ logger.exception("Error fixing corrupted settings")+ db_session.rollback()+ return (+ jsonify(+ {+ "status": "error",+ "message": f"Error fixing corrupted settings: {e!s}",+ }+ ),+ 500,+ )@settings_bp.route("/api/warnings", methods=["GET"])@@ -1961,7 +2001,7 @@ def get_bulk_settings():]# Fetch all settings at once- session = get_db_session()+ username = session.get("username")result = {}for key in requested:@@ -1976,8 +2016,6 @@ def get_bulk_settings():"error": "Failed to retrieve setting",}- session.close()-return jsonify({"success": True, "settings": result})except Exception:diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 1c4d656420..5a873511e2 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -17,7 +17,7 @@ from ...metrics.search_tracker import set_search_contextfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystemfrom ...text_optimization import CitationFormatter, CitationMode-from ...utilities.db_utils import get_db_session, get_db_setting+from ...utilities.db_utils import get_db_sessionfrom ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_resultsfrom ...utilities.threading_utils import thread_context, thread_with_app_context@@ -28,7 +28,10 @@ OUTPUT_DIR = get_research_outputs_directory()def get_citation_formatter():- """Get citation formatter with settings from database."""+ """Get citation formatter with settings from thread context."""+ # Import here to avoid circular imports+ from ...config.search_config import get_db_setting+citation_format = get_db_setting("report.citation_format", "domain_id_hyperlinks")@@ -304,12 +307,16 @@ def run_research_process("settings_snapshot", {}) # Complete settings snapshot- # Save the strategy to the database- logger.debug(- f"About to call save_research_strategy with research_id={research_id}, strategy={strategy}"+ # Log settings snapshot to debug+ logger.info(+ f"Settings snapshot received in thread: {settings_snapshot}")- save_research_strategy(research_id, strategy)- logger.debug("save_research_strategy call completed")+ logger.info(+ f"Settings snapshot keys: {list(settings_snapshot.keys()) if settings_snapshot else 'None'}"+ )++ # Strategy should already be saved in the database before thread starts+ logger.info(f"Research strategy: {strategy}")# Log all parameters for debugginglogger.info(@@ -330,18 +337,41 @@ def run_research_process(def __init__(self, snapshot, username):self.snapshot = snapshot or {}self.username = username+ # Extract values from setting objects if needed+ self.values = {}+ for key, setting in self.snapshot.items():+ if isinstance(setting, dict) and "value" in setting:+ # It's a full setting object, extract the value+ self.values[key] = setting["value"]+ else:+ # It's already just a value+ self.values[key] = settingdef get_setting(self, key, default=None):- """Get setting from snapshot first, then fallback to database"""- if key in self.snapshot:- return self.snapshot[key]- # Fallback to database (for backward compatibility)- from ...utilities.db_utils import get_db_setting-- return get_db_setting(key, default, username=self.username)+ """Get setting from snapshot only - no database access in threads"""+ if key in self.values:+ return self.values[key]+ # No fallback to database - threads must use snapshot only+ logger.warning(+ f"Setting '{key}' not found in snapshot, using default: {default}"+ )+ return defaultsettings_context = SettingsContext(settings_snapshot, username)+ # Debug log the extracted values+ logger.debug(+ f"SettingsContext values extracted: {settings_context.values}"+ )+ logger.debug(+ f"Search engine from context: {settings_context.get_setting('search.tool', 'NOT_FOUND')}"+ )++ # Set the settings context for this thread+ from ...config.search_config import set_settings_context++ set_settings_context(settings_context)+# Create shared research context that can be updated during researchshared_research_context = {"research_id": research_id,@@ -433,22 +463,18 @@ def run_research_process(if adjusted_progress is not None:active_research[research_id]["progress"] = adjusted_progress- # Update progress in the research_history table (for backward compatibility)- db_session = get_db_session(username)-- # Update the progress and log separately to avoid race conditions+ # Queue the progress update to be processed in main threadif adjusted_progress is not None:- try:- research = (- db_session.query(ResearchHistory)- .filter(ResearchHistory.id == research_id)- .first()+ from ..queue.processor import queue_processor++ if username:+ queue_processor.queue_progress_update(+ username, research_id, adjusted_progress+ )+ else:+ logger.warning(+ f"Cannot queue progress update for research {research_id} - no username available")- if research:- research.progress = adjusted_progress- db_session.commit()- except Exception:- logger.exception("Error updating progress")# Emit a socket eventtry:@@ -509,35 +535,37 @@ def run_research_process(f"Error setting LLM provider={model_provider}, model={model}")- # Set the progress callback in the system- system = AdvancedSearchSystem(llm=use_llm, strategy_name=strategy)- system.set_progress_callback(progress_callback)-- # Override search engine if specified+ # Create search engine first if specified, to avoid default creation without username+ use_search = Noneif search_engine:try:- # For focused-iteration strategy, don't override iterations/questions - use database settings- if strategy != "focused-iteration":- if iterations:- system.max_iterations = int(iterations)- if questions_per_iteration:- system.questions_per_iteration = int(- questions_per_iteration- )-# Create a new search object with these settings- system.search = get_search(- search_tool=search_engine, llm_instance=system.model+ use_search = get_search(+ search_tool=search_engine,+ llm_instance=use_llm,+ username=username,+ settings_snapshot=settings_snapshot,)-logger.info(- f"Successfully set search engine to: {search_engine}"+ f"Successfully created search engine: {search_engine}")except Exception:logger.exception(- f"Error setting search engine to {search_engine}"+ f"Error creating search engine {search_engine}")+ # Set the progress callback in the system+ system = AdvancedSearchSystem(+ llm=use_llm,+ search=use_search,+ strategy_name=strategy,+ max_iterations=iterations,+ questions_per_iteration=questions_per_iteration,+ username=username,+ settings_snapshot=settings_snapshot,+ )+ system.set_progress_callback(progress_callback)+# Run the searchprogress_callback("Starting research process", 5, {"phase": "init"})@@ -848,9 +876,19 @@ def run_research_process()# Export to additional formats if enabled- export_formats = get_db_setting(- "report.export_formats", ["markdown"]- )+ export_formats = [+ "markdown"+ ] # Default to markdown only for now+ # TODO: Get export formats from settings_snapshot when available+ if (+ settings_snapshot+ and "report.export_formats" in settings_snapshot+ ):+ value = settings_snapshot["report.export_formats"]+ if isinstance(value, dict) and "value" in value:+ export_formats = value["value"]+ else:+ export_formats = valueif isinstance(export_formats, str):export_formats = [export_formats]@@ -1155,6 +1193,10 @@ def run_research_process(now = datetime.utcnow()completed_at = now.isoformat()+ # TODO: Fix thread safety - cannot update database from threads+ # This needs to be moved to a queue-based system or use thread-safe messaging+ # For now, commenting out database updates to prevent SQLite thread safety errors+ """# Get the start time from the databaseduration_seconds = Nonedb_session = get_db_session(username)@@ -1186,6 +1228,34 @@ def run_research_process(research.report_path = report_path_to_savedb_session.commit()+ """++ # Queue the error update to be processed in main thread+ from ..queue.processor import queue_processor++ if username:+ # Determine report path if available+ report_path_to_queue = None+ if "report_path_to_save" in locals() and report_path_to_save:+ report_path_to_queue = report_path_to_save++ queue_processor.queue_error_update(+ username=username,+ research_id=research_id,+ status=status,+ error_message=message,+ metadata=metadata,+ completed_at=completed_at,+ report_path=report_path_to_queue,+ )+ logger.info(+ f"Queued error update for research {research_id} with status '{status}'"+ )+ else:+ logger.error(+ f"Cannot queue error update for research {research_id} - no username provided. "+ f"Status: '{status}', Message: {message}"+ )try:SocketIOService().emit_to_subscribers(@@ -1233,6 +1303,11 @@ def cleanup_research_resources(# Get the current status from the database to determine the final status messagecurrent_status = "completed" # Default++ # TODO: Fix thread safety - cannot access database from threads+ # This needs to be moved to a queue-based cleanup system that runs in the main thread+ # For now, commenting out to prevent SQLite thread safety errors+ """try:db_session = get_db_session(username)research = (@@ -1270,6 +1345,20 @@ def cleanup_research_resources(except Exception:logger.exception("Error retrieving research status during cleanup")+ """++ # Queue the database cleanup operation to be processed in main thread+ from ..queue.processor import queue_processor++ if username:+ queue_processor.queue_cleanup_operation(username, research_id)+ logger.info(+ f"Queued cleanup operation for research {research_id} (user: {username})"+ )+ else:+ logger.warning(+ f"Cannot queue cleanup for research {research_id} - no username provided"+ )# Remove from active researchif research_id in active_research:diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.pyindex 963506a65d..0529936db0 100644--- a/src/local_deep_research/web/services/settings_manager.py+++ b/src/local_deep_research/web/services/settings_manager.py@@ -66,10 +66,25 @@ class SettingsManager:self.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.")+ # Initialize settings lock as None - will be checked lazily+ self.__settings_locked = None++ @property+ def settings_locked(self) -> bool:+ """Check if settings are locked (lazy evaluation)."""+ if self.__settings_locked is None:+ try:+ self.__settings_locked = self.get_setting(+ "app.lock_settings", False+ )+ if self.settings_locked:+ logger.info(+ "Settings are locked. Disabling all settings changes."+ )+ except Exception:+ # If we can't check, assume not locked+ self.__settings_locked = False+ return self.__settings_locked@propertydef default_settings(self) -> Dict[str, Any]:@@ -232,7 +247,7 @@ class SettingsManager:"Cannot edit setting {} because no DB was provided.", key)return False- if self.__settings_locked:+ if self.settings_locked:logger.error("Cannot edit setting {} because they are locked.", key)return False@@ -313,7 +328,7 @@ class SettingsManager:step=setting.step,visible=setting.visible,editable=False- if self.__settings_locked+ if self.settings_lockedelse setting.editable,)@@ -348,7 +363,7 @@ class SettingsManager:"No database session available, cannot create/update setting")return None- if self.__settings_locked:+ if self.settings_locked:logger.error("Cannot edit settings because they are locked.")return None@@ -540,6 +555,7 @@ class SettingsManager:`settings_data`."""+ logger.debug(f"Importing {len(settings_data)} settings")for key, setting_values in settings_data.items():if not overwrite:existing_value = self.get_setting(key)@@ -555,6 +571,7 @@ class SettingsManager:if commit or delete_extra:self.db_session.commit()+ logger.info(f"Successfully imported {len(settings_data)} settings")# Emit WebSocket event for all imported settingsself._emit_settings_changed(list(settings_data.keys()))diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex fcc80e7117..f36776ab15 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -7,7 +7,6 @@ from flask_socketio import SocketIOfrom loguru import loggerfrom ...database.models import ResearchHistory-from ...utilities.db_utils import get_db_sessionfrom ..routes.globals import get_globals@@ -46,6 +45,7 @@ class SocketIOService:app: The app to bind this service to."""+ self.__app = app # Store app referenceself.__socketio = SocketIO(app,cors_allowed_origins="*",@@ -200,55 +200,45 @@ class SocketIOService:"""Handle client subscription to research updates"""research_id = data.get("research_id")if research_id:- # First check if this research is still active- db_session = get_db_session()- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )- db_session.close()+ # Skip database check from Socket.IO thread - just allow subscription+ # The client will handle invalid research IDs gracefully- # Only allow subscription to valid research- if research:- status = research.status+ # Initialize subscription set if needed+ with self.__lock:+ if research_id not in self.__socket_subscriptions:+ self.__socket_subscriptions[research_id] = set()- # Initialize subscription set if needed- with self.__lock:- if research_id not in self.__socket_subscriptions:- self.__socket_subscriptions[research_id] = set()+ # Add this client to the subscribers+ self.__socket_subscriptions[research_id].add(+ request.sid+ )+ self.__log_info(+ f"Client {request.sid} subscribed to research {research_id}"+ )- # Add this client to the subscribers- self.__socket_subscriptions[research_id].add(- request.sid- )- self.__log_info(- f"Client {request.sid} subscribed to research {research_id}"+ # Send current status immediately if available+ if active_research and research_id in active_research:+ progress = active_research[research_id]["progress"]+ latest_log = (+ active_research[research_id]["log"][-1]+ if active_research[research_id]["log"]+ else None)- # Send current status immediately if available- if active_research and research_id in active_research:- progress = active_research[research_id]["progress"]- latest_log = (- active_research[research_id]["log"][-1]- if active_research[research_id]["log"]- else None+ if latest_log:+ self.emit_socket_event(+ f"research_progress_{research_id}",+ {+ "progress": progress,+ "message": latest_log.get(+ "message", "Processing..."+ ),+ "status": "in_progress",+ "log_entry": latest_log,+ },+ room=request.sid,)-- if latest_log:- self.emit_socket_event(- f"research_progress_{research_id}",- {- "progress": progress,- "message": latest_log.get(- "message", "Processing..."- ),- "status": "in_progress",- "log_entry": latest_log,- },- room=request.sid,- )- elif status in ["completed", "failed", "suspended"]:+ elif status in ["completed", "failed", "suspended"]:# Send final status for completed researchself.emit_socket_event(f"research_progress_{research_id}",@@ -311,7 +301,7 @@ class SocketIOService:"""logger.info(f"Starting web server on {host}:{port} (debug: {debug})")self.__socketio.run(- current_app,+ self.__app, # Use stored app reference instead of current_appdebug=debug,host=host,port=port,diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex 85dfd4be35..8cb22bb976 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -32,7 +32,7 @@ window.socket = (function() {try {// Use polling only to avoid WebSocket issuessocket = io(baseUrl, {- path: '/research/socket.io',+ path: '/socket.io',reconnection: true,reconnectionDelay: 1000,reconnectionAttempts: 5,diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex 2547eb53c9..24ec0e7ad4 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -5,14 +5,17 @@ from typing import Any, Dict, Optionalfrom loguru import logger-from ..utilities.db_utils import get_db_settingfrom .retriever_registry import retriever_registryfrom .search_engine_base import BaseSearchEngine-from .search_engines_config import default_search_engine, search_config+from .search_engines_config import search_configdef create_search_engine(- engine_name: str, llm=None, **kwargs+ engine_name: str,+ llm=None,+ username: str = None,+ settings_snapshot: Dict[str, Any] = None,+ **kwargs,) -> Optional[BaseSearchEngine]:"""Create a search engine instance based on the engine name.@@ -37,21 +40,77 @@ def create_search_engine(max_results=kwargs.get("max_results", 10),)- # If engine name not found, use default- if engine_name not in search_config():+ # Extract search engine configs from settings snapshot+ if settings_snapshot:+ config = {}++ # Extract web search engines+ web_engines = {}+ for key, value in settings_snapshot.items():+ if key.startswith("search.engine.web."):+ # Extract engine name from key like "search.engine.web.searxng.class_name"+ parts = key.split(".")+ if len(parts) >= 4:+ engine_name_from_key = parts[3]+ if engine_name_from_key not in web_engines:+ web_engines[engine_name_from_key] = {}+ # Store the config value+ remaining_key = (+ ".".join(parts[4:]) if len(parts) > 4 else ""+ )+ if remaining_key:+ web_engines[engine_name_from_key][remaining_key] = (+ value.get("value")+ if isinstance(value, dict)+ else value+ )++ # Add extracted engines to config+ config.update(web_engines)++ # Also check for auto engine+ if "search.engine.auto.class_name" in settings_snapshot:+ config["auto"] = {}+ for key, value in settings_snapshot.items():+ if key.startswith("search.engine.auto."):+ remaining_key = key.replace("search.engine.auto.", "")+ config["auto"][remaining_key] = (+ value.get("value") if isinstance(value, dict) else value+ )++ logger.debug(+ f"Extracted search engines from snapshot: {list(config.keys())}"+ )+ else:+ raise RuntimeError(+ "settings_snapshot is required for search engine creation in threads"+ )++ if engine_name not in config:logger.warning(- f"Search engine '{engine_name}' not found, using default: "- f"{default_search_engine()}"+ f"Search engine '{engine_name}' not found in config, using default")- engine_name = default_search_engine()+ # Try to use 'auto' as default if available+ if "auto" in config:+ engine_name = "auto"+ else:+ logger.error(+ f"No default search engine available. Available engines: {list(config.keys())}"+ )+ return None# Get engine configuration- engine_config = search_config()[engine_name]+ engine_config = config[engine_name]# Set default max_results from config if not provided in kwargsif "max_results" not in kwargs:- max_results = get_db_setting("search.max_results", 10)- if max_results is None:+ if settings_snapshot and "search.max_results" in settings_snapshot:+ max_results = (+ settings_snapshot["search.max_results"].get("value", 20)+ if isinstance(settings_snapshot["search.max_results"], dict)+ else settings_snapshot["search.max_results"]+ )+ else:max_results = 20kwargs["max_results"] = max_results@@ -62,7 +121,9 @@ def create_search_engine(# If not found, check the database for the API keyif not api_key:- api_key = get_db_setting(f"search.engine.web.{engine_name}.api_key")+ api_key = get_db_setting(+ f"search.engine.web.{engine_name}.api_key", username=username+ )# Still try to get from engine config if not foundif not api_key:@@ -145,7 +206,9 @@ def create_search_engine(if kwargs.get("use_full_search", False) and engine_config.get("supports_full_search", False):- return _create_full_search_wrapper(engine_name, engine, llm, kwargs)+ return _create_full_search_wrapper(+ engine_name, engine, llm, kwargs, username+ )return engine@@ -155,11 +218,16 @@ def create_search_engine(def _create_full_search_wrapper(- engine_name: str, base_engine: BaseSearchEngine, llm, params: Dict[str, Any]+ engine_name: str,+ base_engine: BaseSearchEngine,+ llm,+ params: Dict[str, Any],+ username: str = None,) -> Optional[BaseSearchEngine]:"""Create a full search wrapper for the base engine if supported"""try:- engine_config = search_config()[engine_name]+ config = search_config(username=username)+ engine_config = config[engine_name]# Get full search class detailsmodule_path = engine_config.get("full_search_module")@@ -218,10 +286,8 @@ def _create_full_search_wrapper(brave_api_key = os.getenv("BRAVE_API_KEY")# If not found, check databaseif not brave_api_key:- from ..utilities.db_utils import get_db_setting-brave_api_key = get_db_setting(- "search.engine.web.brave.api_key"+ "search.engine.web.brave.api_key", username=username)if brave_api_key:@@ -278,6 +344,7 @@ def get_search(search_snippets_only: bool = False,search_language: str = "English",max_filtered_results: Optional[int] = None,+ settings_snapshot: Dict[str, Any] = None,):"""Get search tool instance based on the provided parameters.@@ -327,7 +394,9 @@ def get_search(f"Creating search engine for tool: {search_tool} with params: {params.keys()}")- engine = create_search_engine(search_tool, **params)+ engine = create_search_engine(+ search_tool, settings_snapshot=settings_snapshot, **params+ )# Add debugging to check if engine is Noneif engine is None:diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex 38d7ffa39e..07302948a7 100644--- a/src/local_deep_research/web_search_engines/search_engines_config.py+++ b/src/local_deep_research/web_search_engines/search_engines_config.py@@ -46,16 +46,18 @@ def _extract_per_engine_config(return nested_config-def search_config() -> Dict[str, Any]:+def search_config(username: str = None) -> Dict[str, Any]:"""Returns:The search engine configuration loaded from the database."""# Extract search engine definitions- config_data = get_db_setting("search.engine.web", {})+ config_data = get_db_setting("search.engine.web", {}, username=username)search_engines = _extract_per_engine_config(config_data)- search_engines["auto"] = get_db_setting("search.engine.auto", {})+ search_engines["auto"] = get_db_setting(+ "search.engine.auto", {}, username=username+ )# Add registered retrievers as available search enginesfrom .retriever_registry import retriever_registry@@ -92,7 +94,9 @@ def search_config() -> Dict[str, Any]:search_engines["elasticsearch"] = get_default_elasticsearch_config()# Register local document collections- local_collections_data = get_db_setting("search.engine.local", {})+ local_collections_data = get_db_setting(+ "search.engine.local", {}, username=username+ )local_collections_data = _extract_per_engine_config(local_collections_data)for collection, config in local_collections_data.items():@@ -121,10 +125,12 @@ def search_config() -> Dict[str, Any]:engine_config["module_path"] = get_db_setting(f"{engine_config_prefix}.module_path","local_deep_research.web_search_engines.engines.search_engine_local",+ username=username,)engine_config["class_name"] = get_db_setting(f"{engine_config_prefix}.class_name","LocalSearchEngine",+ username=username,)# Copy these specific fields to the top level if they exist@@ -143,22 +149,26 @@ def search_config() -> Dict[str, Any]:return search_engines-def default_search_engine() -> str:+def default_search_engine(username: str = None) -> str:"""Returns:The configured default search engine."""- return get_db_setting("search.engine.DEFAULT_SEARCH_ENGINE", "wikipedia")+ return get_db_setting(+ "search.engine.DEFAULT_SEARCH_ENGINE", "wikipedia", username=username+ )-def local_search_engines() -> List[str]:+def local_search_engines(username: str = None) -> List[str]:"""Returns:A list of the enabled local search engines."""- local_collections_data = get_db_setting("search.engine.local", {})+ local_collections_data = get_db_setting(+ "search.engine.local", {}, username=username+ )local_collections_data = _extract_per_engine_config(local_collections_data)# Don't include the `local_all` collection.diff --git a/tests/ui_tests/test_research_searxng.js b/tests/ui_tests/test_research_searxng.jsnew file mode 100644index 0000000000..12c7a6d1c9--- /dev/null+++ b/tests/ui_tests/test_research_searxng.js@@ -0,0 +1,128 @@+/**+ * Test research with specific search engine (searxng)+ */++const puppeteer = require('puppeteer');+const AuthHelper = require('./auth_helper');++const BASE_URL = 'http://127.0.0.1:5000';+const RESEARCH_QUESTION = 'What is the capital of France?';++async function testResearchWithSearxng() {+ console.log('🔬 Testing Research with Searxng\n');++ const browser = await puppeteer.launch({+ headless: true,+ args: ['--no-sandbox', '--disable-setuid-sandbox']+ });++ const page = await browser.newPage();+ const authHelper = new AuthHelper(page, BASE_URL);++ // Log console messages+ page.on('console', msg => {+ if (msg.type() === 'error' || msg.type() === 'warning') {+ console.log(`📝 [${msg.type().toUpperCase()}] ${msg.text()}`);+ }+ });++ // Log requests+ page.on('request', request => {+ if (request.url().includes('/api/start_research')) {+ console.log(`→ REQUEST: ${request.method()} ${request.url()}`);+ console.log(` Body: ${request.postData()}`);+ }+ });++ page.on('response', response => {+ if (response.url().includes('/api/start_research')) {+ console.log(`← RESPONSE: ${response.status()} ${response.url()}`);+ }+ });++ try {+ // Login+ console.log('🔐 Logging in...');+ await authHelper.ensureAuthenticated();+ console.log('✅ Logged in\n');++ // Navigate to home+ await page.goto(BASE_URL, { waitUntil: 'networkidle2' });++ // Fill form+ console.log('📝 Filling research form...');+ await page.type('#query', RESEARCH_QUESTION);++ // Wait for models to load+ await page.waitForTimeout(1000);++ // Select searxng as search engine+ console.log('🔍 Selecting searxng search engine...');++ // Try to find and select searxng+ const searchEngineSet = await page.evaluate(() => {+ const select = document.querySelector('#search_engine');+ if (select) {+ // Try regular select+ for (let option of select.options) {+ if (option.value === 'searxng' || option.text.toLowerCase().includes('searxng')) {+ select.value = option.value;+ select.dispatchEvent(new Event('change'));+ return true;+ }+ }+ }++ // Try custom dropdown+ const hiddenInput = document.querySelector('#search_engine_hidden');+ if (hiddenInput) {+ hiddenInput.value = 'searxng';+ hiddenInput.dispatchEvent(new Event('change'));+ return true;+ }++ return false;+ });++ if (!searchEngineSet) {+ console.log('⚠️ Could not set search engine to searxng');+ } else {+ console.log('✅ Search engine set to searxng');+ }++ // Submit research+ console.log('\n📤 Submitting research...');+ await Promise.all([+ page.waitForResponse(response =>+ response.url().includes('/api/start_research'),+ { timeout: 10000 }+ ),+ page.click('#submit-research')+ ]);++ // Wait a bit for research to start+ await page.waitForTimeout(3000);++ // Get research ID from URL or response+ const currentUrl = page.url();+ const researchIdMatch = currentUrl.match(/progress\/([a-f0-9-]+)/);++ if (researchIdMatch) {+ const researchId = researchIdMatch[1];+ console.log(`\n✅ Research started with ID: ${researchId}`);++ // Check server logs will show search engine usage+ console.log('\n📋 Check server logs for search engine usage:');+ console.log(' tail -100 /tmp/ldr_server.log | grep -i searxng');+ } else {+ console.log('\n⚠️ Could not extract research ID from URL');+ }++ } catch (error) {+ console.error('❌ Error:', error.message);+ } finally {+ await browser.close();+ }+}++testResearchWithSearxng().catch(console.error);diff --git a/tests/ui_tests/test_simple_research.js b/tests/ui_tests/test_simple_research.jsindex de6eef71a9..29a19607f9 100644--- a/tests/ui_tests/test_simple_research.js+++ b/tests/ui_tests/test_simple_research.js@@ -30,6 +30,20 @@ const AuthHelper = require('./auth_helper');// Navigate to homeawait page.goto('http://127.0.0.1:5000/', { waitUntil: 'networkidle2' });+ // Log the page content if we can't find the query element+ const queryElement = await page.$('#query');+ if (!queryElement) {+ console.error('Could not find #query element. Page content:');+ const pageContent = await page.content();+ console.error(pageContent.substring(0, 2000)); // First 2000 chars++ // Also log the URL we ended up at+ console.error('Current URL:', page.url());++ // Take a screenshot+ await page.screenshot({ path: '/tmp/no_query_element.png' });+ }+// Fill formawait page.type('#query', 'Test research about JavaScript');@@ -62,8 +76,8 @@ const AuthHelper = require('./auth_helper');await page.evaluate(() => {const searchInput = document.querySelector('#search_engine');if (searchInput) {- // Set to wikipedia which should be in default settings- searchInput.value = 'wikipedia';+ // Set to searxng which should be in default settings+ searchInput.value = 'searxng';// Trigger input eventconst inputEvent = new Event('input', { bubbles: true });