~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Merge feature/per-user-encrypted-databases into feature/news-subscription
LearningCircuit7a03ca28de3c
diff --cc pyproject.tomlindex 8330ad29ff,5c8f64188c..56fb015d26--- a/pyproject.toml+++ b/pyproject.toml@@@ -67,9 -67,12 +67,15 @@@ dependencies ="kaleido==0.2.1","aiohttp>=3.9.0","tenacity>=8.0.0",+ "apscheduler>=3.10.0",+ "rich>=13.0.0",+ "click>=8.0.0",+ "flask-login>=0.6.3",+ "dogpile.cache>=1.2.0",+ "redis>=4.0.0",+ "msgpack>=1.0.0",+ "sqlcipher3-binary>=0.5.4; sys_platform == 'linux'",+ "sqlcipher3>=0.5.0; sys_platform != 'linux'",][project.urls]diff --cc src/local_deep_research/api/__init__.pyindex cee1df3482,f5fde09d37..47019da111--- a/src/local_deep_research/api/__init__.py+++ b/src/local_deep_research/api/__init__.py@@@ -9,40 -9,18 +9,48 @@@ from .research_functions importgenerate_report,quick_summary,)+ from .settings_utils import (+ create_settings_snapshot,+ get_default_settings_snapshot,+ extract_setting_value,+ )+try:+ from ..news import (+ get_news_feed,+ research_news_item,+ submit_news_feedback,+ save_news_preferences,+ get_news_categories,+ )++ NEWS_AVAILABLE = True+except ImportError:+ NEWS_AVAILABLE = False+ # Define placeholders to avoid NameErrors+ get_news_feed = None+ research_news_item = None+ submit_news_feedback = None+ save_news_preferences = None+ get_news_categories = None+__all__ = [- "quick_summary",+ "analyze_documents","detailed_research","generate_report",- "analyze_documents",+ "quick_summary",+ "create_settings_snapshot",+ "get_default_settings_snapshot",+ "extract_setting_value",]++if NEWS_AVAILABLE:+ __all__.extend(+ [+ "get_news_feed",+ "research_news_item",+ "submit_news_feedback",+ "save_news_preferences",+ "get_news_categories",+ ]+ )diff --cc src/local_deep_research/database/encrypted_db.pyindex 0000000000,0f53d7e8bb..34d88395d7mode 000000,100644..100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@@ -1,0 -1,579 +1,590 @@@+ """+ Encrypted database management using SQLCipher.+ Handles per-user encrypted databases with browser-friendly authentication.+ """++ import os++import sys+ from pathlib import Path+ from typing import Any, Dict, Optional++ from loguru import logger+ from sqlalchemy import create_engine, event, text+ from sqlalchemy.engine import Engine+ from sqlalchemy.orm import Session, sessionmaker+ from sqlalchemy.pool import QueuePool, NullPool, StaticPool++ from ..config.paths import get_data_directory, get_user_database_filename+ from .sqlcipher_utils import (+ set_sqlcipher_key,+ set_sqlcipher_rekey,+ apply_sqlcipher_pragmas,+ apply_performance_pragmas,+ verify_sqlcipher_connection,+ )+++ class DatabaseManager:+ """Manages encrypted SQLCipher databases for each user."""++ def __init__(self):+ self.connections: Dict[str, Engine] = {}+ self.data_dir = get_data_directory() / "encrypted_databases"+ self.data_dir.mkdir(parents=True, exist_ok=True)++ # Check SQLCipher availability+ self.has_encryption = self._check_encryption_available()++ # Determine pool class based on environment+ # Use StaticPool for testing to avoid locking issues+ self._pool_class = (+ StaticPool if os.environ.get("TESTING") else QueuePool+ )++ def _is_valid_encryption_key(self, password: str) -> bool:+ """+ Check if the provided password is valid (not None or empty).++ Args:+ password: The password to check++ Returns:+ True if the password is valid, False otherwise+ """+ return password is not None and password != ""++ def _check_encryption_available(self) -> bool:+ """Check if SQLCipher is available for encryption."""+ try:+ import os as os_module+ import tempfile++ # Test if SQLCipher actually works, not just if it imports+ with tempfile.NamedTemporaryFile(delete=False) as tmp:+ tmp_path = tmp.name++ try:+ # Try to create a test encrypted database++ # Use raw sqlcipher3 connection to test+ from sqlcipher3 import dbapi2 as sqlcipher++ conn = sqlcipher.connect(tmp_path)+ # Use centralized key setting+ set_sqlcipher_key(conn, "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"+ )+ return True+ except Exception as e:+ logger.warning(f"SQLCipher module found but not working: {e}")+ raise ImportError("SQLCipher not functional")+ finally:+ # Clean up test file+ try:+ os_module.unlink(tmp_path)+ except:+ pass++ except ImportError:+ import os++ # Check if user has explicitly allowed unencrypted databases+ allow_unencrypted = (+ os.environ.get("LDR_ALLOW_UNENCRYPTED", "").lower() == "true"+ )+++ # Check if we're in a pre-commit hook context++ if not allow_unencrypted and (++ "pre-commit" in sys.argv[0]++ or ".pre-commit-hooks" in sys.argv[0]++ ):++ logger.debug(++ "Running in pre-commit context, allowing unencrypted for checks"++ )++ allow_unencrypted = True+++ if not allow_unencrypted:+ logger.exception(+ "SECURITY ERROR: SQLCipher is not installed!\n"+ "Your databases will NOT be encrypted.\n"+ "To fix this:\n"+ "1. Install SQLCipher: sudo apt install sqlcipher libsqlcipher-dev\n"+ "2. Install Python binding: pip install pysqlcipher3\n"+ "Or use Docker with SQLCipher pre-installed.\n\n"+ "To explicitly allow unencrypted databases (NOT RECOMMENDED):\n"+ "export LDR_ALLOW_UNENCRYPTED=true"+ )+ raise RuntimeError(+ "SQLCipher not available. Set LDR_ALLOW_UNENCRYPTED=true to proceed without encryption (NOT RECOMMENDED)"+ )+ else:+ logger.warning(+ "⚠️ WARNING: Running with UNENCRYPTED databases!\n"+ "This means:\n"+ "- Passwords don't protect data access\n"+ "- API keys are stored in plain text\n"+ "- Anyone with file access can read all data\n"+ "Install SQLCipher for secure operation!"+ )+ return False++ def _get_user_db_path(self, username: str) -> Path:+ """Get the path for a user's encrypted database."""+ return self.data_dir / get_user_database_filename(username)++ def _apply_pragmas(self, connection, connection_record):+ """Apply pragmas for optimal performance."""+ # Check if this is SQLCipher or regular SQLite+ is_encrypted = self.has_encryption++ # Use centralized performance pragma application+ from .sqlcipher_utils import apply_performance_pragmas++ apply_performance_pragmas(connection)++ # SQLCipher-specific pragmas+ if is_encrypted:+ from .sqlcipher_utils import get_sqlcipher_settings++ settings = get_sqlcipher_settings()+ pragmas = [+ f"PRAGMA kdf_iter = {settings['kdf_iterations']}",+ f"PRAGMA cipher_page_size = {settings['page_size']}",+ ]+ for pragma in pragmas:+ try:+ connection.execute(pragma)+ except Exception:+ pass+ else:+ # Regular SQLite pragma+ try:+ connection.execute(+ "PRAGMA mmap_size = 268435456"+ ) # 256MB memory mapping+ except Exception:+ pass++ def create_user_database(self, username: str, password: str) -> Engine:+ """Create a new encrypted database for a user."""++ # Validate the encryption key+ if not self._is_valid_encryption_key(password):+ logger.error(+ f"Invalid encryption key for user {username}: password is None or empty"+ )+ raise ValueError(+ "Invalid encryption key: password cannot be None or empty"+ )++ db_path = self._get_user_db_path(username)++ if db_path.exists():+ raise ValueError(f"Database already exists for user {username}")++ # Create connection string - use regular SQLite when SQLCipher not available+ if self.has_encryption:+ # 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+ # Use isolation_level=None to prevent locking issues+ conn = sqlcipher3.connect(+ str(db_path), isolation_level=None, check_same_thread=False+ )+ # Use centralized SQLCipher setup+ set_sqlcipher_key(conn, password)+ apply_sqlcipher_pragmas(conn, creation_mode=True)++ # 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), isolation_level=None, check_same_thread=False+ )+ cursor = conn.cursor()++ # Use centralized SQLCipher setup+ set_sqlcipher_key(cursor, password)++ # Verify connection works+ if not verify_sqlcipher_connection(cursor):+ raise ValueError("Failed to verify database key")++ # Apply SQLCipher and performance settings+ apply_sqlcipher_pragmas(cursor, creation_mode=False)+ apply_performance_pragmas(cursor, username)++ cursor.close()+ return conn++ # Create engine with custom creator function and optimized cache+ engine = create_engine(+ "sqlite://",+ creator=create_sqlcipher_connection,+ poolclass=self._pool_class,+ echo=False,+ query_cache_size=1000, # Increased for complex queries with SQLCipher+ )+ else:+ logger.warning(+ f"SQLCipher not available - creating UNENCRYPTED database for user {username}"+ )+ # Fall back to regular SQLite with query cache+ engine = create_engine(+ f"sqlite:///{db_path}",+ connect_args={"check_same_thread": False, "timeout": 30},+ poolclass=self._pool_class,+ echo=False,+ query_cache_size=1000, # Same optimization for unencrypted+ )++ # For unencrypted databases, just apply pragmas+ event.listen(engine, "connect", self._apply_pragmas)++ # Tables have already been created using raw SQLCipher above+ # No need to create them again with SQLAlchemy++ # Store connection+ self.connections[username] = engine++ logger.info(f"Created encrypted database for user {username}")+ return engine++ def open_user_database(+ self, username: str, password: str+ ) -> Optional[Engine]:+ """Open an existing encrypted database for a user."""++ # Validate the encryption key+ if not self._is_valid_encryption_key(password):+ logger.error(+ f"Invalid encryption key when opening database for user {username}: password is None or empty"+ )+ # TODO: Fix the root cause - research threads are not getting the correct password+ logger.error(+ "TODO: This usually means the research thread is not receiving the user's "+ "password for database encryption. Need to ensure password is passed from "+ "the main thread to research threads."+ )+ raise ValueError(+ "Invalid encryption key: password cannot be None or empty"+ )++ # Check if already open+ if username in self.connections:+ return self.connections[username]++ db_path = self._get_user_db_path(username)++ if not db_path.exists():+ logger.error(f"No database found for user {username}")+ return None++ # Create connection string - use regular SQLite when SQLCipher not available+ if self.has_encryption:+ # 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), isolation_level=None, check_same_thread=False+ )+ cursor = conn.cursor()++ # Use centralized SQLCipher setup+ set_sqlcipher_key(cursor, password)++ # Verify connection works+ if not verify_sqlcipher_connection(cursor):+ raise ValueError("Failed to verify database key")++ # Apply SQLCipher and performance settings+ apply_sqlcipher_pragmas(cursor, creation_mode=False)+ apply_performance_pragmas(cursor, username)++ cursor.close()+ return conn++ # Create engine with custom creator function and optimized cache+ engine = create_engine(+ "sqlite://",+ creator=create_sqlcipher_connection,+ poolclass=self._pool_class,+ echo=False,+ query_cache_size=1000, # Increased for complex queries with SQLCipher+ )+ else:+ logger.warning(+ f"SQLCipher not available - opening UNENCRYPTED database for user {username}"+ )+ # Fall back to regular SQLite (no password protection!)+ engine = create_engine(+ f"sqlite:///{db_path}",+ connect_args={"check_same_thread": False, "timeout": 30},+ poolclass=self._pool_class,+ echo=False,+ query_cache_size=1000, # Same optimization for unencrypted+ )++ # For unencrypted databases, just apply pragmas+ event.listen(engine, "connect", self._apply_pragmas)++ try:+ # Test connection by running a simple query+ with engine.connect() as conn:+ conn.execute(text("SELECT 1"))++ # Store connection+ self.connections[username] = engine++ # Ensure all tables exist (for new tables added after database creation)++ # Don't create tables when opening existing database+ # Tables should already exist from create_user_database++ logger.info(f"Opened encrypted database for user {username}")+ return engine++ except Exception as e:+ logger.exception(+ f"Failed to open database for user {username}: {e}"+ )+ return None++ def get_session(self, username: str) -> Optional[Session]:+ """Create a new session for a user's database."""+ if username not in self.connections:+ # Use debug level for this common scenario to reduce log noise+ logger.debug(f"No open database for user {username}")+ return None++ # Always create a fresh session to avoid stale session issues+ engine = self.connections[username]+ SessionLocal = sessionmaker(bind=engine)+ return SessionLocal()++ def close_user_database(self, username: str):+ """Close a user's database connection."""+ if username in self.connections:+ self.connections[username].dispose()+ del self.connections[username]+ logger.info(f"Closed database for user {username}")++ def check_database_integrity(self, username: str) -> bool:+ """Check integrity of a user's encrypted database."""+ if username not in self.connections:+ return False++ try:+ with self.connections[username].connect() as conn:+ # Quick integrity check+ result = conn.execute(text("PRAGMA quick_check"))+ if result.fetchone()[0] != "ok":+ return False++ # SQLCipher integrity check+ result = conn.execute(text("PRAGMA cipher_integrity_check"))+ # If this returns any rows, there are HMAC failures+ failures = list(result)+ if failures:+ logger.error(+ f"Integrity check failed for {username}: {len(failures)} HMAC failures"+ )+ return False++ return True++ except Exception as e:+ logger.exception(f"Integrity check error for {username}: {e}")+ return False++ def change_password(+ self, username: str, old_password: str, new_password: str+ ) -> bool:+ """Change the encryption password for a user's database."""+ if not self.has_encryption:+ logger.warning(+ "Cannot change password - SQLCipher not available (databases are unencrypted)"+ )+ return False++ db_path = self._get_user_db_path(username)++ if not db_path.exists():+ return False++ try:+ # Close existing connection if any+ self.close_user_database(username)++ # Open with old password+ engine = self.open_user_database(username, old_password)+ if not engine:+ return False++ # Rekey the database (only works with SQLCipher)+ with engine.connect() as conn:+ # Use centralized rekey function+ set_sqlcipher_rekey(conn, new_password)++ logger.info(f"Password changed for user {username}")+ return True++ except Exception as e:+ logger.exception(f"Failed to change password for {username}: {e}")+ return False+ finally:+ # Close the connection+ self.close_user_database(username)++ def user_exists(self, username: str) -> bool:+ """Check if a user exists in the auth database."""+ from .auth_db import get_auth_db_session+ from .models.auth import User++ auth_db = get_auth_db_session()+ user = auth_db.query(User).filter_by(username=username).first()+ auth_db.close()++ return user is not None++ def get_memory_usage(self) -> Dict[str, Any]:+ """Get memory usage statistics."""+ return {+ "active_connections": len(self.connections),+ "active_sessions": 0, # Sessions are created on-demand, not tracked+ "estimated_memory_mb": len(self.connections)+ * 3.5, # ~3.5MB per connection+ }++ def create_thread_safe_session_for_metrics(+ self, username: str, password: str+ ):+ """+ Create a new database session safe for use in background threads.+ This is specifically for metrics/logging - NOT for settings or user data.++ Args:+ username: The username+ password: The user's password (encryption key)++ Returns:+ A SQLAlchemy session that can be used in the current thread++ IMPORTANT: This should ONLY be used for:+ - Writing token metrics+ - Writing search metrics+ - Writing logs++ DO NOT use this for:+ - Reading/writing settings+ - Modifying user data+ - Any operation that should be synchronized with user requests+ """+ db_path = self._get_user_db_path(username)++ if not db_path.exists():+ raise ValueError(f"No database found for user {username}")++ # Create a thread-local engine+ if self.has_encryption:+ import sqlcipher3++ def create_thread_connection():+ """Create a SQLCipher connection for this thread."""+ try:+ conn = sqlcipher3.connect(str(db_path))+ cursor = conn.cursor()++ # Use centralized SQLCipher setup+ set_sqlcipher_key(cursor, password)+ apply_sqlcipher_pragmas(cursor, creation_mode=False)++ # Verify connection works+ if not verify_sqlcipher_connection(cursor):+ raise ValueError("Failed to verify database key")+ except Exception as e:+ logger.exception(+ f"Failed to create thread connection for {username}: {e}"+ )+ raise++ # Apply performance pragmas for metrics writes+ apply_performance_pragmas(cursor, username)++ cursor.close()+ return conn++ engine = create_engine(+ "sqlite://",+ creator=create_thread_connection,+ poolclass=NullPool, # Important: no connection pooling for threads+ echo=False,+ )+ else:+ # Unencrypted fallback+ logger.warning("Creating unencrypted thread session for metrics")+ engine = create_engine(+ f"sqlite:///{db_path}",+ poolclass=NullPool,+ echo=False,+ )++ # Create session+ Session = sessionmaker(bind=engine)+ return Session()+++ # Global instance+ db_manager = DatabaseManager()diff --cc src/local_deep_research/search_system.pyindex dd28f6de8f,ff7c6db2f5..d5bad3ae3c--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@@ -47,12 -47,8 +47,11 @@@ from .advanced_search_system.strategiesfrom .advanced_search_system.strategies.source_based_strategy import (SourceBasedSearchStrategy,)- from .advanced_search_system.strategies.standard_strategy import (- StandardSearchStrategy,- )+from .advanced_search_system.strategies.news_strategy import (+ NewsAggregationStrategy,+)++ # StandardSearchStrategy imported lazily to avoid database access during module importfrom .citation_handler import CitationHandlerfrom .config.llm_config import get_llmfrom .config.search_config import get_search@@@ -491,15 -543,13 +546,20 @@@ class AdvancedSearchSystemsearch=self.search,all_links_of_system=self.all_links_of_system,)+ elif strategy_name.lower() in [+ "news",+ "news_aggregation",+ "news-aggregation",+ ]:+ logger.info("Creating NewsAggregationStrategy instance")+ self.strategy = NewsAggregationStrategy()else:logger.info("Creating StandardSearchStrategy instance")+ # Import lazily to avoid database access during module import+ from .advanced_search_system.strategies.standard_strategy import (+ StandardSearchStrategy,+ )+self.strategy = StandardSearchStrategy(model=self.model,search=self.search,@@@ -534,57 -585,39 +595,83 @@@Args:query: The research query to analyze+ **kwargs: Additional arguments (is_user_search, is_news_search, user_id)"""+ # Import news integration if available+ try:+ from .news.core.priority_manager import (- get_priority_manager,+ UserSearchContext,+ )- from .news.core.search_integration import NewsSearchCallback++ news_enabled = True+ except ImportError:+ news_enabled = False++ # Determine search type+ is_user_search = kwargs.get("is_user_search", True)+ is_news_search = kwargs.get("is_news_search", False)+ user_id = kwargs.get("user_id", "anonymous")+ search_id = kwargs.get("search_id", None)++ # Generate search ID if not provided+ if search_id is None:+ import uuid++ search_id = str(uuid.uuid4())++ # Handle priority if news system is enabled+ if news_enabled and is_user_search and not is_news_search:+ with UserSearchContext(search_id):+ result = self._perform_search(+ query, search_id, is_user_search, is_news_search, user_id+ )+ else:+ result = self._perform_search(+ query, search_id, is_user_search, is_news_search, user_id+ )+ return result++ def _perform_search(+ self,+ query: str,+ search_id: str,+ is_user_search: bool,+ is_news_search: bool,+ user_id: str,+ ) -> Dict:+ """Perform the actual search."""# Send progress message with LLM info+ # Get settings from snapshot if available+ llm_provider = "unknown"+ llm_model = "unknown"+ search_tool = "unknown"++ if self.settings_snapshot:+ # Extract values from settings snapshot+ provider_setting = self.settings_snapshot.get("llm.provider", {})+ llm_provider = (+ provider_setting.get("value", "unknown")+ if isinstance(provider_setting, dict)+ else provider_setting+ )++ model_setting = self.settings_snapshot.get("llm.model", {})+ llm_model = (+ model_setting.get("value", "unknown")+ if isinstance(model_setting, dict)+ else model_setting+ )++ tool_setting = self.settings_snapshot.get("search.tool", {})+ search_tool = (+ tool_setting.get("value", "searxng")+ if isinstance(tool_setting, dict)+ else tool_setting+ )+self.progress_callback(- f"Using {get_db_setting('llm.provider')} model: {get_db_setting('llm.model')}",+ f"Using {llm_provider} model: {llm_model}",1, # Low percentage to show this as an early step{"phase": "setup",@@@ -634,23 -665,4 +719,23 @@@if "query" not in result:result["query"] = queryresult["questions_by_iteration"] = self.questions_by_iteration++ # Call news callback if enabled+ try:+ from .news.core.search_integration import NewsSearchCallback++ callback = NewsSearchCallback()+ if callback.enabled:+ context = {+ "is_user_search": is_user_search,+ "is_news_search": is_news_search,+ "user_id": user_id,+ "search_id": search_id,+ }+ callback(query, result, context)+ except ImportError:+ pass+ except Exception as e:- logger.error(f"Error in news callback: {e}")++ logger.exception(f"Error in news callback: {e}")+return resultdiff --cc src/local_deep_research/web/app.pyindex a88fff2969,5be7bcaefe..452b4c0f51--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@@ -55,62 -14,46 +14,57 @@@ def main()# Configure logging with milestone levelconfig_logger("ldr_web")- # Create the Flask app and SocketIO instance- app, socketio = create_app()-- # Check if migration is needed- if check_migration_needed():- logger.info(- "Database migration required. Run migrate_db.py before starting the application."- )- print("=" * 80)- print("DATABASE MIGRATION REQUIRED")- print(- "Legacy database files were found, but the new unified database doesn't exist."- )- print(- "Please run 'python -m src.local_deep_research.web.database.migrate_to_ldr_db' to migrate your data."- )- print(- "You can continue without migration, but your previous data won't be available."- )- print("=" * 80)+ # Register atexit handler to flush logs on exit+ def flush_logs_on_exit():+ """Flush any pending logs when the program exits."""+ try:+ # Create a minimal Flask app context to allow database access+ from flask import Flask- # If --auto-migrate flag is passed, run migration automatically- if "--auto-migrate" in sys.argv:- logger.info("Auto-migration flag detected, running migration...")- try:- from .database.migrate_to_ldr_db import migrate_to_ldr_db+ app = Flask(__name__)+ with app.app_context():+ flush_log_queue()+ except Exception as e:+ logger.exception(f"Failed to flush logs on exit: {e}")- success = migrate_to_ldr_db()- if success:- logger.info("Database migration completed successfully.")- else:- logger.warning("Database migration failed.")- except Exception:- logger.exception("Error running database migration")- print("Please run migration manually.")+ atexit.register(flush_logs_on_exit)+ logger.debug("Registered atexit handler for log flushing")- # 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)+ # Create the Flask app and SocketIO instance+ app, socket_service = create_app()++ # Get web server settings from configuration file or environment+ # This allows settings to be configured through the web UI+ from .server_config import load_server_config++ config = load_server_config()+ host = config["host"]+ port = config["port"]+ debug = config["debug"]+ use_https = config["use_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."+ )+ # Register shutdown handler for scheduler- import atexit-+ def shutdown_scheduler():+ if hasattr(app, "news_scheduler") and app.news_scheduler:+ try:+ app.news_scheduler.stop()+ logger.info("News subscription scheduler stopped gracefully")+ except Exception as e:- logger.error(f"Error stopping scheduler: {e}")++ logger.exception(f"Error stopping scheduler: {e}")++ atexit.register(shutdown_scheduler)+- with app.app_context():- socketio.run(host, port, debug=debug)+ # 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 --cc src/local_deep_research/web/app_factory.pyindex eff6726922,2968e277cc..54422da0d8--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@@ -82,46 -143,6 +143,46 @@@ def create_app()# Register socket servicesocket_service = SocketIOService(app=app)+ # Initialize news subscription scheduler if news is enabled+ try:+ from ..utilities.db_utils import get_db_setting++ if get_db_setting("news.enabled", True):+ # Initialize news database tables+ from ..news.database import init_news_tables+- if init_news_tables(db_path):++ if init_news_tables():+ logger.info("News database tables initialized successfully")+ else:+ logger.warning("Failed to initialize news database tables")++ from ..news.subscription_manager.scheduler import (+ SubscriptionScheduler,+ SCHEDULER_AVAILABLE,+ )++ if SCHEDULER_AVAILABLE:+ # Create scheduler instance+ scheduler = SubscriptionScheduler()+ # Store in app context for later access+ app.news_scheduler = scheduler+ # Start the scheduler+ scheduler.start()+ logger.info("News subscription scheduler started successfully")+ else:+ logger.warning(+ "APScheduler not available - subscription auto-refresh disabled. Install with: pip install apscheduler"+ )+ app.news_scheduler = None+ else:+ logger.info(+ "News module disabled - subscription scheduler not started"+ )+ app.news_scheduler = None+ except Exception as e:- logger.error(f"Failed to initialize news scheduler: {e}")++ logger.exception(f"Failed to initialize news scheduler: {e}")+ app.news_scheduler = None+# Apply middlewareapply_middleware(app)@@@ -213,17 -291,7 +331,16 @@@ def register_blueprints(app)from .routes.metrics_routes import metrics_bpfrom .routes.research_routes import research_bpfrom .routes.settings_routes import settings_bp- from ..benchmarks.web_api.benchmark_routes import benchmark_bp+ # Try to import news blueprint+ try:+ from ..news.web import create_news_blueprint+ from ..utilities.db_utils import get_db_setting++ news_available = True+ except ImportError:+ news_available = False+# Add root route@app.route("/")def index():diff --cc src/local_deep_research/web/database/migrations.pyindex eddffac7e4,0000000000..7a4ea905bcmode 100644,000000..100644--- a/src/local_deep_research/web/database/migrations.py+++ b/src/local_deep_research/web/database/migrations.py@@@ -1,144 -1,0 +1,144 @@@+from loguru import logger+from sqlalchemy import inspect++from ..services.settings_manager import SettingsManager+from .models import (+ Base,+ Journal,+ Setting,+ ResearchLog,+ Research,+ ResearchHistory,+)++# Import news models for table creation+try:+ from ...news.models import (+ BaseSubscription,+ SubscriptionFolder,+ UserPreference,+ Rating,+ NewsCard,+ CardVersion,+ )++ NEWS_MODELS_AVAILABLE = True+except ImportError:+ NEWS_MODELS_AVAILABLE = False+ logger.warning(+ "News models not available - news tables will not be created"+ )+++def import_default_settings_file(db_session):+ """+ Imports all settings from the default settings file to the DB.+ """+ settings_mgr = SettingsManager(db_session)+ if settings_mgr.db_version_matches_package():+ # We probably shouldn't bother loading settings if the version didn't+ # change.+ return+ logger.info("Detected a new version of default settings, upgrading DB.")++ # Create settings manager and import settings+ try:+ # This will not overwrite existing settings, but will delete+ # extraneous ones. This should be enough to update anyone with+ # old versions of the settings.+ settings_mgr.load_from_defaults_file(overwrite=False, delete_extra=True)+ logger.info("Successfully imported settings from files")++ # Update the saved version.+ settings_mgr.update_db_version()+ except Exception as e:- logger.error("Error importing settings from files: %s", e)++ logger.exception("Error importing settings from files: %s", e)+++def run_migrations(engine, db_session=None):+ """+ Run any necessary database migrations++ Args:+ engine: SQLAlchemy engine+ db_session: Optional SQLAlchemy session+ """+ # Create all tables if they don't exist+ inspector = inspect(engine)+ if not inspector.has_table("settings"):+ logger.info("Creating settings table")+ Base.metadata.create_all(engine, tables=[Setting.__table__])++ if not inspector.has_table(Journal.__tablename__):+ logger.info("Creating journals table.")+ Base.metadata.create_all(engine, tables=[Journal.__table__])++ if not inspector.has_table(ResearchLog.__tablename__):+ logger.info("Creating research logs table.")+ Base.metadata.create_all(engine, tables=[ResearchLog.__table__])++ if not inspector.has_table(Research.__tablename__):+ logger.info("Creating research table.")+ Base.metadata.create_all(engine, tables=[Research.__table__])++ if not inspector.has_table(ResearchHistory.__tablename__):+ logger.info("Creating research table.")+ Base.metadata.create_all(engine, tables=[ResearchHistory.__table__])++ # Create news tables if available+ if NEWS_MODELS_AVAILABLE:+ from ...utilities.db_utils import get_db_setting++ # Check if news is enabled (default to True)+ news_enabled = True+ if db_session:+ try:+ news_enabled = get_db_setting(+ "news.enabled", True, db_session=db_session+ )+ except Exception:+ # If we can't check the setting, default to enabled+ news_enabled = True++ if news_enabled:+ # Import the news Base to ensure proper metadata+ from ...news.models import Base as NewsBase++ # Create news tables if they don't exist+ if not inspector.has_table("news_subscriptions"):+ logger.info("Creating news_subscriptions table")+ NewsBase.metadata.create_all(+ engine, tables=[BaseSubscription.__table__]+ )++ if not inspector.has_table("news_subscription_folders"):+ logger.info("Creating news_subscription_folders table")+ NewsBase.metadata.create_all(+ engine, tables=[SubscriptionFolder.__table__]+ )++ if not inspector.has_table("news_user_preferences"):+ logger.info("Creating news_user_preferences table")+ NewsBase.metadata.create_all(+ engine, tables=[UserPreference.__table__]+ )++ if not inspector.has_table("news_ratings"):+ logger.info("Creating news_ratings table")+ NewsBase.metadata.create_all(engine, tables=[Rating.__table__])++ if not inspector.has_table("news_cards"):+ logger.info("Creating news_cards table")+ NewsBase.metadata.create_all(+ engine, tables=[NewsCard.__table__]+ )++ if not inspector.has_table("news_card_versions"):+ logger.info("Creating news_card_versions table")+ NewsBase.metadata.create_all(+ engine, tables=[CardVersion.__table__]+ )++ # Import existing settings from files+ if db_session:+ import_default_settings_file(db_session)diff --cc src/local_deep_research/web/routes/history_routes.pyindex 5ac8a16c67,878e6dcacd..9a725ef613--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@@ -60,37 -47,23 +47,30 @@@ def get_history()# Convert to list of dictshistory = []- for result in results:- item = dict(result)-- # Ensure all keys exist with default values- if "id" not in item:- item["id"] = None- if "query" not in item:- item["query"] = "Untitled Research"- if "mode" not in item:- item["mode"] = "quick"- if "status" not in item:- item["status"] = "unknown"- if "created_at" not in item:- item["created_at"] = None- if "completed_at" not in item:- item["completed_at"] = None- if "duration_seconds" not in item:- item["duration_seconds"] = None- if "report_path" not in item:- item["report_path"] = None- if "research_meta" not in item:- item["research_meta"] = "{}"- if "progress_log" not in item:- item["progress_log"] = "[]"+ for research in results:+ 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": research.duration_seconds,+ "report_path": research.report_path,+ "research_meta": json.dumps(research.research_meta)+ if research.research_meta+ else "{}",+ "progress_log": json.dumps(research.progress_log)+ if research.progress_log+ else "[]",+ }++ # Parse research_meta as metadata for the frontend+ try:+ metadata = json.loads(item["research_meta"])+ item["metadata"] = metadata+ except:+ item["metadata"] = {}# Ensure timestamps are in ISO formatif item["created_at"] and "T" not in item["created_at"]:diff --cc src/local_deep_research/web/routes/research_routes.pyindex 0412a9fc10,bfa5f7e546..f4b98a6f78--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@@ -113,99 -127,35 +127,111 @@@ def llm_config_page()@research_bp.route("/api/start_research", methods=["POST"])+ @login_requireddef start_research():data = request.json- logger.debug(f"Received research request: {json.dumps(data, indent=2)}")-+ # Debug logging to trace model parameter+ logger.debug(f"Received request data: {data}")+ logger.debug(f"Request data keys: {list(data.keys()) if data else 'None'}")+ # Check if this is a news search+ metadata = data.get("metadata", {})+ if metadata.get("is_news_search"):+ logger.info(+ f"News search request received: triggered_by={metadata.get('triggered_by', 'unknown')}"+ )+query = data.get("query")mode = data.get("mode", "quick")- # Get model provider and model selections- model_provider = data.get("model_provider", "OLLAMA")+ # Replace date placeholders if they exist+ if query and "YYYY-MM-DD" in query:+ from datetime import datetime++ # Use local system time+ current_date = datetime.now().strftime("%Y-%m-%d")++ original_query = query+ query = query.replace("YYYY-MM-DD", current_date)+ logger.info(+ f"Replaced date placeholder in query: {original_query[:100]}... -> {query[:100]}..."+ )+ logger.info(f"Using date: {current_date}")++ # Update metadata to track the replacement+ if not metadata:+ metadata = {}+ metadata["original_query"] = original_query+ metadata["processed_query"] = query+ metadata["date_replaced"] = current_date+ data["metadata"] = metadata++ # Get parameters from request or use database settings+ from ..services.settings_manager import SettingsManager+- session = get_db_session()- settings_manager = SettingsManager(db_session=session)++ username = session.get("username")++ if not username:++ return jsonify({"error": "Not authenticated"}), 401++++ with get_user_db_session(username) as db_session:++ settings_manager = SettingsManager(db_session=db_session)++ # Get model provider and model selections - use database settings if not provided+ model_provider = data.get("model_provider")+ if not model_provider:+ model_provider = settings_manager.get_setting("llm.provider", "OLLAMA")+ logger.debug(+ f"No model_provider in request, using database setting: {model_provider}"+ )+ else:+ logger.debug(f"Using model_provider from request: {model_provider}")+model = data.get("model")+ if not model:+ model = settings_manager.get_setting("llm.model", None)+ logger.debug(f"No model in request, using database setting: {model}")+ else:+ logger.debug(f"Using model from request: {model}")+custom_endpoint = data.get("custom_endpoint")+ if not custom_endpoint and model_provider == "OPENAI_ENDPOINT":+ custom_endpoint = settings_manager.get_setting(+ "llm.openai_endpoint.url", None+ )+ logger.debug(+ f"No custom_endpoint in request, using database setting: {custom_endpoint}"+ )search_engine = data.get("search_engine") or data.get("search_tool")+ if not search_engine:+ search_engine = settings_manager.get_setting("search.tool", "searxng")+max_results = data.get("max_results")time_period = data.get("time_period")+iterations = data.get("iterations")+ if iterations is None:+ iterations = settings_manager.get_setting("search.iterations", 5)+questions_per_iteration = data.get("questions_per_iteration")+ if questions_per_iteration is None:+ questions_per_iteration = settings_manager.get_setting(+ "search.questions_per_iteration", 5+ )++ # Get strategy from request or database+ strategy = data.get("strategy")+ if not strategy:+ strategy = settings_manager.get_setting(+ "search.search_strategy", "source-based"+ )- # Add strategy parameter with default value- strategy = data.get("strategy", "source-based")+ session.close()+ # Debug logging for model parameter specifically+ logger.debug(+ f"Extracted model value: '{model}' (type: {type(model).__name__})"+ )+# Log the selections for troubleshootinglogger.info(f"Starting research with provider: {model_provider}, model: {model}, search engine: {search_engine}"@@@ -230,293 -180,584 +256,596 @@@)if not model:- return jsonify({"status": "error", "message": "Model is required"}), 400+ logger.error(+ f"No model specified or configured. Provider: {model_provider}"+ )+ return jsonify(+ {+ "status": "error",+ "message": "Model is required. Please configure a model in the settings.",+ }+ ), 400- # Check if there's any active research that's actually still running- if active_research:- # Verify each active research is still valid- stale_research_ids = []- for research_id, research_data in list(active_research.items()):- # Check database status- conn = get_db_connection()- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?",- (research_id,),+ # Check if the user has too many active researches+ username = session.get("username")++ # Get max concurrent researches from settings+ from ...settings import SettingsManager++ with get_user_db_session() as db_session:+ settings_manager = SettingsManager(db_session)+ max_concurrent_researches = settings_manager.get_setting(+ "app.max_concurrent_researches", 3+ )++ # Use existing session from g to check active researches+ try:+ if hasattr(g, "db_session") and g.db_session:+ # Count active researches for this user+ active_count = (+ g.db_session.query(UserActiveResearch)+ .filter_by(username=username, status="in_progress")+ .count())- result = cursor.fetchone()- conn.close()-- # If the research doesn't exist in DB or is not in_progress, it's stale- if not result or result[0] != "in_progress":- stale_research_ids.append(research_id)- # Also check if thread is still alive- elif (- not research_data.get("thread")- or not research_data.get("thread").is_alive()- ):- stale_research_ids.append(research_id)-- # Clean up any stale research processes- for stale_id in stale_research_ids:- print(f"Cleaning up stale research process: {stale_id}")- if stale_id in active_research:- del active_research[stale_id]- if stale_id in termination_flags:- del termination_flags[stale_id]-- # After cleanup, check if there's still active research- if active_research:- return (- jsonify(- {- "status": "error",- "message": "Another research is already in progress. Please wait for it to complete.",- }- ),- 409,++ # Debug logging+ logger.info(+ 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}")+ else:+ logger.warning(+ "No database session available to check active researches"+ )+ should_queue = False+ 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 timestamp- created_at = datetime.utcnow().isoformat()- conn = get_db_connection()- cursor = conn.cursor()+ import uuid+ import threading- # Save research settings in the metadata field+ created_at = datetime.now(UTC).isoformat()+ research_id = str(uuid.uuid4())++ # Create organized research metadata with settings snapshot- research_meta = {+ research_settings = {- "model_provider": model_provider,- "model": model,- "custom_endpoint": custom_endpoint,- "search_engine": search_engine,- "max_results": max_results,- "time_period": time_period,- "iterations": iterations,- "questions_per_iteration": questions_per_iteration,+ # Direct submission parameters+ "submission": {+ "model_provider": model_provider,+ "model": model,+ "custom_endpoint": custom_endpoint,+ "search_engine": search_engine,+ "max_results": max_results,+ "time_period": time_period,+ "iterations": iterations,+ "questions_per_iteration": questions_per_iteration,+ "strategy": strategy,+ },+ # System information+ "system": {+ "timestamp": created_at,+ "user": username,+ "version": "1.0", # Track metadata version for future migrations+ },}+ # Add any additional metadata from request+ additional_metadata = data.get("metadata", {})+ if additional_metadata:+ research_settings.update(additional_metadata)+ # Get complete settings snapshot for this research+ try:+ from local_deep_research.settings import SettingsManager++ # Use the existing session from g (set by middleware)+ if hasattr(g, "db_session") and g.db_session:+ # Create SettingsManager with the existing session+ username = session.get("username")+ # Ensure any pending changes are committed+ try:+ g.db_session.commit()+ except Exception:+ g.db_session.rollback()+ settings_manager = SettingsManager(g.db_session)+ # Get all current settings as a snapshot (bypass cache to ensure fresh data)+ all_settings = settings_manager.get_all_settings(bypass_cache=True)++ # Add settings snapshot to metadata- research_meta["settings_snapshot"] = all_settings++ research_settings["settings_snapshot"] = all_settings+ logger.info(+ f"Captured {len(all_settings)} settings for research {research_id}"+ )+ else:+ # If no session in g, create a new one temporarily to get settings+ logger.warning(+ "No database session in g, creating temporary session for settings snapshot"+ )+ from ...database.thread_local_session import get_metrics_session++ # Get password from session or g+ password = getattr(g, "user_password", None)+ if not password:+ # Try to get from session password store+ from ...database.session_passwords import session_password_store++ session_id = session.get("session_id")+ if session_id:+ password = session_password_store.get_session_password(+ username, session_id+ )- db_session = get_db_session()- with db_session:- research = ResearchHistory(- query=query,- mode=mode,- status="in_progress",- created_at=created_at,- progress_log=[{"time": created_at, "progress": 0}],- research_meta=research_settings,- )- db_session.add(research)- db_session.commit()- research_id = research.id-- # Start the research process with the selected parameters- research_thread = start_research_process(- research_id,- query,- mode,- active_research,- termination_flags,- run_research_process,- model_provider=model_provider,- model=model,- custom_endpoint=custom_endpoint,- search_engine=search_engine,- max_results=max_results,- time_period=time_period,- iterations=iterations,- questions_per_iteration=questions_per_iteration,- strategy=strategy,- )+ if password:+ temp_session = get_metrics_session(username, password)+ if temp_session:+ username = session.get("username")+ settings_manager = SettingsManager(temp_session)+ all_settings = settings_manager.get_all_settings(+ bypass_cache=True+ )- research_meta["settings_snapshot"] = all_settings++ research_settings["settings_snapshot"] = all_settings+ logger.info(+ f"Captured {len(all_settings)} settings using temporary session for research {research_id}"+ )+ else:+ logger.error(+ "Failed to create temporary session for settings snapshot"+ )+ raise Exception(+ "Cannot create research without settings snapshot"+ )+ else:+ logger.error(+ "No password available to create session for settings snapshot"+ )+ raise Exception(+ "Cannot create research without settings snapshot"+ )+ except Exception:+ logger.exception("Failed to capture settings snapshot")+ # Cannot continue without settings snapshot for thread-based research+ return jsonify(+ {+ "status": "error",+ "message": "Failed to capture settings for research. Please try again.",+ }+ ), 500- # Store the thread reference in active_research- active_research[research_id]["thread"] = research_thread+ # Use existing session from g+ username = session.get("username")+ if not username:+ return jsonify({"status": "error", "message": "Not authenticated"}), 401- return jsonify({"status": "success", "research_id": research_id})+ try:+ # Use existing session from g+ if hasattr(g, "db_session") and g.db_session:+ db_session = g.db_session+ # 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,++ research_meta=research_settings,+ )+ 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+ )- @research_bp.route("/api/terminate/<int:research_id>", methods=["POST"])- def terminate_research(research_id):- """Terminate an in-progress research process"""+ queued_record = QueuedResearch(+ username=username,+ research_id=research_id,+ query=query,+ mode=mode,- settings_snapshot=research_meta,++ settings_snapshot=research_settings,+ position=max_position + 1,+ )+ db_session.add(queued_record)+ db_session.commit()+ logger.info(+ f"Queued research {research_id} at position {max_position + 1} for user {username}"+ )- # Check if the research exists and is in progress- conn = get_db_connection()- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?", (research_id,)- )- result = cursor.fetchone()+ # Notify queue processor with all parameters for potential direct execution+ from ..queue.processor_v2 import queue_processor++ # Get session ID for password access+ session_id = session.get("session_id")++ # Pass all parameters needed for direct execution+ queue_processor.notify_research_queued(+ username,+ research_id,+ session_id=session_id,+ query=query,+ mode=mode,- settings_snapshot=research_meta,++ settings_snapshot=research_settings,+ model_provider=model_provider,+ model=model,+ custom_endpoint=custom_endpoint,+ search_engine=search_engine,+ max_results=max_results,+ time_period=time_period,+ iterations=iterations,+ questions_per_iteration=questions_per_iteration,+ strategy=strategy,+ )- if not result:- conn.close()+ # 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,++ settings_snapshot=research_settings,+ )+ db_session.add(active_record)+ db_session.commit()+ logger.info(+ f"Created active research record for user {username}"+ )++ # Double-check the count after committing to handle race conditions+ # Use the existing session for the recheck+ try:+ # Use the same session we already have+ recheck_session = db_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}"+ )++ 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,++ settings_snapshot=research_settings,+ position=max_position + 1,+ )+ db_session.add(queued_record)++ # Update research status to queued+ research.status = "queued"+ db_session.commit()++ # Notify queue processor for potential direct execution+ from ..queue.processor_v2 import queue_processor++ # Get session ID for password access+ session_id = session.get("session_id")++ # Pass all parameters needed for direct execution+ queue_processor.notify_research_queued(+ username,+ research_id,+ session_id=session_id,+ query=query,+ mode=mode,- settings_snapshot=research_meta,++ settings_snapshot=research_settings,+ model_provider=model_provider,+ model=model,+ custom_endpoint=custom_endpoint,+ search_engine=search_engine,+ max_results=max_results,+ time_period=time_period,+ iterations=iterations,+ questions_per_iteration=questions_per_iteration,+ strategy=strategy,+ )++ 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}")return jsonify(- {"status": "error", "message": "Research not found"}- ), 404+ {"status": "error", "message": "Failed to create research entry"}+ ), 500- status = result[0]+ # Only start the research if not queued+ if not should_queue:+ # Save the research strategy to the database before starting the thread+ try:+ from ..services.research_service import save_research_strategy- # If it's not in progress, return an error- if status != "in_progress":- conn.close()- return (- jsonify(- {"status": "error", "message": "Research is not in progress"}- ),- 400,- )+ save_research_strategy(research_id, strategy, username=username)+ except Exception as e:+ logger.warning(f"Could not save research strategy: {e}")- # Check if it's in the active_research dict- if research_id not in active_research:- # Update the status in the database- cursor.execute(- "UPDATE research_history SET status = ? WHERE id = ?",- ("suspended", research_id),+ # Debug logging for settings snapshot- snapshot_data = research_meta.get("settings_snapshot", {})++ snapshot_data = research_settings.get("settings_snapshot", {})+ logger.debug(+ f"Settings snapshot being passed to thread: {snapshot_data}")- conn.commit()- conn.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"},- }+ 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")- # Add to in-memory log- active_research[research_id]["log"].append(log_entry)+ # Get the user's password for metrics access in background thread+ # Try session password store first+ from ...database.session_passwords import session_password_store- # Add to database log- logger.log("MILESTONE", f"Research ended: {termination_message}")+ session_id = session.get("session_id")+ user_password = None- # Update the log in the database (old way for backward compatibility)- cursor.execute(- "SELECT progress_log FROM research_history WHERE id = ?", (research_id,)- )- log_result = cursor.fetchone()- if log_result:- try:- current_log = json.loads(log_result[0])- except Exception:- current_log = []- current_log.append(log_entry)- cursor.execute(- "UPDATE research_history SET progress_log = ? WHERE id = ?",- (json.dumps(current_log), research_id),+ if session_id:+ user_password = session_password_store.get_session_password(+ username, session_id+ )++ # Fallback to g.user_password (set by middleware if temp_auth was used)+ if not user_password:+ user_password = getattr(g, "user_password", None)++ # Last resort: try temp_auth_store+ if not user_password:+ from ...database.temp_auth import temp_auth_store++ auth_token = session.get("temp_auth_token")+ if auth_token:+ # Use peek_auth to avoid consuming the token+ auth_data = temp_auth_store.peek_auth(auth_token)+ if auth_data and auth_data[0] == username:+ user_password = auth_data[1]++ if not user_password:+ logger.warning(+ f"No password available for metrics access for user {username}"+ )++ # Start the research process with the selected parameters+ research_thread = start_research_process(+ research_id,+ query,+ mode,+ active_research,+ termination_flags,+ run_research_process,+ username=username, # Pass username to the thread+ user_password=user_password, # Pass password for metrics database access+ model_provider=model_provider,+ model=model,+ custom_endpoint=custom_endpoint,+ search_engine=search_engine,+ max_results=max_results,+ time_period=time_period,+ iterations=iterations,+ questions_per_iteration=questions_per_iteration,+ strategy=strategy,+ settings_snapshot=snapshot_data, # Pass complete settings)- # IMMEDIATELY update the status to 'suspended' to avoid race conditions- cursor.execute(- "UPDATE research_history SET status = ? WHERE id = ?",- ("suspended", research_id),- )- conn.commit()- conn.close()+ # Update the active research record with the actual thread ID+ try:+ 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})+++ @research_bp.route("/api/terminate/<string:research_id>", methods=["POST"])+ @login_required+ def terminate_research(research_id):+ """Terminate an in-progress research process"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401- # Emit a socket event for the termination request+ # Check if the research exists and is in progresstry:- event_data = {- "status": "suspended", # Changed from 'terminating' to 'suspended'- "message": "Research was suspended by user request",- }+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )- from ..services.socket_service import emit_socket_event+ if not research:+ return jsonify(+ {"status": "error", "message": "Research not found"}+ ), 404- emit_socket_event(f"research_progress_{research_id}", event_data)+ status = research.status- except Exception:- logger.exception("Socket emit error (non-critical)")+ # If it's already completed or suspended, return success+ if status in ["completed", "suspended", "error"]:+ return jsonify(+ {+ "status": "success",+ "message": f"Research already {status}",+ }+ )- return jsonify(- {"status": "success", "message": "Research termination requested"}- )+ # 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"}+ )+ # Set the termination flag+ termination_flags[research_id] = True- @research_bp.route("/api/delete/<int:research_id>", methods=["DELETE"])- def delete_research(research_id):- """Delete a research record"""- conn = get_db_connection()- cursor = conn.cursor()+ # 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"]- # First check if the research exists and is not in progress- cursor.execute(- "SELECT status, report_path FROM research_history WHERE id = ?",- (research_id,),- )- result = cursor.fetchone()+ # Create log entry+ log_entry = {+ "time": timestamp,+ "message": termination_message,+ "progress": current_progress,+ "metadata": {"phase": "termination"},+ }- if not result:- conn.close()- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404+ # Add to in-memory log+ active_research[research_id]["log"].append(log_entry)- status, report_path = result+ # Add to database log+ logger.log("MILESTONE", f"Research ended: {termination_message}")- # Don't allow deleting research in progress- if status == "in_progress" and research_id in active_research:- conn.close()- return (- jsonify(- {- "status": "error",- "message": "Cannot delete research that is in 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)+ 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()++ # 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",}- ),- 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")+ from ..services.socket_service import SocketIOService- # Delete the database record- cursor.execute("DELETE FROM research_history WHERE id = ?", (research_id,))- conn.commit()- conn.close()+ SocketIOService().emit_socket_event(+ f"research_progress_{research_id}", event_data+ )- return jsonify({"status": "success"})+ 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/clear_history", methods=["POST"])- def clear_history():- """Clear all research history"""- try:- conn = get_db_connection()- cursor = conn.cursor()- # Get all research IDs first to clean up files- cursor.execute("SELECT id, report_path FROM research_history")- research_records = cursor.fetchall()+ @research_bp.route("/api/delete/<string:research_id>", methods=["DELETE"])+ @login_required+ def delete_research(research_id):+ """Delete a research record"""+ username = session.get("username")+ if not username:+ return jsonify({"error": "Not authenticated"}), 401++ try:+ with get_user_db_session(username) as db_session:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )- # Clean up report files- for research_id, report_path in research_records:- # Skip active research- if research_id in active_research:- continue+ if not research:+ return jsonify(+ {"status": "error", "message": "Research not found"}+ ), 404++ status = research.status+ report_path = research.report_path++ # 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 existsif report_path and os.path.exists(report_path):@@@ -685,20 -954,19 +1042,20 @@@ def get_history()# Create a history itemitem = {- "id": research_id,- "query": query,- "mode": mode,- "status": status,- "created_at": created_at,- "completed_at": completed_at,+ "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": report_path,- "metadata": metadata, # Include parsed metadata+ "report_path": research.report_path,++ "metadata": research.research_meta, # Include metadata for news}- # Add title if not None- if title is not None:- item["title"] = title+ # Add title if it exists+ if hasattr(research, "title") and research.title is not None:+ item["title"] = research.titlehistory_items.append(item)diff --cc src/local_deep_research/web/services/research_service.pyindex ae357a0ac5,ed4a01fcba..7672bb22b9--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@@ -1,9 -1,9 +1,11 @@@import hashlib+import json+ import reimport threadingfrom datetime import datetimefrom pathlib import Path++from flask import g, sessionfrom loguru import loggerfrom ...config.llm_config import get_llm@@@ -753,156 -911,18 +913,172 @@@ Query: {query.first())+ # Preserve existing metadata and update with new values+ logger.info(+ f"Existing research_meta type: {type(research.research_meta)}"+ )+ logger.info(+ f"Existing research_meta value: {research.research_meta}"+ )++ # Handle both dict and string types for research_meta+ if isinstance(research.research_meta, dict):+ metadata = dict(research.research_meta)+ elif isinstance(research.research_meta, str):+ try:+ metadata = json.loads(research.research_meta)+ except json.JSONDecodeError:- logger.error(++ logger.exception(+ f"Failed to parse research_meta as JSON: {research.research_meta}"+ )+ metadata = {}+ else:+ metadata = {}++ logger.info(f"Metadata after loading: {metadata}")+ metadata.update(+ {+ "iterations": results["iterations"],+ "generated_at": datetime.utcnow().isoformat(),+ }+ )+ logger.info(f"Metadata after update: {metadata}")+# Use the helper function for consistent duration calculationduration_seconds = calculate_duration(- research.created_at, research.completed_at+ research.created_at, completed_at)research.status = "completed"research.completed_at = completed_atresearch.duration_seconds = duration_seconds- research.report_path = str(report_path)- # Note: report_content is already saved by CachedResearchService- # We don't need report_path anymore++ # Note: report_content is saved by CachedResearchService++ # report_path is not used in encrypted database version++ # Generate headline and topics only for news searches+ if (+ metadata.get("is_news_search")+ or metadata.get("search_type") == "news_analysis"+ ):+ try:+ from ...news.utils.headline_generator import (+ generate_headline,+ )+ from ...news.utils.topic_generator import (+ generate_topics,+ )+- # Read the report content for better headline/topic generation++ # Get the report content from database for better headline/topic generation+ report_content = ""- if report_path.exists():- report_content = report_path.read_text(- encoding="utf-8"- ) # Read FULL report, no truncation- logger.info(- f"Read {len(report_content)} chars from report for headline generation"++ try:++ from ...memory_cache.cached_services import (++ CachedResearchService,++ )++++ cached_research = CachedResearchService(++ db_session, username++ )++ report_data = cached_research.get_report(++ research_id+ )- else:++ if report_data and report_data.get(++ "content"++ ):++ report_content = report_data["content"]++ logger.info(++ f"Retrieved {len(report_content)} chars from database for headline generation"++ )++ else:++ logger.warning(++ f"No report content found in database for research_id: {research_id}"++ )++ except Exception as e:+ logger.warning(- f"Report path does not exist: {report_path}"++ f"Could not retrieve report content from database: {e}"+ )++ # Generate headline+ logger.info(+ f"Generating headline for query: {query[:100]}"+ )+ headline = generate_headline(+ query, report_content+ )+ metadata["generated_headline"] = headline++ # Generate topics+ logger.info(+ f"Generating topics with category: {metadata.get('category', 'News')}"+ )+ topics = generate_topics(+ query=query,+ findings=report_content,+ category=metadata.get("category", "News"),+ max_topics=6,+ )+ metadata["generated_topics"] = topics++ logger.info(f"Generated headline: {headline}")+ logger.info(f"Generated topics: {topics}")++ except Exception as e:+ logger.warning(+ f"Could not generate headline/topics: {e}"+ )++ logger.info(f"Final metadata being saved: {metadata}")+ research.research_meta = metadatadb_session.commit()+ logger.info(+ f"Database commit completed for research_id: {research_id}"+ )++ # Update subscription if this was triggered by a subscription+ if metadata.get("subscription_id"):+ try:+ from ...news.subscription_manager.storage import (+ SQLSubscriptionStorage,+ )+ from datetime import (+ datetime as dt,+ timezone,+ timedelta,+ )++ sub_storage = SQLSubscriptionStorage()+ subscription_id = metadata["subscription_id"]++ # Get subscription to find refresh interval+ subscription = sub_storage.get(subscription_id)+ if subscription:+ refresh_hours = subscription.get(+ "refresh_hours", 4+ )+ now = dt.now(timezone.utc)+ next_refresh = now + timedelta(+ hours=refresh_hours+ )++ # Update refresh times+ sub_storage.update_refresh_time(+ subscription_id=subscription_id,+ last_refresh=now,+ next_refresh=next_refresh,+ )++ # Increment stats+ sub_storage.increment_stats(+ subscription_id, 1+ )++ logger.info(+ f"Updated subscription {subscription_id} refresh times"+ )+ except Exception as e:+ logger.warning(+ f"Could not update subscription refresh time: {e}"+ )logger.info(f"Database updated successfully for research_id: {research_id}"@@@ -976,84 -1016,15 +1172,102 @@@.first())+ # Preserve existing metadata and merge with report metadata+ logger.info(+ f"Full report - Existing research_meta type: {type(research.research_meta)}"+ )+ logger.info(+ f"Full report - Existing research_meta value: {research.research_meta}"+ )++ # Handle both dict and string types for research_meta+ if isinstance(research.research_meta, dict):+ metadata = dict(research.research_meta)+ elif isinstance(research.research_meta, str):+ try:+ metadata = json.loads(research.research_meta)+ except json.JSONDecodeError:- logger.error(++ logger.exception(+ f"Failed to parse research_meta as JSON: {research.research_meta}"+ )+ metadata = {}+ else:+ metadata = {}++ logger.info(f"Full report - Metadata after loading: {metadata}")+ metadata.update(final_report["metadata"])+ metadata["iterations"] = results["iterations"]+# Use the helper function for consistent duration calculationduration_seconds = calculate_duration(- research.created_at, research.completed_at+ research.created_at, completed_at)research.status = "completed"research.completed_at = completed_atresearch.duration_seconds = duration_seconds- research.report_path = str(report_path)- # Note: report_content is already saved by CachedResearchService++ # Note: report_content is saved by CachedResearchService++ # report_path is not used in encrypted database version++ # Generate headline and topics only for news searches+ if (+ metadata.get("is_news_search")+ or metadata.get("search_type") == "news_analysis"+ ):+ try:+ from ..news.utils.headline_generator import (+ generate_headline,+ )+ from ..news.utils.topic_generator import (+ generate_topics,+ )+- # Read the report content for better headline/topic generation++ # Get the report content from database for better headline/topic generation+ report_content = ""- if report_path.exists():- report_content = report_path.read_text(- encoding="utf-8"- ) # Read FULL report, no truncation++ try:++ from ...memory_cache.cached_services import (++ CachedResearchService,++ )++++ cached_research = CachedResearchService(++ db_session, username++ )++ report_data = cached_research.get_report(++ research_id++ )++ if report_data and report_data.get("content"):++ report_content = report_data["content"]++ else:++ logger.warning(++ f"No report content found in database for research_id: {research_id}"++ )++ except Exception as e:++ logger.warning(++ f"Could not retrieve report content from database: {e}"++ )++ # Generate headline+ headline = generate_headline(query, report_content)+ metadata["generated_headline"] = headline++ # Generate topics+ topics = generate_topics(+ query=query,+ findings=report_content,+ category=metadata.get("category", "News"),+ max_topics=6,+ )+ metadata["generated_topics"] = topics++ logger.info(f"Generated headline: {headline}")+ logger.info(f"Generated topics: {topics}")++ except Exception as e:+ logger.warning(+ f"Could not generate headline/topics: {e}"+ )++ research.research_meta = metadatadb_session.commit()@@@ -1200,24 -1135,8 +1414,28 @@@enhanced_report_content = Nonereport_path_to_save = None- # Update metadata with more context about the error- metadata = {"phase": "error", "error": user_friendly_error}+ # Get existing metadata from database first+ existing_metadata = {}+ try:- db_session = get_db_session()- with db_session:- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )- if research and research.research_meta:- existing_metadata = dict(research.research_meta)++ # Get username from the research context++ username = getattr(g, "username", None) or session.get(++ "username"++ )++ if username:++ with get_user_db_session(username) as db_session:++ research = (++ db_session.query(ResearchHistory)++ .filter_by(id=research_id)++ .first()++ )++ if research and research.research_meta:++ existing_metadata = dict(research.research_meta)+ except Exception:+ logger.exception("Failed to get existing metadata")++ # Update metadata with more context about the error while preserving existing values+ metadata = existing_metadata+ metadata.update({"phase": "error", "error": user_friendly_error})if error_context:metadata.update(error_context)if enhanced_report_content: