Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: Fix benchmark charts and improve real-time metrics display

LearningCircuit23ce85008bd5
diff --git a/.gitignore b/.gitignore
index 7de3e4394c..af0df5fabd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -196,3 +196,8 @@ screenshots/
# Ignore cookiecutter-generated files.
docker-compose.*.yml
scripts/*.sh
+backup/
+
+# Security - ignore generated secret keys
+.secret_key
+.cache_key_secret
diff --git a/examples/api_usage/programmatic/comprehensive_tutorial.py b/examples/api_usage/programmatic/comprehensive_tutorial.py
index 811ca96f15..7953ba074c 100644
--- a/examples/api_usage/programmatic/comprehensive_tutorial.py
+++ b/examples/api_usage/programmatic/comprehensive_tutorial.py
@@ -35,8 +35,8 @@ from local_deep_research.api import (
detailed_research,
generate_report,
)
-from local_deep_research.settings import CachedSettingsManager
from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.settings import SettingsManager
# Additional imports for advanced features
from local_deep_research.config.llm_config import get_available_providers
@@ -97,7 +97,7 @@ def section_1_authentication():
with get_user_db_session(
username=USERNAME, password=PASSWORD
) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Display current configuration
@@ -142,7 +142,7 @@ def section_2_quick_summary():
print_section("2. GENERATING QUICK SUMMARIES")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Example 1: Basic quick summary
@@ -189,7 +189,7 @@ def section_3_detailed_research():
print_section("3. CONDUCTING DETAILED RESEARCH")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
print("Starting detailed research (this may take a few minutes)...")
@@ -247,7 +247,7 @@ def section_4_report_generation():
print_section("4. GENERATING COMPREHENSIVE REPORTS")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
print(
@@ -316,7 +316,7 @@ def section_5_search_engines():
print_section("5. USING DIFFERENT SEARCH ENGINES")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Test different search engines
@@ -450,7 +450,7 @@ def section_6_custom_retriever():
custom_retriever = CustomDocumentRetriever(sample_docs)
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
print("Using custom retriever for research...")
@@ -504,7 +504,7 @@ def section_7_analyzing_results():
print_section("7. ANALYZING AND PROCESSING RESULTS")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Conduct research for analysis
@@ -642,7 +642,7 @@ def section_8_export_formats():
print_section("8. EXPORTING IN DIFFERENT FORMATS")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# First, generate a research result
@@ -752,7 +752,7 @@ def section_9_advanced_features():
print_section("9. ADVANCED FEATURES AND TIPS")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
print("1. Performance Optimization Tips:")
diff --git a/examples/api_usage/programmatic/programmatic_access_v1.py b/examples/api_usage/programmatic/programmatic_access_v1.py
index a4c8386c0d..b220edc399 100644
--- a/examples/api_usage/programmatic/programmatic_access_v1.py
+++ b/examples/api_usage/programmatic/programmatic_access_v1.py
@@ -18,9 +18,9 @@ from local_deep_research.api.research_functions import (
detailed_research,
generate_report,
)
-from local_deep_research.settings import CachedSettingsManager
from local_deep_research.database.session_context import get_user_db_session
from local_deep_research.config.llm_config import get_available_providers
+from local_deep_research.settings import SettingsManager
# Configuration - UPDATE THESE!
USERNAME = "your_username" # Change this to your LDR username
@@ -36,7 +36,7 @@ def example_basic_usage():
username=USERNAME, password=PASSWORD
) as session:
# Create settings manager
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Show current configuration
@@ -76,7 +76,7 @@ def example_custom_parameters():
print("\n=== Example 2: Custom Parameters ===")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Custom research parameters
@@ -111,7 +111,7 @@ def example_detailed_research():
print("\n=== Example 3: Detailed Research ===")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Run detailed research
@@ -152,7 +152,7 @@ def example_generate_report():
print("\n=== Example 4: Generate Report ===")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Generate comprehensive report
@@ -204,7 +204,7 @@ def example_check_providers():
print("\n=== Example 5: Available Providers ===")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Get available providers (with settings context)
@@ -247,7 +247,7 @@ def example_search_engines():
print("\n=== Example 6: Search Engine Selection ===")
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Example with Wikipedia only
diff --git a/examples/api_usage/programmatic/retriever_usage_example.py b/examples/api_usage/programmatic/retriever_usage_example.py
index 116279f674..59e28f3ce6 100644
--- a/examples/api_usage/programmatic/retriever_usage_example.py
+++ b/examples/api_usage/programmatic/retriever_usage_example.py
@@ -22,8 +22,8 @@ from local_deep_research.api.research_functions import (
detailed_research,
quick_summary,
)
-from local_deep_research.settings import CachedSettingsManager
from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.settings import SettingsManager
# Configuration - UPDATE THESE!
USERNAME = "your_username" # Change this to your LDR username
@@ -68,7 +68,7 @@ def example_single_retriever():
# Authenticate and get settings
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
# Get settings snapshot for thread safety
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
print(f"Authenticated as: {USERNAME}")
@@ -99,7 +99,7 @@ def example_multiple_retrievers():
business_retriever = MockRetriever()
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Use them with LDR
@@ -127,7 +127,7 @@ def example_hybrid_search():
retriever = MockRetriever()
with get_user_db_session(username=USERNAME, password=PASSWORD) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session, USERNAME)
settings_snapshot = settings_manager.get_all_settings()
# Use retriever + web search
@@ -194,7 +194,7 @@ def example_real_vector_store():
with get_user_db_session(
username=USERNAME, password=PASSWORD
) as session:
- settings_manager = CachedSettingsManager(session, USERNAME)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
# Use with LDR
diff --git a/scripts/dev/restart_server.sh b/scripts/dev/restart_server.sh
new file mode 100755
index 0000000000..fadbf13ca2
--- /dev/null
+++ b/scripts/dev/restart_server.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# Script to restart the LDR server
+
+echo "Stopping existing LDR server..."
+pkill -f "python -m local_deep_research.web.app" 2>/dev/null || echo "No existing server found"
+
+# Wait a moment for the process to stop
+sleep 1
+
+echo "Starting LDR server..."
+# Change to the script's parent directory (project root)
+cd "$(dirname "$0")/../.."
+
+# Start server in background and detach from terminal
+(nohup pdm run python -m local_deep_research.web.app > /tmp/ldr_server.log 2>&1 &) &
+SERVER_PID=$!
+
+# Give it a moment to start
+sleep 2
+
+echo "Server started. PID: $SERVER_PID"
+echo "Logs: /tmp/ldr_server.log"
+echo "URL: http://127.0.0.1:5000"
+echo ""
+echo "To check server status: ps aux | grep 'python -m local_deep_research.web.app'"
+echo "To view logs: tail -f /tmp/ldr_server.log"
+echo "To stop server: pkill -f 'python -m local_deep_research.web.app'"
+
+# Exit immediately - don't wait for background process
+exit 0
diff --git a/scripts/test_database_access.py b/scripts/test_database_access.py
deleted file mode 100644
index 7ad3c5d00d..0000000000
--- a/scripts/test_database_access.py
+++ /dev/null
@@ -1,156 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test database creation and access with the new centralized SQLCipher utilities.
-This simulates what happens during user registration and login.
-"""
-
-import sys
-from pathlib import Path
-
-# Add parent directory to path
-sys.path.insert(0, str(Path(__file__).parent.parent))
-
-from src.local_deep_research.database.encrypted_db import db_manager
-from src.local_deep_research.database.models import UserSettings
-
-
-def test_user_flow():
- """Test the complete user registration and login flow."""
-
- print("🧪 Testing Database Access with Centralized Utilities")
- print("=" * 60)
-
- # Test user details
- test_username = "test_user_hex"
- test_password = "test'pass\"with$pecial@chars!"
-
- print(f"\n1. Test user: {test_username}")
- print(f" Password: {test_password}")
- print(" (Contains special characters to test encoding)")
-
- # Step 1: Create user database (simulating registration)
- print("\n2. Creating user database (registration)...")
- try:
- # Close any existing connection first
- if test_username in db_manager.connections:
- db_manager.close_database(test_username)
-
- # Create new database
- success = db_manager.create_user_database(test_username, test_password)
- if success:
- print(" ✅ Database created successfully")
- else:
- print(" ❌ Failed to create database")
- return False
- except Exception as e:
- print(f" ❌ Error creating database: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
- # Step 2: Open database (simulating login)
- print("\n3. Opening database (login)...")
- try:
- success = db_manager.open_user_database(test_username, test_password)
- if success:
- print(" ✅ Database opened successfully")
- else:
- print(" ❌ Failed to open database")
- return False
- except Exception as e:
- print(f" ❌ Error opening database: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
- # Step 3: Test database operations
- print("\n4. Testing database operations...")
- try:
- session = db_manager.get_session(test_username)
- if not session:
- print(" ❌ Failed to get session")
- return False
-
- # Add a test settings record instead (User model not available in per-user DBs)
- setting = UserSettings(key="test.setting", value="test_value")
- session.add(setting)
- session.commit()
-
- # Query it back
- found_setting = (
- session.query(UserSettings).filter_by(key="test.setting").first()
- )
- if found_setting and found_setting.value == "test_value":
- print(" ✅ Database operations work correctly")
- else:
- print(" ❌ Failed to query data")
- return False
-
- session.close()
- except Exception as e:
- print(f" ❌ Error with database operations: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
- # Step 4: Test thread-safe session for metrics
- print("\n5. Testing thread-safe session for metrics...")
- try:
- metrics_session = db_manager.create_thread_safe_session_for_metrics(
- test_username, test_password
- )
-
- # Test a simple query
- from sqlalchemy import text
-
- result = metrics_session.execute(text("SELECT 1")).fetchone()
- if result and result[0] == 1:
- print(" ✅ Thread-safe metrics session works")
- else:
- print(" ❌ Thread-safe metrics session failed")
- return False
-
- metrics_session.close()
- except Exception as e:
- print(f" ❌ Error with metrics session: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
- # Step 5: Clean up
- print("\n6. Cleaning up...")
- try:
- db_manager.close_database(test_username)
-
- # Remove test database file
- db_path = (
- Path.home() / ".local/share/local-deep-research/encrypted_databases"
- )
- test_db_files = list(db_path.glob(f"*{test_username}*.db*"))
- for f in test_db_files:
- f.unlink()
- print(f" ✅ Removed {f.name}")
- except Exception as e:
- print(f" ⚠️ Cleanup warning: {e}")
-
- return True
-
-
-def main():
- """Run the test."""
- success = test_user_flow()
-
- print("\n" + "=" * 60)
- if success:
- print("✅ All tests passed! Database access is working correctly.")
- else:
- print("❌ Tests failed. Check the errors above.")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/test_metrics_flow.py b/scripts/test_metrics_flow.py
deleted file mode 100644
index 5a88a23617..0000000000
--- a/scripts/test_metrics_flow.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/env python3
-"""Test the complete metrics flow with hex encoding."""
-
-import sys
-from pathlib import Path
-
-# Add parent directory to path
-sys.path.insert(0, str(Path(__file__).parent.parent))
-
-from src.local_deep_research.database.encrypted_db import db_manager
-from src.local_deep_research.database.models import TokenUsage
-from src.local_deep_research.database.thread_metrics import metrics_writer
-
-
-def test_metrics_flow():
- """Test creating a database and saving metrics."""
-
- # Test user with special chars in password
- username = "test_metrics_user"
- password = "test'pass\"with$pecial"
-
- print("🧪 Testing Metrics Flow with Hex Encoding")
- print("=" * 60)
- print(f"Username: {username}")
- print(f"Password: {password} (contains special characters)")
-
- try:
- # Step 1: Create database
- print("\n1. Creating database...")
- if not db_manager.create_user_database(username, password):
- print(" ❌ Failed to create database")
- return False
- print(" ✅ Database created")
-
- # Step 2: Open database
- print("\n2. Opening database...")
- if not db_manager.open_user_database(username, password):
- print(" ❌ Failed to open database")
- return False
- print(" ✅ Database opened")
-
- # Step 3: Simulate metrics from thread
- print("\n3. Simulating metrics from background thread...")
-
- # Set password for thread
- metrics_writer.set_user_password(username, password)
-
- # Write test metrics
- token_data = {
- "model_name": "test_model",
- "provider": "test_provider",
- "prompt_tokens": 100,
- "completion_tokens": 50,
- "research_query": "test query",
- "research_mode": "quick",
- "research_phase": "search",
- "search_iteration": 1,
- }
-
- try:
- metrics_writer.write_token_metrics(username, 123, token_data)
- print(" ✅ Metrics written from thread")
- except Exception as e:
- print(f" ❌ Failed to write metrics: {e}")
- return False
-
- # Step 4: Verify metrics were saved
- print("\n4. Verifying metrics...")
- session = db_manager.get_session(username)
- count = session.query(TokenUsage).count()
-
- if count > 0:
- print(f" ✅ Found {count} token usage record(s)")
- token = session.query(TokenUsage).first()
- print(f" Model: {token.model_name}")
- print(f" Tokens: {token.total_tokens}")
- else:
- print(" ❌ No metrics found")
- return False
-
- session.close()
-
- # Clean up
- print("\n5. Cleaning up...")
- db_manager.close_user_database(username)
-
- # Remove test database
- import hashlib
-
- user_hash = hashlib.sha256(username.encode()).hexdigest()[:16]
- db_path = (
- Path.home()
- / ".local/share/local-deep-research/encrypted_databases"
- / f"ldr_user_{user_hash}.db"
- )
- if db_path.exists():
- db_path.unlink()
- print(" ✅ Test database removed")
-
- return True
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
-
-def main():
- """Run the test."""
- success = test_metrics_flow()
-
- print("\n" + "=" * 60)
- if success:
- print(
- "✅ Metrics flow test PASSED! The monitoring dashboard should work."
- )
- else:
- print("❌ Metrics flow test FAILED.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/test_search_metrics.py b/scripts/test_search_metrics.py
deleted file mode 100644
index 6f1d41b516..0000000000
--- a/scripts/test_search_metrics.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/env python3
-"""Test search metrics collection with hex encoding."""
-
-import sys
-import time
-from pathlib import Path
-
-# Add parent directory to path
-sys.path.insert(0, str(Path(__file__).parent.parent))
-
-from src.local_deep_research.database.encrypted_db import db_manager
-from src.local_deep_research.database.models import SearchCall
-from src.local_deep_research.metrics.search_tracker import (
- get_search_tracker,
- set_search_context,
-)
-
-
-def test_search_metrics():
- """Test search metrics collection."""
-
- # Test user with special chars in password
- username = "test_search_user"
- password = "test'pass\"with$pecial"
-
- print("🔍 Testing Search Metrics with Hex Encoding")
- print("=" * 60)
- print(f"Username: {username}")
- print(f"Password: {password} (contains special characters)")
-
- try:
- # Step 1: Create database
- print("\n1. Creating database...")
- if not db_manager.create_user_database(username, password):
- print(" ❌ Failed to create database")
- return False
- print(" ✅ Database created")
-
- # Step 2: Open database
- print("\n2. Opening database...")
- if not db_manager.open_user_database(username, password):
- print(" ❌ Failed to open database")
- return False
- print(" ✅ Database opened")
-
- # Step 3: Simulate search calls in a background thread
- print("\n3. Simulating search calls in background thread...")
-
- # Function to run searches in thread
- def run_searches():
- # Set search context inside the thread
- search_context = {
- "research_id": "test-research-123",
- "research_query": "test search query",
- "research_mode": "quick",
- "research_phase": "search",
- "search_iteration": 1,
- "username": username,
- "user_password": password,
- }
- set_search_context(search_context)
- print(" ✅ Search context set in thread")
-
- # Get tracker instance
- tracker = get_search_tracker()
-
- # Simulate searches from different engines
- searches = [
- ("searxng", "What is Node.js", 25, 450, True, None),
- ("arxiv", "machine learning papers", 10, 1200, True, None),
- ("pubmed", "covid vaccines", 15, 800, True, None),
- (
- "google",
- "python tutorials",
- 30,
- 350,
- False,
- "Rate limit exceeded",
- ),
- ]
-
- for engine, query, results, time_ms, success, error in searches:
- tracker.record_search(
- engine_name=engine,
- query=query,
- results_count=results,
- response_time_ms=time_ms,
- success=success,
- error_message=error,
- )
- print(f" ✅ Recorded search: {engine} - '{query[:30]}...'")
- time.sleep(0.1) # Small delay between searches
-
- # Run in a thread to simulate real research
- import threading
-
- search_thread = threading.Thread(target=run_searches)
- search_thread.start()
- search_thread.join()
-
- # Step 4: Verify metrics were saved
- print("\n4. Verifying search metrics...")
- session = db_manager.get_session(username)
- count = session.query(SearchCall).count()
-
- if count > 0:
- print(f" ✅ Found {count} search call record(s)")
-
- # Show some details
- calls = session.query(SearchCall).all()
- for call in calls:
- print(
- f" - {call.search_engine}: {call.results_count} results in {call.response_time_ms}ms"
- )
- if call.error_message:
- print(f" Error: {call.error_message}")
- else:
- print(" ❌ No search metrics found")
- return False
-
- session.close()
-
- # Step 5: Test retrieval of metrics
- print("\n5. Testing metrics retrieval...")
- tracker = get_search_tracker()
- metrics = tracker.get_search_metrics(
- period="all",
- research_mode="all",
- username=username,
- password=password,
- )
-
- if metrics["search_engine_stats"]:
- print(" ✅ Search engine statistics:")
- for stat in metrics["search_engine_stats"]:
- print(
- f" - {stat['engine']}: {stat['call_count']} calls, "
- f"{stat['success_rate']:.1f}% success rate"
- )
-
- # Clean up
- print("\n6. Cleaning up...")
- db_manager.close_user_database(username)
-
- # Remove test database
- import hashlib
-
- user_hash = hashlib.sha256(username.encode()).hexdigest()[:16]
- db_path = (
- Path.home()
- / ".local/share/local-deep-research/encrypted_databases"
- / f"ldr_user_{user_hash}.db"
- )
- if db_path.exists():
- db_path.unlink()
- print(" ✅ Test database removed")
-
- return True
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
- import traceback
-
- traceback.print_exc()
- return False
-
-
-def main():
- """Run the test."""
- success = test_search_metrics()
-
- print("\n" + "=" * 60)
- if success:
- print("✅ Search metrics test PASSED! Search monitoring should work.")
- else:
- print("❌ Search metrics test FAILED.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
index 57957ec251..91e4d78d0e 100644
--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
@@ -7,7 +7,6 @@ from typing import Dict, List
from loguru import logger
-from ...utilities.db_utils import get_db_setting
from ...utilities.search_utilities import remove_think_tags
from .base_filter import BaseFilter
@@ -21,6 +20,7 @@ class CrossEngineFilter(BaseFilter):
max_results=None,
default_reorder=True,
default_reindex=True,
+ settings_snapshot=None,
):
"""
Initialize the cross-engine filter.
@@ -30,12 +30,20 @@ class CrossEngineFilter(BaseFilter):
max_results: Maximum number of results to keep after filtering
default_reorder: Default setting for reordering results by relevance
default_reindex: Default setting for reindexing results after filtering
+ settings_snapshot: Settings snapshot for thread context
"""
super().__init__(model)
# Get max_results from database settings if not provided
if max_results is None:
+ # Import here to avoid circular import
+ from ...config.search_config import get_setting_from_snapshot
+
max_results = int(
- get_db_setting("search.cross_engine_max_results", 100)
+ get_setting_from_snapshot(
+ "search.cross_engine_max_results",
+ 100,
+ settings_snapshot=settings_snapshot,
+ )
)
self.max_results = max_results
self.default_reorder = default_reorder
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index ede1e5386d..f23d5cc30e 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -10,7 +10,7 @@ from methodtools import lru_cache
from ...config.llm_config import get_llm
from ...database.models import Journal
from ...search_system import AdvancedSearchSystem
-from ...utilities.db_utils import get_db_session, get_db_setting
+from ...utilities.db_utils import get_db_session
from ...web_search_engines.search_engine_factory import create_search_engine
from .base_filter import BaseFilter
@@ -35,6 +35,7 @@ class JournalReputationFilter(BaseFilter):
max_context: int | None = None,
exclude_non_published: bool | None = None,
quality_reanalysis_period: timedelta | None = None,
+ settings_snapshot: Dict[str, Any] | None = None,
):
"""
Args:
@@ -49,6 +50,7 @@ class JournalReputationFilter(BaseFilter):
don't have an associated journal publication.
quality_reanalysis_period: Period at which to update journal
quality assessments.
+ settings_snapshot: Settings snapshot for thread context.
"""
super().__init__(model)
@@ -58,40 +60,64 @@ class JournalReputationFilter(BaseFilter):
self.__threshold = reliability_threshold
if self.__threshold is None:
+ # Import here to avoid circular import
+ from ...config.search_config import get_setting_from_snapshot
+
self.__threshold = int(
- get_db_setting("search.journal_reputation.threshold", 4)
+ get_setting_from_snapshot(
+ "search.journal_reputation.threshold",
+ 4,
+ settings_snapshot=settings_snapshot,
+ )
)
self.__max_context = max_context
if self.__max_context is None:
self.__max_context = int(
- get_db_setting("search.journal_reputation.max_context", 3000)
+ get_setting_from_snapshot(
+ "search.journal_reputation.max_context",
+ 3000,
+ settings_snapshot=settings_snapshot,
+ )
)
self.__exclude_non_published = exclude_non_published
if self.__exclude_non_published is None:
self.__exclude_non_published = bool(
- get_db_setting(
- "search.journal_reputation.exclude_non_published", False
+ get_setting_from_snapshot(
+ "search.journal_reputation.exclude_non_published",
+ False,
+ settings_snapshot=settings_snapshot,
)
)
self.__quality_reanalysis_period = quality_reanalysis_period
if self.__quality_reanalysis_period is None:
self.__quality_reanalysis_period = timedelta(
days=int(
- get_db_setting(
- "search.journal_reputation.reanalysis_period", 365
+ get_setting_from_snapshot(
+ "search.journal_reputation.reanalysis_period",
+ 365,
+ settings_snapshot=settings_snapshot,
)
)
)
+ # Store settings_snapshot for later use
+ self.__settings_snapshot = settings_snapshot
+
# SearXNG is required so we can search the open web for reputational
# information.
- self.__engine = create_search_engine("searxng", llm=self.model)
+ self.__engine = create_search_engine(
+ "searxng", llm=self.model, settings_snapshot=settings_snapshot
+ )
if self.__engine is None:
raise JournalFilterError("SearXNG initialization failed.")
@classmethod
def create_default(
- cls, model: BaseChatModel | None = None, *, engine_name: str
+ cls,
+ model: BaseChatModel | None = None,
+ *,
+ engine_name: str,
+ settings_snapshot: Dict[str, Any] | None = None,
) -> Optional["JournalReputationFilter"]:
"""
Initializes a default configuration of the filter based on the settings.
@@ -100,23 +126,30 @@ class JournalReputationFilter(BaseFilter):
model: Explicitly specify the LLM to use.
engine_name: The name of the search engine. Will be used to check
the enablement status for that engine.
+ settings_snapshot: Settings snapshot for thread context.
Returns:
The filter that it created, or None if filtering is disabled in
the settings, or misconfigured.
"""
+ # Import here to avoid circular import
+ from ...config.search_config import get_setting_from_snapshot
+
if not bool(
- get_db_setting(
+ get_setting_from_snapshot(
f"search.engine.web.{engine_name}.journal_reputation.enabled",
True,
+ settings_snapshot=settings_snapshot,
)
):
return None
try:
# Initialize the filter with default settings.
- return JournalReputationFilter(model=model)
+ return JournalReputationFilter(
+ model=model, settings_snapshot=settings_snapshot
+ )
except JournalFilterError:
logger.error(
"SearXNG is not configured, but is required for "
@@ -138,6 +171,7 @@ class JournalReputationFilter(BaseFilter):
# We clamp down on the default iterations and questions for speed.
max_iterations=2,
questions_per_iteration=3,
+ settings_snapshot=self.__settings_snapshot,
)
@lru_cache(maxsize=1024)
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
index a4201253c4..4620b83322 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
@@ -106,9 +106,17 @@ class BrowseCompEntityStrategy(BaseSearchStrategy):
"""
def __init__(
- self, model=None, search=None, all_links_of_system=None, **kwargs
+ self,
+ model=None,
+ search=None,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ **kwargs,
):
- super().__init__(all_links_of_system=all_links_of_system)
+ super().__init__(
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
# Store model and search engine
self.model = model
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
index 75165f8949..96f052e34a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
@@ -53,9 +53,10 @@ class BrowseCompOptimizedStrategy(BaseSearchStrategy):
confidence_threshold: float = 0.90,
max_iterations: int = 1, # This is for source-based strategy iterations
questions_per_iteration: int = 3, # This is for source-based strategy questions
+ settings_snapshot=None,
):
"""Initialize the BrowseComp-optimized strategy."""
- super().__init__(all_links_of_system)
+ super().__init__(all_links_of_system, settings_snapshot)
self.model = model
self.search = search
self.max_browsecomp_iterations = max_browsecomp_iterations
diff --git a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
index 9814c86cbd..7922d5c287 100644
--- a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
@@ -45,6 +45,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
max_search_iterations: int = 2,
questions_per_iteration: int = 3,
min_candidates_per_stage: int = 20, # Need more candidates before filtering
+ settings_snapshot=None,
):
"""Initialize the constrained search strategy."""
super().__init__(
@@ -57,6 +58,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
evidence_threshold=evidence_threshold,
max_search_iterations=max_search_iterations,
questions_per_iteration=questions_per_iteration,
+ settings_snapshot=settings_snapshot,
)
self.min_candidates_per_stage = min_candidates_per_stage
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
index c231b5df81..554e644560 100644
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
@@ -44,9 +44,10 @@ class EvidenceBasedStrategy(BaseSearchStrategy):
evidence_threshold: float = 0.6,
max_search_iterations: int = 2, # For source-based sub-searches
questions_per_iteration: int = 3,
+ settings_snapshot=None,
):
"""Initialize the evidence-based strategy."""
- super().__init__(all_links_of_system)
+ super().__init__(all_links_of_system, settings_snapshot)
self.model = model
self.search = search
self.max_iterations = max_iterations
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index 239ce964a1..c956ab4eba 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -56,9 +56,10 @@ class FocusedIterationStrategy(BaseSearchStrategy):
max_iterations: int = 8, # OPTIMAL FOR SIMPLEQA: 90%+ accuracy achieved
questions_per_iteration: int = 5, # OPTIMAL FOR SIMPLEQA: proven config
use_browsecomp_optimization: bool = True, # True for 90%+ accuracy with forced_answer handler
+ settings_snapshot=None,
):
"""Initialize with components optimized for focused iteration."""
- super().__init__(all_links_of_system)
+ super().__init__(all_links_of_system, settings_snapshot)
self.search = search or get_search()
self.model = model or get_llm()
self.progress_callback = None
@@ -366,7 +367,11 @@ class FocusedIterationStrategy(BaseSearchStrategy):
def search_question(q):
try:
- result = self.search.run(q)
+ # Get the current research context to pass explicitly
+ from ...metrics.search_tracker import get_search_tracker
+
+ current_context = get_search_tracker()._get_research_context()
+ result = self.search.run(q, research_context=current_context)
return {"question": q, "results": result or []}
except Exception as e:
logger.error(f"Error searching '{q}': {e!s}")
@@ -418,7 +423,11 @@ class FocusedIterationStrategy(BaseSearchStrategy):
},
)
- result = self.search.run(q)
+ # Get the current research context to pass explicitly
+ from ...metrics.search_tracker import get_search_tracker
+
+ current_context = get_search_tracker()._get_research_context()
+ result = self.search.run(q, research_context=current_context)
completed_searches += 1
# Report completion of this search
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
index ad9a83cb70..8a116a1f72 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -11,7 +11,7 @@ from loguru import logger
from ...citation_handler import CitationHandler
from ...config.llm_config import get_llm
from ...config.search_config import get_search
-from ...utilities.db_utils import get_db_setting
+from ...config.search_config import get_setting_from_snapshot
from ...utilities.search_utilities import extract_links_from_search_results
from ..findings.repository import FindingsRepository
from ..knowledge.standard_knowledge import StandardKnowledge
@@ -29,6 +29,7 @@ class IterDRAGStrategy(BaseSearchStrategy):
max_iterations=3,
subqueries_per_iteration=2,
all_links_of_system=None,
+ settings_snapshot=None,
):
"""Initialize the IterDRAG strategy with search and LLM.
@@ -38,8 +39,12 @@ class IterDRAGStrategy(BaseSearchStrategy):
max_iterations: Maximum number of iterations to run
subqueries_per_iteration: Number of sub-queries to generate per iteration
all_links_of_system: Optional list of links to initialize with
+ settings_snapshot: Settings snapshot for thread context
"""
- super().__init__(all_links_of_system=all_links_of_system)
+ 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.max_iterations = max_iterations
@@ -82,7 +87,12 @@ Initial Search Results:
return self.question_generator.generate_questions(
query,
context,
- int(get_db_setting("search.questions_per_iteration")),
+ int(
+ get_setting_from_snapshot(
+ "search.questions_per_iteration",
+ settings_snapshot=self.settings_snapshot,
+ )
+ ),
)
except Exception:
logger.exception("Error generating sub-queries")
@@ -431,7 +441,11 @@ Please try again with a different query or contact support.
# Compress knowledge if needed
if (
- get_db_setting("general.knowledge_accumulation", "ITERATION")
+ get_setting_from_snapshot(
+ "general.knowledge_accumulation",
+ "ITERATION",
+ settings_snapshot=self.settings_snapshot,
+ )
== "ITERATION"
):
try:
diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
index 711c2883ec..c1fa61c180 100644
--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
@@ -294,9 +294,13 @@ class ModularStrategy(BaseSearchStrategy):
early_stopping: bool = True, # Enable early stopping by default
llm_constraint_processing: bool = True, # Enable LLM-driven constraint processing by default
immediate_evaluation: bool = True, # Enable immediate candidate evaluation by default
+ settings_snapshot=None,
**kwargs,
):
- super().__init__(all_links_of_system=all_links_of_system)
+ super().__init__(
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ )
self.model = model
self.search_engine = search
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
index c691410b67..a274f2ecf1 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
@@ -10,7 +10,7 @@ from loguru import logger
from ...citation_handler import CitationHandler
from ...config.llm_config import get_llm
from ...config.search_config import get_search
-from ...utilities.db_utils import get_db_setting
+from ...config.search_config import get_setting_from_snapshot
from ...utilities.search_utilities import extract_links_from_search_results
from ..filters.cross_engine_filter import CrossEngineFilter
from ..findings.repository import FindingsRepository
@@ -35,6 +35,7 @@ class ParallelSearchStrategy(BaseSearchStrategy):
filter_reindex: bool = True,
cross_engine_max_results: int = None,
all_links_of_system=None,
+ settings_snapshot=None,
):
"""Initialize with optional dependency injection for testing.
@@ -48,8 +49,12 @@ class ParallelSearchStrategy(BaseSearchStrategy):
filter_reindex: Whether to update result indices after filtering
cross_engine_max_results: Maximum number of results to keep after cross-engine filtering
all_links_of_system: Optional list of links to initialize with
+ settings_snapshot: Settings snapshot for thread context
"""
- super().__init__(all_links_of_system=all_links_of_system)
+ 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
@@ -65,6 +70,7 @@ class ParallelSearchStrategy(BaseSearchStrategy):
max_results=cross_engine_max_results,
default_reorder=filter_reorder,
default_reindex=filter_reindex,
+ settings_snapshot=settings_snapshot,
)
# Set include_full_content on the search engine if it supports it
@@ -117,7 +123,9 @@ class ParallelSearchStrategy(BaseSearchStrategy):
}
# Determine number of iterations to run
- iterations_to_run = get_db_setting("search.iterations")
+ iterations_to_run = get_setting_from_snapshot(
+ "search.iterations", settings_snapshot=self.settings_snapshot
+ )
logger.debug("Selected amount of iterations: " + str(iterations_to_run))
iterations_to_run = int(iterations_to_run)
try:
@@ -153,7 +161,10 @@ class ParallelSearchStrategy(BaseSearchStrategy):
current_knowledge=context,
query=query,
questions_per_iteration=int(
- get_db_setting("search.questions_per_iteration")
+ get_setting_from_snapshot(
+ "search.questions_per_iteration",
+ settings_snapshot=self.settings_snapshot,
+ )
),
questions_by_iteration=self.questions_by_iteration,
)
@@ -188,7 +199,10 @@ class ParallelSearchStrategy(BaseSearchStrategy):
current_knowledge=context,
query=query,
questions_per_iteration=int(
- get_db_setting("search.questions_per_iteration")
+ get_setting_from_snapshot(
+ "search.questions_per_iteration",
+ settings_snapshot=self.settings_snapshot,
+ )
),
questions_by_iteration=self.questions_by_iteration,
)
diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
index 96b3bb7b94..84ee51798a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
@@ -28,9 +28,13 @@ class RapidSearchStrategy(BaseSearchStrategy):
model=None,
citation_handler=None,
all_links_of_system=None,
+ settings_snapshot=None,
):
"""Initialize with optional dependency injection for testing."""
- super().__init__(all_links_of_system=all_links_of_system)
+ 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
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
index 49932a2069..24cd0d1d90 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
@@ -47,6 +47,7 @@ class SmartDecompositionStrategy(BaseSearchStrategy):
model: BaseChatModel,
search: Any,
all_links_of_system: List[str],
+ settings_snapshot=None,
**kwargs,
):
"""Initialize the smart decomposition strategy.
@@ -55,9 +56,10 @@ class SmartDecompositionStrategy(BaseSearchStrategy):
model: The language model to use
search: The search engine instance
all_links_of_system: List to store all encountered links
+ settings_snapshot: Settings snapshot for thread context
**kwargs: Additional parameters for sub-strategies
"""
- super().__init__(all_links_of_system)
+ super().__init__(all_links_of_system, settings_snapshot)
self.model = model
self.search = search
self.strategy_params = kwargs
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.py
index 18b1bd5a46..382492028f 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
@@ -46,7 +46,11 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# Use provided model and search, or fall back to defaults
# Note: If model/search are provided, they should already have the proper context
self.model = model if model is not None else get_llm()
- self.search = search if search is not None else get_search()
+ self.search = (
+ search
+ if search is not None
+ else get_search(settings_snapshot=settings_snapshot)
+ )
self.progress_callback = None
self.questions_by_iteration = {}
@@ -226,7 +230,15 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
@preserve_research_context
def search_question(q):
try:
- result = self.search.run(q)
+ # Get the current research context to pass explicitly
+ from ...metrics.search_tracker import get_search_tracker
+
+ current_context = (
+ get_search_tracker()._get_research_context()
+ )
+ result = self.search.run(
+ q, research_context=current_context
+ )
return {"question": q, "results": result or []}
except Exception as e:
logger.error(f"Error searching for '{q}': {e!s}")
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 7d0453e886..e4f6d2fab5 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -6,7 +6,7 @@ from loguru import logger
from ...citation_handler import CitationHandler
from ...config.llm_config import get_llm
from ...config.search_config import get_search
-from ...utilities.db_utils import get_db_setting
+from ...config.search_config import get_setting_from_snapshot
from ...utilities.enums import KnowledgeAccumulationApproach
from ...utilities.search_utilities import extract_links_from_search_results
from ..findings.repository import FindingsRepository
@@ -24,20 +24,34 @@ class StandardSearchStrategy(BaseSearchStrategy):
model=None,
citation_handler=None,
all_links_of_system=None,
+ settings_snapshot=None,
):
"""Initialize with optional dependency injection for testing."""
- super().__init__(all_links_of_system=all_links_of_system)
+ 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()
# Get iterations setting
- self.max_iterations = int(get_db_setting("search.iterations"))
+ self.max_iterations = int(
+ get_setting_from_snapshot(
+ "search.iterations", settings_snapshot=settings_snapshot
+ )
+ )
self.questions_per_iteration = int(
- get_db_setting("search.questions_per_iteration")
+ get_setting_from_snapshot(
+ "search.questions_per_iteration",
+ settings_snapshot=settings_snapshot,
+ )
)
self.context_limit = int(
- get_db_setting("general.knowledge_accumulation_context_limit")
+ get_setting_from_snapshot(
+ "general.knowledge_accumulation_context_limit",
+ settings_snapshot=settings_snapshot,
+ )
)
self.questions_by_iteration = {}
@@ -123,9 +137,10 @@ Iteration: {iteration + 1} of {total_iterations}"""
logger.info(f"Generated questions: {questions}")
question_count = len(questions)
- knowledge_accumulation = get_db_setting(
+ knowledge_accumulation = get_setting_from_snapshot(
"general.knowledge_accumulation",
"ITERATION",
+ settings_snapshot=self.settings_snapshot,
)
for q_idx, question in enumerate(questions):
question_progress_base = iteration_progress_base + (
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 225e5ad1c4..8e47dc82e5 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -243,6 +243,9 @@ def quick_summary(
"search_iteration": 0,
"search_engine_selected": kwargs.get("search_tool"),
"username": username, # Include username for metrics tracking
+ "user_password": kwargs.get(
+ "user_password"
+ ), # Include password for metrics tracking
}
set_search_context(search_context)
diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.py
index 543967313b..cb78f0d1af 100644
--- a/src/local_deep_research/api/settings_utils.py
+++ b/src/local_deep_research/api/settings_utils.py
@@ -11,7 +11,7 @@ import copy
from typing import Any, Dict, Optional, Union
from loguru import logger
-from ..settings import CachedSettingsManager
+from ..settings import SettingsManager
from ..settings.base import ISettingsManager
@@ -26,7 +26,7 @@ class InMemorySettingsManager(ISettingsManager):
def __init__(self):
"""Initialize with default settings from JSON file."""
# Create a base manager to get default settings
- self._base_manager = CachedSettingsManager(db_session=None)
+ self._base_manager = SettingsManager(db_session=None)
self._settings = {}
self._load_defaults()
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index e626130590..ffa25d1574 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -85,10 +85,12 @@ def get_evaluation_llm(
)
else:
# Fallback to database if no snapshot (not thread-safe)
- from ..utilities.db_utils import get_db_setting
+ from ..utilities.db_utils import get_setting_from_db_main_thread
try:
- api_key = get_db_setting("llm.openai_endpoint.api_key")
+ api_key = get_setting_from_db_main_thread(
+ "llm.openai_endpoint.api_key"
+ )
except RuntimeError:
# In a thread context without snapshot
logger.warning(
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index 5e7f1257d7..c41f11b3cf 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -7,7 +7,7 @@ from loguru import logger
from ...database.session_context import get_user_db_session
from ...web.auth.decorators import login_required
-from ...settings import CachedSettingsManager
+from local_deep_research.settings import SettingsManager
from ...web.utils.templates import render_template_with_defaults
from .benchmark_service import benchmark_service
@@ -23,7 +23,7 @@ def index():
username = flask_session.get("username")
with get_user_db_session(username) as db_session:
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
# Load evaluation settings from database
eval_settings = {
@@ -68,7 +68,7 @@ def start_benchmark():
# Get search config from database instead of request
from ...database.session_context import get_user_db_session
- from ...settings import CachedSettingsManager
+ from local_deep_research.settings import SettingsManager
from flask import session as flask_session
username = flask_session.get("username")
@@ -78,7 +78,7 @@ def start_benchmark():
with get_user_db_session(username) as db_session:
# Use the logged-in user's settings
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
# Build search config from database settings
search_config = {
@@ -262,6 +262,13 @@ def get_benchmark_status(benchmark_run_id: int):
)
if status:
+ logger.info(
+ f"Returning status for benchmark {benchmark_run_id}: "
+ f"completed={status.get('completed_examples')}, "
+ f"overall_acc={status.get('overall_accuracy')}, "
+ f"avg_time={status.get('avg_time_per_example')}, "
+ f"estimated_remaining={status.get('estimated_time_remaining')}"
+ )
return jsonify({"success": True, "status": status})
else:
return jsonify(
@@ -446,6 +453,9 @@ def get_benchmark_results(benchmark_run_id: int):
logger.info(f"Getting results for benchmark {benchmark_run_id}")
username = flask_session.get("username")
+
+ # First sync any pending results from active runs
+ benchmark_service.sync_pending_results(benchmark_run_id, username)
with get_user_db_session(username) as session:
# Get recent results (limit to last 10)
limit = int(request.args.get("limit", 10))
@@ -652,7 +662,7 @@ def start_benchmark_simple():
username = flask_session.get("username")
with get_user_db_session(username) as session:
# For benchmarks, use a default test username
- settings_manager = CachedSettingsManager(session, "benchmark_user")
+ settings_manager = SettingsManager(session, "benchmark_user")
# Build search config from database settings
search_config = {
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 26a2bfa1a6..8fff21d3e5 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -188,15 +188,31 @@ class BenchmarkService:
)
# Create settings snapshot for thread safety
- from ...settings import CachedSettingsManager
+ from local_deep_research.settings import SettingsManager
- settings_manager = CachedSettingsManager(session, username)
+ settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_all_settings()
+ # Get user password for metrics tracking in background thread
+ from flask import session as flask_session
+ from ...database.session_passwords import session_password_store
+
+ user_password = None
+ session_id = flask_session.get("session_id")
+ if session_id and username:
+ user_password = session_password_store.get_session_password(
+ username, session_id
+ )
+ if not user_password:
+ logger.warning(
+ f"No password found for user {username} in session {session_id}"
+ )
+
# Extract all data we need
benchmark_data = {
"benchmark_run_id": benchmark_run_id,
"username": username or "benchmark_user",
+ "user_password": user_password, # Add password for metrics tracking
"config_hash": benchmark_run.config_hash,
"datasets_config": benchmark_run.datasets_config,
"search_config": benchmark_run.search_config,
@@ -345,6 +361,10 @@ class BenchmarkService:
# Process tasks
for i, task in enumerate(task_queue):
try:
+ # Add username and password to task for metrics tracking
+ task["username"] = benchmark_data.get("username")
+ task["user_password"] = benchmark_data.get("user_password")
+
# Process single task
result = self._process_benchmark_task(
task,
@@ -568,6 +588,9 @@ class BenchmarkService:
except Exception:
logger.exception("Error sending benchmark progress update")
+ # Get user password from task data
+ user_password = task.get("user_password")
+
search_result = quick_summary(
query=formatted_query,
research_id=tracking_id, # Pass the tracking ID
@@ -585,6 +608,8 @@ class BenchmarkService:
temperature=search_config.get("temperature", 0.7),
openai_endpoint_url=search_config.get("openai_endpoint_url"),
settings_snapshot=settings_context.snapshot, # Pass settings snapshot for thread safety
+ username=task.get("username"), # Pass username
+ user_password=user_password, # Pass password for metrics tracking
)
processing_time = time.time() - start_time
@@ -711,6 +736,66 @@ class BenchmarkService:
"completed_at": datetime.now(),
}
+ def sync_pending_results(self, benchmark_run_id: int, username: str = None):
+ """Sync any pending results to database. Can be called from main thread."""
+ if benchmark_run_id not in self.active_runs:
+ return 0
+
+ run_data = self.active_runs[benchmark_run_id]
+ results_to_save = run_data.get("results", [])
+ saved_indices = run_data.get("saved_indices", set())
+
+ if not username:
+ username = run_data.get("data", {}).get("username")
+
+ saved_count = 0
+ from ...database.session_context import get_user_db_session
+ from ...database.models.benchmark import BenchmarkResult
+
+ try:
+ with get_user_db_session(username) as session:
+ # Save any results that haven't been saved yet
+ for idx, result in enumerate(results_to_save):
+ if idx not in saved_indices:
+ benchmark_result = BenchmarkResult(
+ benchmark_run_id=benchmark_run_id,
+ example_id=result["example_id"],
+ query_hash=result["query_hash"],
+ dataset_type=DatasetType(result["dataset_type"]),
+ research_id=result.get("research_id"),
+ question=result["question"],
+ correct_answer=result["correct_answer"],
+ response=result.get("response"),
+ extracted_answer=result.get("extracted_answer"),
+ confidence=result.get("confidence"),
+ processing_time=result.get("processing_time"),
+ sources=result.get("sources"),
+ is_correct=result.get("is_correct"),
+ graded_confidence=result.get("graded_confidence"),
+ grader_response=result.get("grader_response"),
+ completed_at=result.get("completed_at"),
+ research_error=result.get("research_error"),
+ evaluation_error=result.get("evaluation_error"),
+ task_index=result.get("task_index"),
+ )
+ session.add(benchmark_result)
+ saved_indices.add(idx)
+ saved_count += 1
+
+ if saved_count > 0:
+ session.commit()
+ run_data["saved_indices"] = saved_indices
+ logger.info(
+ f"Saved {saved_count} new results for benchmark {benchmark_run_id}"
+ )
+
+ except Exception:
+ logger.exception(
+ f"Error syncing pending results for benchmark {benchmark_run_id}"
+ )
+
+ return saved_count
+
def _sync_results_to_database(self, benchmark_run_id: int):
"""Sync benchmark results from memory to database after thread completes."""
if benchmark_run_id not in self.active_runs:
@@ -1041,30 +1126,47 @@ class BenchmarkService:
avg_time_per_example = None
accuracy_confidence = None
- if (
- benchmark_run.start_time
- and benchmark_run.completed_examples > 0
- ):
+ # Get ALL results for timing calculation (including those pending evaluation)
+ all_results_for_timing = (
+ session.query(BenchmarkResult)
+ .filter(
+ BenchmarkResult.benchmark_run_id == benchmark_run_id
+ )
+ .all()
+ )
+
+ if benchmark_run.start_time and all_results_for_timing:
# Calculate elapsed time
current_time = datetime.now()
total_elapsed_time = (
current_time - benchmark_run.start_time
).total_seconds()
- # Calculate average processing time per example
- avg_time_per_example = (
- total_elapsed_time / benchmark_run.completed_examples
+ # Calculate average processing time per example using actual count
+ avg_time_per_example = total_elapsed_time / len(
+ all_results_for_timing
+ )
+
+ logger.info(
+ f"Time calculation - elapsed: {total_elapsed_time:.2f}s, "
+ f"results_count: {len(all_results_for_timing)}, "
+ f"avg_per_example: {avg_time_per_example:.2f}s"
)
# Estimate remaining time
- remaining_examples = (
- benchmark_run.total_examples
- - benchmark_run.completed_examples
+ remaining_examples = benchmark_run.total_examples - len(
+ all_results_for_timing
)
if remaining_examples > 0:
estimated_time_remaining = (
avg_time_per_example * remaining_examples
)
+ logger.info(
+ f"Time estimation - total: {benchmark_run.total_examples}, "
+ f"completed: {len(all_results_for_timing)}, remaining: {remaining_examples}, "
+ f"avg_time: {avg_time_per_example:.2f}s, "
+ f"estimated_remaining: {estimated_time_remaining:.2f}s"
+ )
# Calculate accuracy confidence interval (95% confidence)
if results and len(results) >= 3:
@@ -1087,11 +1189,13 @@ class BenchmarkService:
"sample_size": n,
}
- return {
+ status_data = {
"id": benchmark_run.id,
"run_name": benchmark_run.run_name,
"status": benchmark_run.status.value,
- "completed_examples": benchmark_run.completed_examples,
+ "completed_examples": len(
+ all_results_for_timing
+ ), # Use actual count from DB
"total_examples": benchmark_run.total_examples,
"failed_examples": benchmark_run.failed_examples,
"overall_accuracy": benchmark_run.overall_accuracy
@@ -1116,6 +1220,14 @@ class BenchmarkService:
"error_message": benchmark_run.error_message,
}
+ logger.info(
+ f"Benchmark {benchmark_run_id} status - completed: {benchmark_run.completed_examples}, "
+ f"running_acc: {running_accuracy}, simpleqa_acc: {simpleqa_accuracy}, "
+ f"browsecomp_acc: {browsecomp_accuracy}, avg_time: {avg_time_per_example}"
+ )
+
+ return status_data
+
except Exception:
logger.exception("Error getting benchmark status")
return None
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 8d3f8d2fb8..d27eed667c 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -26,7 +26,9 @@ VALID_PROVIDERS = [
]
-def get_db_setting(key, default=None, username=None, settings_snapshot=None):
+def get_setting_from_snapshot(
+ 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:
@@ -59,7 +61,7 @@ def get_db_setting(key, default=None, username=None, settings_snapshot=None):
def is_openai_available(settings_snapshot=None):
"""Check if OpenAI is available"""
try:
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.openai.api_key", settings_snapshot=settings_snapshot
)
return bool(api_key)
@@ -70,7 +72,7 @@ def is_openai_available(settings_snapshot=None):
def is_anthropic_available(settings_snapshot=None):
"""Check if Anthropic is available"""
try:
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.anthropic.api_key", settings_snapshot=settings_snapshot
)
return bool(api_key)
@@ -81,7 +83,7 @@ def is_anthropic_available(settings_snapshot=None):
def is_openai_endpoint_available(settings_snapshot=None):
"""Check if OpenAI endpoint is available"""
try:
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.openai_endpoint.api_key", settings_snapshot=settings_snapshot
)
return bool(api_key)
@@ -94,7 +96,7 @@ def is_ollama_available(settings_snapshot=None):
try:
import requests
- raw_base_url = get_db_setting(
+ raw_base_url = get_setting_from_snapshot(
"llm.ollama.url",
"http://localhost:11434",
settings_snapshot=settings_snapshot,
@@ -147,7 +149,7 @@ def is_lmstudio_available(settings_snapshot=None):
try:
import requests
- lmstudio_url = get_db_setting(
+ lmstudio_url = get_setting_from_snapshot(
"llm.lmstudio.url",
"http://localhost:1234",
settings_snapshot=settings_snapshot,
@@ -164,7 +166,7 @@ def is_llamacpp_available(settings_snapshot=None):
try:
from langchain_community.llms import LlamaCpp # noqa: F401
- model_path = get_db_setting(
+ model_path = get_setting_from_snapshot(
"llm.llamacpp_model_path", settings_snapshot=settings_snapshot
)
return bool(model_path) and os.path.exists(model_path)
@@ -212,7 +214,7 @@ def get_available_providers(settings_snapshot=None):
def get_selected_llm_provider():
- return get_db_setting("llm.provider", "ollama").lower()
+ return get_setting_from_snapshot("llm.provider", "ollama").lower()
def get_llm(
@@ -242,15 +244,15 @@ def get_llm(
# Use database values for parameters if not provided
if model_name is None:
- model_name = get_db_setting(
+ model_name = get_setting_from_snapshot(
"llm.model", "gemma:latest", settings_snapshot=settings_snapshot
)
if temperature is None:
- temperature = get_db_setting(
+ temperature = get_setting_from_snapshot(
"llm.temperature", 0.7, settings_snapshot=settings_snapshot
)
if provider is None:
- provider = get_db_setting(
+ provider = get_setting_from_snapshot(
"llm.provider", "ollama", settings_snapshot=settings_snapshot
)
@@ -303,14 +305,17 @@ def get_llm(
provider_has_config = False
if (
- (provider == "openai" and get_db_setting("llm.openai.api_key"))
+ (
+ provider == "openai"
+ and get_setting_from_snapshot("llm.openai.api_key")
+ )
or (
provider == "anthropic"
- and get_db_setting("llm.anthropic.api_key")
+ and get_setting_from_snapshot("llm.anthropic.api_key")
)
or (
provider == "openai_endpoint"
- and get_db_setting("llm.openai_endpoint.api_key")
+ and get_setting_from_snapshot("llm.openai_endpoint.api_key")
)
or (provider == "ollama" and is_ollama_available())
):
@@ -355,7 +360,7 @@ def get_llm(
def get_context_window_size(provider_type):
if provider_type in ["ollama", "llamacpp", "lmstudio"]:
# Local providers: use smaller default to prevent memory issues
- window_size = get_db_setting(
+ window_size = get_setting_from_snapshot(
"llm.local_context_window_size",
4096,
settings_snapshot=settings_snapshot,
@@ -364,7 +369,7 @@ def get_llm(
return int(window_size) if window_size is not None else 4096
else:
# Cloud providers: check if unrestricted mode is enabled
- use_unrestricted = get_db_setting(
+ use_unrestricted = get_setting_from_snapshot(
"llm.context_window_unrestricted",
True,
settings_snapshot=settings_snapshot,
@@ -374,7 +379,7 @@ def get_llm(
return None # Will be handled per provider
else:
# Use user-specified limit
- window_size = get_db_setting(
+ window_size = get_setting_from_snapshot(
"llm.context_window_size",
128000,
settings_snapshot=settings_snapshot,
@@ -383,14 +388,14 @@ def get_llm(
context_window_size = get_context_window_size(provider)
- if get_db_setting(
+ if get_setting_from_snapshot(
"llm.supports_max_tokens", True, settings_snapshot=settings_snapshot
):
# Use 80% of context window to leave room for prompts
if context_window_size is not None:
max_tokens = min(
int(
- get_db_setting(
+ get_setting_from_snapshot(
"llm.max_tokens",
100000,
settings_snapshot=settings_snapshot,
@@ -402,7 +407,7 @@ def get_llm(
else:
# Unrestricted context: use provider's default max_tokens
max_tokens = int(
- get_db_setting(
+ get_setting_from_snapshot(
"llm.max_tokens",
100000,
settings_snapshot=settings_snapshot,
@@ -412,7 +417,7 @@ def get_llm(
# Handle different providers
if provider == "anthropic":
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.anthropic.api_key", settings_snapshot=settings_snapshot
)
if not api_key:
@@ -433,7 +438,7 @@ def get_llm(
)
elif provider == "openai":
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.openai.api_key", settings_snapshot=settings_snapshot
)
if not api_key:
@@ -452,7 +457,7 @@ def get_llm(
)
elif provider == "openai_endpoint":
- api_key = get_db_setting(
+ api_key = get_setting_from_snapshot(
"llm.openai_endpoint.api_key", settings_snapshot=settings_snapshot
)
if not api_key:
@@ -463,7 +468,7 @@ def get_llm(
# Get endpoint URL from settings
if openai_endpoint_url is None:
- openai_endpoint_url = get_db_setting(
+ openai_endpoint_url = get_setting_from_snapshot(
"llm.openai_endpoint.url",
"https://openrouter.ai/api/v1",
settings_snapshot=settings_snapshot,
@@ -507,7 +512,7 @@ def get_llm(
elif provider == "ollama":
try:
# Use the configurable Ollama base URL
- raw_base_url = get_db_setting(
+ raw_base_url = get_setting_from_snapshot(
"llm.ollama.url", "http://localhost:11434"
)
base_url = (
@@ -609,7 +614,7 @@ def get_llm(
elif provider == "lmstudio":
# LM Studio supports OpenAI API format, so we can use ChatOpenAI directly
- lmstudio_url = get_db_setting(
+ lmstudio_url = get_setting_from_snapshot(
"llm.lmstudio.url",
"http://localhost:1234",
settings_snapshot=settings_snapshot,
@@ -636,7 +641,7 @@ def get_llm(
from langchain_community.llms import LlamaCpp
# Get LlamaCpp connection mode from settings
- connection_mode = get_db_setting(
+ connection_mode = get_setting_from_snapshot(
"llm.llamacpp_connection_mode", "local"
)
@@ -644,19 +649,19 @@ def get_llm(
# Use HTTP client mode
from langchain_community.llms.llamacpp_client import LlamaCppClient
- server_url = get_db_setting(
+ server_url = get_setting_from_snapshot(
"llm.llamacpp_server_url", "http://localhost:8000"
)
llm = LlamaCppClient(
server_url=server_url,
temperature=temperature,
- max_tokens=get_db_setting("llm.max_tokens", 8192),
+ max_tokens=get_setting_from_snapshot("llm.max_tokens", 8192),
)
else:
# Use direct model loading (existing code)
# Get LlamaCpp model path from settings
- model_path = get_db_setting(
+ model_path = get_setting_from_snapshot(
"llm.llamacpp_model_path", settings_snapshot=settings_snapshot
)
if not model_path:
@@ -664,15 +669,15 @@ def get_llm(
raise ValueError("llamacpp_model_path not set in settings")
# Get additional LlamaCpp parameters
- n_gpu_layers = get_db_setting(
+ n_gpu_layers = get_setting_from_snapshot(
"llm.llamacpp_n_gpu_layers",
1,
settings_snapshot=settings_snapshot,
)
- n_batch = get_db_setting(
+ n_batch = get_setting_from_snapshot(
"llm.llamacpp_n_batch", 512, settings_snapshot=settings_snapshot
)
- f16_kv = get_db_setting(
+ f16_kv = get_setting_from_snapshot(
"llm.llamacpp_f16_kv", True, settings_snapshot=settings_snapshot
)
@@ -731,7 +736,7 @@ def wrap_llm_without_think_tags(
# Check if LLM rate limiting is enabled (independent of search rate limiting)
# Use the thread-safe get_db_setting defined in this module
- if get_db_setting(
+ if get_setting_from_snapshot(
"rate_limiting.llm_enabled", False, settings_snapshot=settings_snapshot
):
llm = create_rate_limited_llm_wrapper(llm, provider)
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index eb4512f9e7..cd71b44bc0 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -11,7 +11,9 @@ from .thread_settings import _thread_local
QUALITY_CHECK_DDG_URLS = True
-def get_db_setting(key, default=None, username=None, settings_snapshot=None):
+def get_setting_from_snapshot(
+ 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:
@@ -38,7 +40,9 @@ def get_search_snippets_only_setting(username=None):
"""
Lazily retrieve the 'search.snippets_only' setting.
"""
- return get_db_setting("search.snippets_only", True, username=username)
+ return get_setting_from_snapshot(
+ "search.snippets_only", True, username=username
+ )
# Expose get_search function
@@ -56,7 +60,7 @@ def get_search(
"""
# Use specified tool or default from settings
- tool = search_tool or get_db_setting(
+ tool = search_tool or get_setting_from_snapshot(
"search.tool",
"searxng",
username=username,
@@ -71,43 +75,43 @@ def get_search(
params = {
"search_tool": tool,
"llm_instance": llm,
- "max_results": get_db_setting(
+ "max_results": get_setting_from_snapshot(
"search.max_results",
10,
username=username,
settings_snapshot=settings_snapshot,
),
- "region": get_db_setting(
+ "region": get_setting_from_snapshot(
"search.region",
"wt-wt",
username=username,
settings_snapshot=settings_snapshot,
),
- "time_period": get_db_setting(
+ "time_period": get_setting_from_snapshot(
"search.time_period",
"all",
username=username,
settings_snapshot=settings_snapshot,
),
- "safe_search": get_db_setting(
+ "safe_search": get_setting_from_snapshot(
"search.safe_search",
True,
username=username,
settings_snapshot=settings_snapshot,
),
- "search_snippets_only": get_db_setting(
+ "search_snippets_only": get_setting_from_snapshot(
"search.snippets_only",
True,
username=username,
settings_snapshot=settings_snapshot,
),
- "search_language": get_db_setting(
+ "search_language": get_setting_from_snapshot(
"search.search_language",
"English",
username=username,
settings_snapshot=settings_snapshot,
),
- "max_filtered_results": get_db_setting(
+ "max_filtered_results": get_setting_from_snapshot(
"search.max_filtered_results",
5,
username=username,
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 9bc008b8d8..d031949249 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -34,6 +34,18 @@ class DatabaseManager:
# Check SQLCipher availability
self.has_encryption = self._check_encryption_available()
+ 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:
@@ -148,6 +160,16 @@ class DatabaseManager:
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():
@@ -273,6 +295,22 @@ class DatabaseManager:
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]
@@ -468,12 +506,12 @@ class DatabaseManager:
session = SessionLocal()
# Load comprehensive default settings from the defaults file
- from ..settings import CachedSettingsManager
+ from local_deep_research.settings import SettingsManager
logger.info(
f"Loading full default settings for new user {username}"
)
- settings_manager = CachedSettingsManager(session, username)
+ settings_manager = SettingsManager(session)
settings_manager.load_from_defaults_file(commit=True)
# Explicitly commit to ensure settings are saved
diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.py
index e559bae176..d7f0591d34 100644
--- a/src/local_deep_research/error_handling/report_generator.py
+++ b/src/local_deep_research/error_handling/report_generator.py
@@ -29,7 +29,7 @@ class ErrorReportGenerator:
query: str,
partial_results: Optional[Dict[str, Any]] = None,
search_iterations: int = 0,
- research_id: Optional[int] = None,
+ research_id: Optional[str] = None,
) -> str:
"""
Generate a comprehensive error report
diff --git a/src/local_deep_research/memory_cache/cached_services.py b/src/local_deep_research/memory_cache/cached_services.py
index d174ce5257..95343d3804 100644
--- a/src/local_deep_research/memory_cache/cached_services.py
+++ b/src/local_deep_research/memory_cache/cached_services.py
@@ -13,7 +13,7 @@ from .config import get_thread_local_cache
from ..database.models import UserSettings
-class CachedSettingsManager:
+class SettingsManager:
"""Settings manager with dogpile cache integration."""
def __init__(self, session: Session, user_id: str):
diff --git a/src/local_deep_research/memory_cache/config.py b/src/local_deep_research/memory_cache/config.py
index 5509d42f3d..0782f09167 100644
--- a/src/local_deep_research/memory_cache/config.py
+++ b/src/local_deep_research/memory_cache/config.py
@@ -27,9 +27,29 @@ thread_local = threading.local()
DEFAULT_HOT_CACHE_SIZE = 1000 # In-memory entries
DEFAULT_HOT_CACHE_TTL = 300 # 5 minutes
DEFAULT_WARM_CACHE_TTL = 3600 # 1 hour
-CACHE_KEY_SECRET = os.environ.get(
- "CACHE_KEY_SECRET", "default-secret-change-in-production"
-)
+CACHE_KEY_SECRET = os.environ.get("CACHE_KEY_SECRET", None)
+if not CACHE_KEY_SECRET:
+ # Generate a cache key secret similar to Flask SECRET_KEY
+ import secrets
+
+ cache_secret_file = os.path.join(PROJECT_STATIC_DIR, ".cache_key_secret")
+ if os.path.exists(cache_secret_file):
+ try:
+ with open(cache_secret_file, "r") as f:
+ CACHE_KEY_SECRET = f.read().strip()
+ except Exception:
+ CACHE_KEY_SECRET = secrets.token_hex(32)
+ else:
+ # Generate a new cache key on first run
+ CACHE_KEY_SECRET = secrets.token_hex(32)
+ try:
+ os.makedirs(os.path.dirname(cache_secret_file), exist_ok=True)
+ with open(cache_secret_file, "w") as f:
+ f.write(CACHE_KEY_SECRET)
+ os.chmod(cache_secret_file, 0o600) # Secure file permissions
+ logger.info("Generated new CACHE_KEY_SECRET for this installation")
+ except Exception:
+ pass # Use the generated key even if we can't save it
def secure_cache_key(user_id: str, key_parts: list) -> str:
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index 58efb1df34..4d38b1ec31 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -4,6 +4,7 @@ import inspect
import json
import os
import time
+from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional
from langchain_core.callbacks import BaseCallbackHandler
@@ -20,7 +21,7 @@ class TokenCountingCallback(BaseCallbackHandler):
def __init__(
self,
- research_id: Optional[int] = None,
+ research_id: Optional[str] = None,
research_context: Optional[Dict[str, Any]] = None,
):
"""Initialize the token counting callback.
@@ -513,7 +514,7 @@ class TokenCounter:
def create_callback(
self,
- research_id: Optional[int] = None,
+ research_id: Optional[str] = None,
research_context: Optional[Dict[str, Any]] = None,
) -> TokenCountingCallback:
"""Create a new token counting callback.
@@ -529,7 +530,7 @@ class TokenCounter:
research_id=research_id, research_context=research_context
)
- def get_research_metrics(self, research_id: int) -> Dict[str, Any]:
+ def get_research_metrics(self, research_id: str) -> Dict[str, Any]:
"""Get token metrics for a specific research.
Args:
@@ -552,11 +553,23 @@ class TokenCounter:
}
with get_user_db_session(username) as session:
- # Get model usage for this research
- model_usages = (
- session.query(ModelUsage)
+ # Get token usage for this research from TokenUsage table
+ from sqlalchemy import func
+
+ token_usages = (
+ session.query(
+ TokenUsage.model_name,
+ TokenUsage.model_provider,
+ func.sum(TokenUsage.prompt_tokens).label("prompt_tokens"),
+ func.sum(TokenUsage.completion_tokens).label(
+ "completion_tokens"
+ ),
+ func.sum(TokenUsage.total_tokens).label("total_tokens"),
+ func.count().label("calls"),
+ )
.filter_by(research_id=research_id)
- .order_by(ModelUsage.total_tokens.desc())
+ .group_by(TokenUsage.model_name, TokenUsage.model_provider)
+ .order_by(func.sum(TokenUsage.total_tokens).desc())
.all()
)
@@ -564,19 +577,19 @@ class TokenCounter:
total_tokens = 0
total_calls = 0
- for usage in model_usages:
+ for usage in token_usages:
model_usage.append(
{
"model": usage.model_name,
- "provider": usage.provider,
- "tokens": usage.total_tokens,
- "calls": usage.calls,
- "prompt_tokens": usage.prompt_tokens,
- "completion_tokens": usage.completion_tokens,
+ "provider": usage.model_provider,
+ "tokens": usage.total_tokens or 0,
+ "calls": usage.calls or 0,
+ "prompt_tokens": usage.prompt_tokens or 0,
+ "completion_tokens": usage.completion_tokens or 0,
}
)
- total_tokens += usage.total_tokens
- total_calls += usage.calls
+ total_tokens += usage.total_tokens or 0
+ total_calls += usage.calls or 0
return {
"research_id": research_id,
@@ -625,169 +638,469 @@ class TokenCounter:
# Build base query with filters
query = session.query(TokenUsage)
- # Apply time filter
- time_condition = get_time_filter_condition(
- period, TokenUsage.timestamp
- )
- if time_condition is not None:
- query = query.filter(time_condition)
-
- # Apply research mode filter
- mode_condition = get_research_mode_condition(
- research_mode, TokenUsage.research_mode
- )
- if mode_condition is not None:
- query = query.filter(mode_condition)
+ # Apply time filter
+ time_condition = get_time_filter_condition(
+ period, TokenUsage.timestamp
+ )
+ if time_condition is not None:
+ query = query.filter(time_condition)
- # Total tokens and researches
- total_tokens = (
- query.with_entities(func.sum(TokenUsage.total_tokens)).scalar()
- or 0
- )
- total_researches = (
- query.with_entities(
- func.count(func.distinct(TokenUsage.research_id))
- ).scalar()
- or 0
- )
+ # Apply research mode filter
+ mode_condition = get_research_mode_condition(
+ research_mode, TokenUsage.research_mode
+ )
+ if mode_condition is not None:
+ query = query.filter(mode_condition)
- # Model statistics using ORM aggregation
- model_stats_query = session.query(
- TokenUsage.model_name,
- func.sum(TokenUsage.total_tokens).label("tokens"),
- func.count().label("calls"),
- func.sum(TokenUsage.prompt_tokens).label("prompt_tokens"),
- func.sum(TokenUsage.completion_tokens).label(
- "completion_tokens"
- ),
- ).filter(TokenUsage.model_name.isnot(None))
+ # Total tokens from TokenUsage
+ total_tokens = (
+ query.with_entities(
+ func.sum(TokenUsage.total_tokens)
+ ).scalar()
+ or 0
+ )
- # Apply same filters to model stats
- if time_condition is not None:
- model_stats_query = model_stats_query.filter(time_condition)
- if mode_condition is not None:
- model_stats_query = model_stats_query.filter(mode_condition)
+ # Import ResearchHistory model
+ from ..database.models.research import ResearchHistory
- model_stats = (
- model_stats_query.group_by(TokenUsage.model_name)
- .order_by(func.sum(TokenUsage.total_tokens).desc())
- .all()
- )
+ # Count researches from ResearchHistory table
+ research_query = session.query(func.count(ResearchHistory.id))
- # Get provider info from ModelUsage table
- by_model = []
- for stat in model_stats:
- # Try to get provider from ModelUsage table
- provider_info = (
- session.query(ModelUsage.provider)
- .filter(ModelUsage.model_name == stat.model_name)
- .first()
+ # Debug: Check if any research history records exist at all
+ all_research_count = (
+ session.query(func.count(ResearchHistory.id)).scalar() or 0
)
- provider = (
- provider_info.provider if provider_info else "unknown"
+ logger.warning(
+ f"DEBUG: Total ResearchHistory records in database: {all_research_count}"
)
- by_model.append(
- {
- "model": stat.model_name,
- "provider": provider,
- "tokens": stat.tokens,
- "calls": stat.calls,
- "prompt_tokens": stat.prompt_tokens,
- "completion_tokens": stat.completion_tokens,
- }
+ # Debug: List first few research IDs and their timestamps
+ sample_researches = (
+ session.query(
+ ResearchHistory.id,
+ ResearchHistory.created_at,
+ ResearchHistory.mode,
+ )
+ .limit(5)
+ .all()
)
+ if sample_researches:
+ logger.warning("DEBUG: Sample ResearchHistory records:")
+ for r_id, r_created, r_mode in sample_researches:
+ logger.warning(
+ f" - ID: {r_id}, Created: {r_created}, Mode: {r_mode}"
+ )
+ else:
+ logger.warning(
+ "DEBUG: No ResearchHistory records found in database!"
+ )
+
+ # Get time filter conditions for ResearchHistory query
+ start_time, end_time = None, None
+ if period != "all":
+ if period == "today":
+ start_time = datetime.now().replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ elif period == "week":
+ start_time = datetime.now() - timedelta(days=7)
+ elif period == "month":
+ start_time = datetime.now() - timedelta(days=30)
+
+ if start_time:
+ end_time = datetime.now()
+
+ # Apply time filter if specified
+ if start_time and end_time:
+ research_query = research_query.filter(
+ ResearchHistory.created_at >= start_time.isoformat(),
+ ResearchHistory.created_at <= end_time.isoformat(),
+ )
- # Get recent researches with token usage
- # Note: This requires research_history table - for now we'll use available data
- recent_research_query = session.query(
- TokenUsage.research_id,
- func.sum(TokenUsage.total_tokens).label("token_count"),
- func.max(TokenUsage.timestamp).label("latest_timestamp"),
- ).filter(TokenUsage.research_id.isnot(None))
-
- if time_condition is not None:
- recent_research_query = recent_research_query.filter(
- time_condition
+ # Apply mode filter if specified
+ mode_filter = research_mode if research_mode != "all" else None
+ if mode_filter:
+ logger.warning(
+ f"DEBUG: Applying mode filter: {mode_filter}"
+ )
+ research_query = research_query.filter(
+ ResearchHistory.mode == mode_filter
+ )
+
+ total_researches = research_query.scalar() or 0
+ logger.warning(
+ f"DEBUG: Final filtered research count: {total_researches}"
)
- if mode_condition is not None:
- recent_research_query = recent_research_query.filter(
- mode_condition
+
+ # Also check distinct research_ids in TokenUsage for comparison
+ token_research_count = (
+ session.query(
+ func.count(func.distinct(TokenUsage.research_id))
+ ).scalar()
+ or 0
+ )
+ logger.warning(
+ f"DEBUG: Distinct research_ids in TokenUsage: {token_research_count}"
)
- recent_research_data = (
- recent_research_query.group_by(TokenUsage.research_id)
- .order_by(func.max(TokenUsage.timestamp).desc())
- .limit(10)
- .all()
- )
+ # Model statistics using ORM aggregation
+ model_stats_query = session.query(
+ TokenUsage.model_name,
+ func.sum(TokenUsage.total_tokens).label("tokens"),
+ func.count().label("calls"),
+ func.sum(TokenUsage.prompt_tokens).label("prompt_tokens"),
+ func.sum(TokenUsage.completion_tokens).label(
+ "completion_tokens"
+ ),
+ ).filter(TokenUsage.model_name.isnot(None))
- recent_researches = []
- for research_data in recent_research_data:
- # Get research query from token_usage table if available
- research_query_data = (
- session.query(TokenUsage.research_query)
- .filter(
- TokenUsage.research_id == research_data.research_id,
- TokenUsage.research_query.isnot(None),
- )
- .first()
- )
+ # Apply same filters to model stats
+ if time_condition is not None:
+ model_stats_query = model_stats_query.filter(time_condition)
+ if mode_condition is not None:
+ model_stats_query = model_stats_query.filter(mode_condition)
- query_text = (
- research_query_data.research_query
- if research_query_data
- else f"Research {research_data.research_id}"
+ model_stats = (
+ model_stats_query.group_by(TokenUsage.model_name)
+ .order_by(func.sum(TokenUsage.total_tokens).desc())
+ .all()
)
- recent_researches.append(
- {
- "id": research_data.research_id,
- "query": query_text,
- "tokens": research_data.token_count or 0,
- "created_at": research_data.latest_timestamp,
- }
+ # Get provider info from ModelUsage table
+ by_model = []
+ for stat in model_stats:
+ # Try to get provider from ModelUsage table
+ provider_info = (
+ session.query(ModelUsage.model_provider)
+ .filter(ModelUsage.model_name == stat.model_name)
+ .first()
+ )
+ provider = (
+ provider_info.model_provider
+ if provider_info
+ else "unknown"
+ )
+
+ by_model.append(
+ {
+ "model": stat.model_name,
+ "provider": provider,
+ "tokens": stat.tokens,
+ "calls": stat.calls,
+ "prompt_tokens": stat.prompt_tokens,
+ "completion_tokens": stat.completion_tokens,
+ }
+ )
+
+ # Get recent researches with token usage
+ # Note: This requires research_history table - for now we'll use available data
+ recent_research_query = session.query(
+ TokenUsage.research_id,
+ func.sum(TokenUsage.total_tokens).label("token_count"),
+ func.max(TokenUsage.timestamp).label("latest_timestamp"),
+ ).filter(TokenUsage.research_id.isnot(None))
+
+ if time_condition is not None:
+ recent_research_query = recent_research_query.filter(
+ time_condition
+ )
+ if mode_condition is not None:
+ recent_research_query = recent_research_query.filter(
+ mode_condition
+ )
+
+ recent_research_data = (
+ recent_research_query.group_by(TokenUsage.research_id)
+ .order_by(func.max(TokenUsage.timestamp).desc())
+ .limit(10)
+ .all()
)
- # Token breakdown statistics
- breakdown_query = query.with_entities(
- func.sum(TokenUsage.prompt_tokens).label("total_input_tokens"),
- func.sum(TokenUsage.completion_tokens).label(
- "total_output_tokens"
- ),
- func.avg(TokenUsage.prompt_tokens).label("avg_input_tokens"),
- func.avg(TokenUsage.completion_tokens).label(
- "avg_output_tokens"
- ),
- func.avg(TokenUsage.total_tokens).label("avg_total_tokens"),
- )
- token_breakdown = breakdown_query.first()
+ recent_researches = []
+ for research_data in recent_research_data:
+ # Get research query from token_usage table if available
+ research_query_data = (
+ session.query(TokenUsage.research_query)
+ .filter(
+ TokenUsage.research_id == research_data.research_id,
+ TokenUsage.research_query.isnot(None),
+ )
+ .first()
+ )
- return {
- "total_tokens": total_tokens,
- "total_researches": total_researches,
- "by_model": by_model,
- "recent_researches": recent_researches,
- "token_breakdown": {
- "total_input_tokens": int(
- token_breakdown.total_input_tokens or 0
- ),
- "total_output_tokens": int(
- token_breakdown.total_output_tokens or 0
+ query_text = (
+ research_query_data.research_query
+ if research_query_data
+ else f"Research {research_data.research_id}"
+ )
+
+ recent_researches.append(
+ {
+ "id": research_data.research_id,
+ "query": query_text,
+ "tokens": research_data.token_count or 0,
+ "created_at": research_data.latest_timestamp,
+ }
+ )
+
+ # Token breakdown statistics
+ breakdown_query = query.with_entities(
+ func.sum(TokenUsage.prompt_tokens).label(
+ "total_input_tokens"
),
- "avg_input_tokens": int(
- token_breakdown.avg_input_tokens or 0
+ func.sum(TokenUsage.completion_tokens).label(
+ "total_output_tokens"
),
- "avg_output_tokens": int(
- token_breakdown.avg_output_tokens or 0
+ func.avg(TokenUsage.prompt_tokens).label(
+ "avg_input_tokens"
),
- "avg_total_tokens": int(
- token_breakdown.avg_total_tokens or 0
+ func.avg(TokenUsage.completion_tokens).label(
+ "avg_output_tokens"
),
- },
- }
+ func.avg(TokenUsage.total_tokens).label("avg_total_tokens"),
+ )
+ token_breakdown = breakdown_query.first()
+
+ # Get rate limiting metrics
+ from ..database.models import (
+ RateLimitAttempt,
+ RateLimitEstimate,
+ )
+
+ # Get rate limit attempts
+ rate_limit_query = session.query(RateLimitAttempt)
+
+ # Apply time filter
+ if time_condition is not None:
+ # RateLimitAttempt uses timestamp as float, not datetime
+ if period == "7d":
+ cutoff_time = time.time() - (7 * 24 * 3600)
+ elif period == "30d":
+ cutoff_time = time.time() - (30 * 24 * 3600)
+ elif period == "3m":
+ cutoff_time = time.time() - (90 * 24 * 3600)
+ elif period == "1y":
+ cutoff_time = time.time() - (365 * 24 * 3600)
+ else: # all
+ cutoff_time = 0
+
+ if cutoff_time > 0:
+ rate_limit_query = rate_limit_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
+ )
+
+ # Get rate limit statistics
+ total_attempts = rate_limit_query.count()
+ successful_attempts = rate_limit_query.filter(
+ RateLimitAttempt.success
+ ).count()
+ failed_attempts = total_attempts - successful_attempts
+
+ # Count rate limiting events (failures with RateLimitError)
+ rate_limit_events = rate_limit_query.filter(
+ ~RateLimitAttempt.success,
+ RateLimitAttempt.error_type == "RateLimitError",
+ ).count()
+
+ logger.warning(
+ f"DEBUG: Rate limit attempts in database: total={total_attempts}, successful={successful_attempts}"
+ )
+
+ # Get all attempts for detailed calculations
+ attempts = rate_limit_query.all()
+
+ # Calculate average wait times
+ if attempts:
+ avg_wait_time = sum(a.wait_time for a in attempts) / len(
+ attempts
+ )
+ successful_wait_times = [
+ a.wait_time for a in attempts if a.success
+ ]
+ avg_successful_wait = (
+ sum(successful_wait_times) / len(successful_wait_times)
+ if successful_wait_times
+ else 0
+ )
+ else:
+ avg_wait_time = 0
+ avg_successful_wait = 0
+
+ # Get tracked engines - count distinct engine types from attempts
+ tracked_engines_query = session.query(
+ func.count(func.distinct(RateLimitAttempt.engine_type))
+ )
+ if cutoff_time > 0:
+ tracked_engines_query = tracked_engines_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
+ )
+ tracked_engines = tracked_engines_query.scalar() or 0
+
+ # Get engine-specific stats from attempts
+ engine_stats = []
+
+ # Get distinct engine types from attempts
+ engine_types_query = session.query(
+ RateLimitAttempt.engine_type
+ ).distinct()
+ if cutoff_time > 0:
+ engine_types_query = engine_types_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
+ )
+ engine_types = [
+ row.engine_type for row in engine_types_query.all()
+ ]
+
+ for engine_type in engine_types:
+ engine_attempts_list = [
+ a for a in attempts if a.engine_type == engine_type
+ ]
+ engine_attempts = len(engine_attempts_list)
+ engine_success = len(
+ [a for a in engine_attempts_list if a.success]
+ )
+
+ # Get estimate if exists
+ estimate = (
+ session.query(RateLimitEstimate)
+ .filter(RateLimitEstimate.engine_type == engine_type)
+ .first()
+ )
+
+ # Calculate recent success rate
+ recent_success_rate = (
+ (engine_success / engine_attempts * 100)
+ if engine_attempts > 0
+ else 0
+ )
+
+ # Determine status based on success rate
+ if estimate:
+ status = (
+ "healthy"
+ if estimate.success_rate > 0.8
+ else "degraded"
+ if estimate.success_rate > 0.5
+ else "poor"
+ )
+ else:
+ status = (
+ "healthy"
+ if recent_success_rate > 80
+ else "degraded"
+ if recent_success_rate > 50
+ else "poor"
+ )
+
+ engine_stat = {
+ "engine": engine_type,
+ "base_wait": estimate.base_wait_seconds
+ if estimate
+ else 0.0,
+ "base_wait_seconds": round(
+ estimate.base_wait_seconds if estimate else 0.0, 2
+ ),
+ "min_wait_seconds": round(
+ estimate.min_wait_seconds if estimate else 0.0, 2
+ ),
+ "max_wait_seconds": round(
+ estimate.max_wait_seconds if estimate else 0.0, 2
+ ),
+ "success_rate": round(estimate.success_rate * 100, 1)
+ if estimate
+ else recent_success_rate,
+ "total_attempts": estimate.total_attempts
+ if estimate
+ else engine_attempts,
+ "recent_attempts": engine_attempts,
+ "recent_success_rate": round(recent_success_rate, 1),
+ "attempts": engine_attempts,
+ "status": status,
+ }
+
+ if estimate:
+ engine_stat["last_updated"] = datetime.fromtimestamp(
+ estimate.last_updated
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ else:
+ engine_stat["last_updated"] = "Never"
+
+ engine_stats.append(engine_stat)
+
+ logger.warning(
+ f"DEBUG: Tracked engines: {tracked_engines}, engine_stats: {engine_stats}"
+ )
+
+ result = {
+ "total_tokens": total_tokens,
+ "total_researches": total_researches,
+ "by_model": by_model,
+ "recent_researches": recent_researches,
+ "token_breakdown": {
+ "total_input_tokens": int(
+ token_breakdown.total_input_tokens or 0
+ ),
+ "total_output_tokens": int(
+ token_breakdown.total_output_tokens or 0
+ ),
+ "avg_input_tokens": int(
+ token_breakdown.avg_input_tokens or 0
+ ),
+ "avg_output_tokens": int(
+ token_breakdown.avg_output_tokens or 0
+ ),
+ "avg_total_tokens": int(
+ token_breakdown.avg_total_tokens or 0
+ ),
+ },
+ "rate_limiting": {
+ "total_attempts": total_attempts,
+ "successful_attempts": successful_attempts,
+ "failed_attempts": failed_attempts,
+ "success_rate": (
+ successful_attempts / total_attempts * 100
+ )
+ if total_attempts > 0
+ else 0,
+ "rate_limit_events": rate_limit_events,
+ "avg_wait_time": round(float(avg_wait_time), 2),
+ "avg_successful_wait": round(
+ float(avg_successful_wait), 2
+ ),
+ "tracked_engines": tracked_engines,
+ "engine_stats": engine_stats,
+ "total_engines_tracked": tracked_engines,
+ "healthy_engines": len(
+ [
+ s
+ for s in engine_stats
+ if s["status"] == "healthy"
+ ]
+ ),
+ "degraded_engines": len(
+ [
+ s
+ for s in engine_stats
+ if s["status"] == "degraded"
+ ]
+ ),
+ "poor_engines": len(
+ [s for s in engine_stats if s["status"] == "poor"]
+ ),
+ },
+ }
+
+ logger.warning(
+ f"DEBUG: Returning from _get_metrics_from_encrypted_db - total_researches: {result['total_researches']}"
+ )
+ return result
except Exception as e:
- logger.debug(f"Error accessing encrypted database for metrics: {e}")
+ logger.error(
+ f"CRITICAL ERROR accessing encrypted database for metrics: {e}"
+ )
+ import traceback
+
+ logger.error(f"Traceback: {traceback.format_exc()}")
return self._get_empty_metrics()
def _get_metrics_from_thread_db(
@@ -928,6 +1241,9 @@ class TokenCounter:
encrypted.get("total_researches", 0),
thread.get("total_researches", 0),
)
+ logger.warning(
+ f"DEBUG: Merged metrics - encrypted researches: {encrypted.get('total_researches', 0)}, thread researches: {thread.get('total_researches', 0)}, final: {total_researches}"
+ )
# Merge model usage
model_map = {}
@@ -979,7 +1295,7 @@ class TokenCounter:
),
}
- return {
+ result = {
"total_tokens": total_tokens,
"total_researches": total_researches,
"by_model": by_model,
@@ -987,6 +1303,11 @@ class TokenCounter:
"token_breakdown": token_breakdown,
}
+ logger.warning(
+ f"DEBUG: Final get_token_metrics result - total_researches: {result['total_researches']}"
+ )
+ return result
+
def _get_empty_metrics(self) -> Dict[str, Any]:
"""Return empty metrics structure when no data is available."""
return {
@@ -1345,7 +1666,7 @@ class TokenCounter:
},
}
- def get_research_timeline_metrics(self, research_id: int) -> Dict[str, Any]:
+ def get_research_timeline_metrics(self, research_id: str) -> Dict[str, Any]:
"""Get timeline metrics for a specific research.
Args:
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index bc6fbe7620..ef5b07354e 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -525,6 +525,7 @@ class AdvancedSearchSystem:
max_iterations=self.max_iterations, # Use database setting
questions_per_iteration=self.questions_per_iteration, # Use database setting
use_browsecomp_optimization=True, # Enable BrowseComp optimizations for 95% accuracy
+ settings_snapshot=self.settings_snapshot,
)
elif strategy_name.lower() in [
"browsecomp-entity",
@@ -551,6 +552,7 @@ class AdvancedSearchSystem:
model=self.model,
search=self.search,
all_links_of_system=self.all_links_of_system,
+ settings_snapshot=self.settings_snapshot,
)
# Log the actual strategy class
diff --git a/src/local_deep_research/settings/__init__.py b/src/local_deep_research/settings/__init__.py
index 8ce0551d0d..80427c32aa 100644
--- a/src/local_deep_research/settings/__init__.py
+++ b/src/local_deep_research/settings/__init__.py
@@ -1,12 +1,11 @@
"""
-Unified settings management system with optional caching.
+Unified settings management system.
This module provides a consistent interface for managing application settings
-with support for caching, proper metadata handling, and database persistence.
+with proper metadata handling and database persistence.
"""
from .base import ISettingsManager
from .manager import SettingsManager
-from .cached_manager import CachedSettingsManager
-__all__ = ["ISettingsManager", "SettingsManager", "CachedSettingsManager"]
+__all__ = ["ISettingsManager", "SettingsManager"]
diff --git a/src/local_deep_research/settings/cached_manager.py b/src/local_deep_research/settings/cached_manager.py
deleted file mode 100644
index 05fca7692f..0000000000
--- a/src/local_deep_research/settings/cached_manager.py
+++ /dev/null
@@ -1,358 +0,0 @@
-"""
-Cached implementation of SettingsManager.
-
-This module extends the original SettingsManager with caching capabilities
-using decorators, maintaining full compatibility with the original implementation.
-"""
-
-from typing import Any, Dict, List, Optional, Union
-from sqlalchemy.orm import Session
-from loguru import logger
-
-from .manager import SettingsManager
-from .settings_cache.decorators import cached, invalidate_cache
-from .settings_cache.strategies import HierarchicalInvalidationStrategy
-from ..database.models import Setting
-from ..web.models.settings import BaseSetting
-
-
-class CachedSettingsManager(SettingsManager):
- """
- Settings manager with caching capabilities.
-
- This class extends the original SettingsManager and adds caching
- through decorators, maintaining full compatibility while improving
- performance.
- """
-
- def __init__(
- self, db_session: Optional[Session] = None, user_id: str = None
- ):
- """
- Initialize the cached settings manager.
-
- Args:
- db_session: SQLAlchemy session for database operations
- user_id: User identifier for cache isolation
- """
- super().__init__(db_session)
- self.user_id = user_id or "global"
- self._cache_strategy = HierarchicalInvalidationStrategy()
-
- @cached(namespace="settings", ttl=300) # 5 minute TTL
- def get_setting(
- self, key: str, default: Any = None, check_env: bool = True
- ) -> Any:
- """
- Get a setting value with caching.
-
- This method is cached to improve performance for frequently accessed settings.
- """
- return super().get_setting(key, default, check_env)
-
- @invalidate_cache(namespace="settings")
- def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:
- """
- Set a setting value and invalidate cache.
-
- This method invalidates the cache after successfully setting a value.
- """
- result = super().set_setting(key, value, commit)
-
- # Additional invalidation for hierarchical keys
- if result and self._cache_strategy:
- self._cache_strategy.invalidate(self.user_id, "settings", [key])
-
- return result
-
- @cached(namespace="settings", ttl=300)
- def get_all_settings(self) -> Dict[str, Any]:
- """
- Get all settings with caching.
-
- This expensive operation is cached to improve performance.
- """
- return super().get_all_settings()
-
- @invalidate_cache(namespace="settings")
- def create_or_update_setting(
- self, setting: Union[BaseSetting, Dict[str, Any]], commit: bool = True
- ) -> Optional[Setting]:
- """
- Create or update a setting and invalidate cache.
- """
- result = super().create_or_update_setting(setting, commit)
-
- # Additional invalidation for the specific key
- if result and self._cache_strategy:
- key = (
- setting.get("key") if isinstance(setting, dict) else setting.key
- )
- self._cache_strategy.invalidate(self.user_id, "settings", [key])
-
- return result
-
- @invalidate_cache(namespace="settings")
- def delete_setting(self, key: str, commit: bool = True) -> bool:
- """
- Delete a setting and invalidate cache.
- """
- result = super().delete_setting(key, commit)
-
- # Additional invalidation
- if result and self._cache_strategy:
- self._cache_strategy.invalidate(self.user_id, "settings", [key])
-
- return result
-
- @invalidate_cache(namespace="settings")
- def import_settings(
- self,
- settings_data: Dict[str, Any],
- commit: bool = True,
- overwrite: bool = True,
- delete_extra: bool = False,
- ) -> None:
- """
- Import settings and invalidate entire cache.
-
- Since this operation can affect many settings, we invalidate
- the entire cache namespace.
- """
- super().import_settings(settings_data, commit, overwrite, delete_extra)
-
- # Full cache invalidation after bulk import
- if self._cache_strategy:
- # Use full invalidation for bulk operations
- from .settings_cache.strategies import FullInvalidationStrategy
-
- strategy = FullInvalidationStrategy()
- strategy.invalidate(self.user_id, "settings", [])
-
- def manual_invalidate_cache(self, keys: Optional[List[str]] = None) -> None:
- """
- Manually invalidate cache for specific keys or entire namespace.
-
- Args:
- keys: Optional list of keys to invalidate. If None, invalidates all.
- """
- if keys:
- self._cache_strategy.invalidate(self.user_id, "settings", keys)
- else:
- # Full invalidation
- from .settings_cache.strategies import FullInvalidationStrategy
-
- strategy = FullInvalidationStrategy()
- strategy.invalidate(self.user_id, "settings", [])
-
- logger.info(
- f"Cache invalidated for user {self.user_id}, keys: {keys or 'all'}"
- )
-
- def warmup_cache(self, keys: Optional[List[str]] = None) -> None:
- """
- Pre-populate cache with frequently used settings.
-
- Args:
- keys: Optional list of keys to warm up. If None, warms up common keys.
- """
- if not keys:
- # Default keys to warm up
- keys = [
- "llm.provider",
- "llm.model",
- "llm.temperature",
- "llm.max_tokens",
- "search.tool",
- "search.iterations",
- "search.questions_per_iteration",
- "app.version",
- "app.lock_settings",
- ]
-
- logger.info(f"Warming up cache for {len(keys)} settings")
-
- for key in keys:
- try:
- # Just calling get_setting will cache it
- self.get_setting(key)
- except Exception as e:
- logger.warning(f"Failed to warm up cache for {key}: {e}")
-
- def get_cache_stats(self) -> Dict[str, Any]:
- """
- Get cache statistics for monitoring.
-
- Returns:
- Dictionary with cache statistics
- """
- # This would integrate with dogpile's cache stats if available
- return {
- "user_id": self.user_id,
- "namespace": "settings",
- "strategy": self._cache_strategy.__class__.__name__,
- }
-
- # Performance optimization: Batch get multiple settings
- @cached(namespace="settings", ttl=300)
- def get_settings_batch(
- self, keys: List[str], defaults: Optional[Dict[str, Any]] = None
- ) -> Dict[str, Any]:
- """
- Get multiple settings in a single operation.
-
- This is more efficient than multiple individual get_setting calls
- as it results in a single database query.
-
- Args:
- keys: List of setting keys to retrieve
- defaults: Optional dictionary of default values per key
-
- Returns:
- Dictionary mapping keys to their values
- """
- if not self.db_session:
- # No database, use defaults
- result = {}
- for key in keys:
- default = defaults.get(key) if defaults else None
- result[key] = self.get_setting(key, default)
- return result
-
- try:
- # Single query for all settings
- settings = (
- self.db_session.query(Setting)
- .filter(Setting.key.in_(keys))
- .all()
- )
-
- # Build result dictionary
- result = {}
- found_keys = set()
-
- for setting in settings:
- result[setting.key] = (
- self._SettingsManager__get_typed_setting_value(
- setting, None, check_env=True
- )
- )
- found_keys.add(setting.key)
-
- # Add defaults for missing keys
- for key in keys:
- if key not in found_keys:
- default = defaults.get(key) if defaults else None
- result[key] = default
-
- return result
-
- except Exception as e:
- logger.error(f"Error batch getting settings: {e}")
- # Fallback to individual gets
- result = {}
- for key in keys:
- default = defaults.get(key) if defaults else None
- result[key] = self.get_setting(key, default)
- return result
-
- # Performance optimization: Preload settings by prefix
- @cached(namespace="settings", ttl=300)
- def preload_settings_by_prefix(self, prefix: str) -> Dict[str, Any]:
- """
- Preload all settings with a given prefix.
-
- This is useful for loading all settings in a category (e.g., 'llm.*')
- in a single operation.
-
- Args:
- prefix: Setting key prefix (e.g., 'llm', 'search')
-
- Returns:
- Dictionary of all settings with the prefix
- """
- if not self.db_session:
- # No database, use get_setting which will use defaults
- return self.get_setting(prefix, {})
-
- try:
- # Query all settings with the prefix
- settings = (
- self.db_session.query(Setting)
- .filter(Setting.key.like(f"{prefix}.%"))
- .all()
- )
-
- # Build result dictionary
- result = {}
- for setting in settings:
- # Remove prefix for nested structure
- key = setting.key[len(prefix) + 1 :] # +1 for the dot
- result[key] = self._SettingsManager__get_typed_setting_value(
- setting, None, check_env=True
- )
-
- return result
-
- except Exception as e:
- logger.error(f"Error preloading settings by prefix {prefix}: {e}")
- return {}
-
- # Performance optimization: Set multiple settings in a single transaction
- @invalidate_cache(namespace="settings")
- def set_settings_batch(
- self, settings: Dict[str, Any], commit: bool = True
- ) -> Dict[str, bool]:
- """
- Set multiple settings in a single database transaction.
-
- This is more efficient than multiple individual set_setting calls.
-
- Args:
- settings: Dictionary mapping keys to values
- commit: Whether to commit the transaction
-
- Returns:
- Dictionary mapping keys to success status
- """
- if not self.db_session:
- logger.error("Cannot batch set settings without database session")
- return {key: False for key in settings}
-
- if self.settings_locked:
- logger.error("Cannot batch set settings when locked")
- return {key: False for key in settings}
-
- results = {}
-
- try:
- # Process all settings in a single transaction
- for key, value in settings.items():
- try:
- # Use parent's set_setting but without commit
- success = super().set_setting(key, value, commit=False)
- results[key] = success
- except Exception as e:
- logger.error(f"Error setting {key}: {e}")
- results[key] = False
-
- # Commit once if all successful
- if commit and all(results.values()):
- self.db_session.commit()
- elif not all(results.values()):
- # Rollback if any failed
- self.db_session.rollback()
-
- except Exception as e:
- logger.error(f"Error in batch set: {e}")
- self.db_session.rollback()
- return {key: False for key in settings}
-
- # Invalidate cache for all affected keys
- if self._cache_strategy and any(results.values()):
- successful_keys = [k for k, v in results.items() if v]
- self._cache_strategy.invalidate(
- self.user_id, "settings", successful_keys
- )
-
- return results
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 979b00f1c9..d3c2759027 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -74,6 +74,9 @@ class SettingsManager(ISettingsManager):
# Initialize settings lock as None - will be checked lazily
self.__settings_locked = None
+ # Simple in-memory cache
+ self._cache = {}
+
def _check_thread_safety(self):
"""Check if this instance is being used in the same thread it was created in."""
current_thread_id = threading.get_ident()
@@ -223,14 +226,23 @@ class SettingsManager(ISettingsManager):
Returns:
Setting value or default if not found
"""
+ # Check cache first
+ cache_key = f"{key}:{check_env}"
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+
# If using database first approach and session available, check database
try:
settings = self.__query_settings(key)
if len(settings) == 1:
# This is a bottom-level key.
- return self.__get_typed_setting_value(
+ result = self.__get_typed_setting_value(
settings[0], default, check_env
)
+ # Cache the result
+ cache_key = f"{key}:{check_env}"
+ self._cache[cache_key] = result
+ return result
elif len(settings) > 1:
# This is a higher-level key.
settings_map = {}
@@ -239,6 +251,9 @@ class SettingsManager(ISettingsManager):
settings_map[output_key] = self.__get_typed_setting_value(
setting, default, check_env
)
+ # Cache the result
+ cache_key = f"{key}:{check_env}"
+ self._cache[cache_key] = settings_map
return settings_map
except SQLAlchemyError as e:
logger.error(f"Error retrieving setting {key} from database: {e}")
@@ -311,8 +326,13 @@ class SettingsManager(ISettingsManager):
if commit:
self.db_session.commit()
+ # Clear cache on successful write
+ self._cache.clear()
# Emit WebSocket event for settings change
self._emit_settings_changed([key])
+ else:
+ # Clear cache even without commit to be safe
+ self._cache.clear()
return True
except SQLAlchemyError as e:
@@ -320,13 +340,24 @@ class SettingsManager(ISettingsManager):
self.db_session.rollback()
return False
- def get_all_settings(self) -> Dict[str, Any]:
+ def clear_cache(self):
+ """Clear the settings cache."""
+ self._cache.clear()
+ logger.debug("Settings cache cleared")
+
+ def get_all_settings(self, bypass_cache: bool = False) -> Dict[str, Any]:
"""
Get all settings
+ Args:
+ bypass_cache: If True, bypass the cache and read directly from database
+
Returns:
Dictionary of all settings
"""
+ if bypass_cache:
+ self._cache.clear()
+
result = {}
# Add database settings if available
@@ -456,8 +487,13 @@ class SettingsManager(ISettingsManager):
if commit:
self.db_session.commit()
+ # Clear cache on successful write
+ self._cache.clear()
# Emit WebSocket event for settings change
self._emit_settings_changed([setting_obj.key])
+ else:
+ # Clear cache even without commit to be safe
+ self._cache.clear()
return db_setting
@@ -495,6 +531,13 @@ class SettingsManager(ISettingsManager):
if commit:
self.db_session.commit()
+ # Clear cache on successful delete
+ if result > 0:
+ self._cache.clear()
+ else:
+ # Clear cache even without commit to be safe
+ if result > 0:
+ self._cache.clear()
return result > 0
except SQLAlchemyError as e:
@@ -589,6 +632,8 @@ class SettingsManager(ISettingsManager):
if commit or delete_extra:
self.db_session.commit()
logger.info(f"Successfully imported {len(settings_data)} settings")
+ # Clear cache after import
+ self._cache.clear()
# Emit WebSocket event for all imported settings
self._emit_settings_changed(list(settings_data.keys()))
diff --git a/src/local_deep_research/settings/settings_cache/__init__.py b/src/local_deep_research/settings/settings_cache/__init__.py
deleted file mode 100644
index 65d6fff9cc..0000000000
--- a/src/local_deep_research/settings/settings_cache/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""
-Cache infrastructure for settings management.
-
-This module provides caching decorators and strategies for the settings system.
-"""
-
-from .decorators import cached, invalidate_cache
-from .strategies import (
- CacheStrategy,
- KeyInvalidationStrategy,
- PatternInvalidationStrategy,
-)
-
-__all__ = [
- "cached",
- "invalidate_cache",
- "CacheStrategy",
- "KeyInvalidationStrategy",
- "PatternInvalidationStrategy",
-]
diff --git a/src/local_deep_research/settings/settings_cache/decorators.py b/src/local_deep_research/settings/settings_cache/decorators.py
deleted file mode 100644
index 244bd9f0a5..0000000000
--- a/src/local_deep_research/settings/settings_cache/decorators.py
+++ /dev/null
@@ -1,163 +0,0 @@
-"""
-Cache decorators for settings management.
-
-This module provides decorators to add caching functionality to any method
-without changing its implementation.
-"""
-
-import functools
-from typing import Callable, Optional
-from loguru import logger
-
-from ...memory_cache.config import get_thread_local_cache
-
-
-def cached(
- namespace: str = "settings",
- ttl: Optional[int] = None,
- key_prefix: Optional[str] = None,
-) -> Callable:
- """
- Decorator to cache method results.
-
- Args:
- namespace: Cache namespace
- ttl: Time to live in seconds (None for default)
- key_prefix: Optional prefix for cache keys
-
- Returns:
- Decorated function
- """
-
- def decorator(func: Callable) -> Callable:
- @functools.wraps(func)
- def wrapper(self, *args, **kwargs):
- # Build cache key
- cache_key = f"{func.__name__}"
- if args:
- cache_key += f":{':'.join(str(arg) for arg in args)}"
- if kwargs:
- sorted_kwargs = sorted(kwargs.items())
- cache_key += (
- f":{':'.join(f'{k}={v}' for k, v in sorted_kwargs)}"
- )
-
- if key_prefix:
- cache_key = f"{key_prefix}:{cache_key}"
-
- # Get cache instance
- cache = get_thread_local_cache()
-
- # Try to get from cache
- try:
- # For settings, we need the user_id
- user_id = getattr(self, "user_id", "global")
- value = cache.get(user_id, namespace, cache_key)
-
- # Check if we got a value (not NO_VALUE)
- from dogpile.cache.api import NO_VALUE
-
- if value is not NO_VALUE:
- logger.debug(f"Cache hit for {namespace}:{cache_key}")
- return value
- except Exception as e:
- logger.warning(f"Cache get failed for {cache_key}: {e}")
-
- # Call the original function
- result = func(self, *args, **kwargs)
-
- # Store in cache
- try:
- user_id = getattr(self, "user_id", "global")
- expiration_time = ttl if ttl is not None else None
- cache.set(
- user_id,
- namespace,
- cache_key,
- result,
- expiration_time=expiration_time,
- )
- logger.debug(f"Cached result for {namespace}:{cache_key}")
- except Exception as e:
- logger.warning(f"Cache set failed for {cache_key}: {e}")
-
- return result
-
- # Store metadata on wrapper for introspection
- wrapper._cached = True
- wrapper._cache_namespace = namespace
- wrapper._cache_ttl = ttl
-
- return wrapper
-
- return decorator
-
-
-def invalidate_cache(
- namespace: str = "settings", pattern: Optional[str] = None
-) -> Callable:
- """
- Decorator to invalidate cache after method execution.
-
- Args:
- namespace: Cache namespace to invalidate
- pattern: Optional pattern for selective invalidation
-
- Returns:
- Decorated function
- """
-
- def decorator(func: Callable) -> Callable:
- @functools.wraps(func)
- def wrapper(self, *args, **kwargs):
- # Call the original function first
- result = func(self, *args, **kwargs)
-
- # Only invalidate if the operation was successful
- if result not in (False, None):
- try:
- cache = get_thread_local_cache()
- user_id = getattr(self, "user_id", "global")
-
- if pattern:
- # Pattern-based invalidation
- cache.invalidate(user_id, namespace, pattern)
- logger.debug(
- f"Invalidated cache pattern {namespace}:{pattern}"
- )
- else:
- # Invalidate entire namespace
- cache.invalidate(user_id, namespace)
- logger.debug(f"Invalidated cache namespace {namespace}")
-
- except Exception as e:
- logger.warning(f"Cache invalidation failed: {e}")
-
- return result
-
- # Store metadata
- wrapper._invalidates_cache = True
- wrapper._invalidate_namespace = namespace
- wrapper._invalidate_pattern = pattern
-
- return wrapper
-
- return decorator
-
-
-def cache_key(*key_args: str) -> Callable:
- """
- Decorator to specify which arguments should be used for cache key generation.
-
- Args:
- *key_args: Names of arguments to include in cache key
-
- Returns:
- Decorated function
- """
-
- def decorator(func: Callable) -> Callable:
- func._cache_key_args = key_args
- return func
-
- return decorator
diff --git a/src/local_deep_research/settings/settings_cache/optimizations.py b/src/local_deep_research/settings/settings_cache/optimizations.py
deleted file mode 100644
index 66aa100994..0000000000
--- a/src/local_deep_research/settings/settings_cache/optimizations.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""
-Performance optimization utilities for settings cache.
-
-This module provides additional performance optimizations for the settings system.
-"""
-
-from typing import Dict, List, Any, Set
-from collections import defaultdict
-from loguru import logger
-import time
-
-
-class SettingsAccessPatternTracker:
- """
- Track access patterns to optimize cache warming and prefetching.
- """
-
- def __init__(self, window_size: int = 1000):
- self.access_history: List[tuple] = [] # (timestamp, key)
- self.access_count: Dict[str, int] = defaultdict(int)
- self.co_access: Dict[str, Set[str]] = defaultdict(set)
- self.window_size = window_size
-
- def track_access(self, key: str) -> None:
- """Track a setting access."""
- timestamp = time.time()
- self.access_history.append((timestamp, key))
- self.access_count[key] += 1
-
- # Maintain window size
- if len(self.access_history) > self.window_size:
- self.access_history.pop(0)
-
- # Track co-access patterns (settings accessed together)
- if len(self.access_history) > 1:
- recent_keys = [k for _, k in self.access_history[-10:]]
- for other_key in recent_keys:
- if other_key != key:
- self.co_access[key].add(other_key)
- self.co_access[other_key].add(key)
-
- def get_hot_keys(self, top_n: int = 20) -> List[str]:
- """Get the most frequently accessed keys."""
- sorted_keys = sorted(
- self.access_count.items(), key=lambda x: x[1], reverse=True
- )
- return [key for key, _ in sorted_keys[:top_n]]
-
- def get_related_keys(self, key: str) -> Set[str]:
- """Get keys frequently accessed together with the given key."""
- return self.co_access.get(key, set())
-
- def suggest_prefetch(self, key: str) -> List[str]:
- """Suggest keys to prefetch based on access patterns."""
- related = self.get_related_keys(key)
- # Sort by access frequency
- return sorted(
- related, key=lambda k: self.access_count.get(k, 0), reverse=True
- )[:5]
-
-
-class LazySettingsLoader:
- """
- Lazy loading wrapper for settings that delays database access.
- """
-
- def __init__(self, manager, key: str, default: Any = None):
- self._manager = manager
- self._key = key
- self._default = default
- self._value = None
- self._loaded = False
-
- def __repr__(self):
- if not self._loaded:
- return f"<LazySettings({self._key}, not loaded)>"
- return f"<LazySettings({self._key}={self._value})>"
-
- def get(self) -> Any:
- """Load the setting value if not already loaded."""
- if not self._loaded:
- self._value = self._manager.get_setting(self._key, self._default)
- self._loaded = True
- return self._value
-
- # Make it behave like the actual value when accessed
- def __getattr__(self, name):
- return getattr(self.get(), name)
-
- def __str__(self):
- return str(self.get())
-
- def __bool__(self):
- return bool(self.get())
-
-
-class SettingsPrefetcher:
- """
- Intelligent prefetching based on access patterns.
- """
-
- def __init__(self, manager, tracker: SettingsAccessPatternTracker):
- self.manager = manager
- self.tracker = tracker
-
- def prefetch_for_operation(self, operation: str) -> Dict[str, Any]:
- """
- Prefetch settings commonly needed for a specific operation.
-
- Args:
- operation: Operation name (e.g., 'research', 'search', 'export')
-
- Returns:
- Dictionary of prefetched settings
- """
- # Define common setting groups per operation
- operation_settings = {
- "research": [
- "llm.provider",
- "llm.model",
- "llm.temperature",
- "llm.max_tokens",
- "search.tool",
- "search.iterations",
- "search.questions_per_iteration",
- "research.max_results",
- "research.timeout",
- ],
- "search": [
- "search.tool",
- "search.iterations",
- "search.questions_per_iteration",
- "search.timeout",
- "search.max_results_per_query",
- ],
- "export": [
- "report.format",
- "report.include_metadata",
- "report.include_sources",
- "report.citation_style",
- ],
- "ui": [
- "app.theme",
- "app.language",
- "app.version",
- "app.lock_settings",
- "ui.show_tooltips",
- "ui.animation_speed",
- ],
- }
-
- keys = operation_settings.get(operation, [])
-
- # Add frequently co-accessed keys
- additional_keys = set()
- for key in keys:
- additional_keys.update(self.tracker.suggest_prefetch(key))
-
- all_keys = list(set(keys) | additional_keys)
-
- # Use batch get for efficiency
- return self.manager.get_settings_batch(all_keys)
-
- def adaptive_prefetch(self, initial_key: str) -> Dict[str, Any]:
- """
- Adaptively prefetch based on access patterns.
-
- Args:
- initial_key: The key being accessed
-
- Returns:
- Dictionary of prefetched settings
- """
- # Track the access
- self.tracker.track_access(initial_key)
-
- # Get related keys
- related_keys = self.tracker.suggest_prefetch(initial_key)
-
- if related_keys:
- # Prefetch related keys
- all_keys = [initial_key] + list(related_keys)
- return self.manager.get_settings_batch(all_keys)
- else:
- # Just get the single key
- return {initial_key: self.manager.get_setting(initial_key)}
-
-
-def optimize_settings_for_request(settings_manager, request_type: str) -> None:
- """
- Optimize settings for a specific request type by warming cache.
-
- Args:
- settings_manager: The settings manager instance
- request_type: Type of request (e.g., 'research', 'api', 'ui')
- """
- # Define settings to warm per request type
- request_settings = {
- "research": [
- "llm.*", # All LLM settings
- "search.*", # All search settings
- "research.*", # All research settings
- ],
- "api": [
- "api.rate_limit",
- "api.timeout",
- "api.max_requests",
- "llm.provider",
- "llm.model",
- ],
- "ui": [
- "app.*", # All app settings
- "ui.*", # All UI settings
- ],
- }
-
- settings_to_warm = request_settings.get(request_type, [])
-
- for setting in settings_to_warm:
- if "*" in setting:
- # Preload by prefix
- prefix = setting.rstrip(".*")
- settings_manager.preload_settings_by_prefix(prefix)
- else:
- # Warm individual setting
- settings_manager.get_setting(setting)
-
- logger.debug(f"Warmed cache for {request_type} request")
diff --git a/src/local_deep_research/settings/settings_cache/strategies.py b/src/local_deep_research/settings/settings_cache/strategies.py
deleted file mode 100644
index dbb07a3db6..0000000000
--- a/src/local_deep_research/settings/settings_cache/strategies.py
+++ /dev/null
@@ -1,123 +0,0 @@
-"""
-Cache invalidation strategies for settings management.
-
-This module provides different strategies for invalidating cached settings
-based on various criteria.
-"""
-
-from abc import ABC, abstractmethod
-from typing import List, Optional
-from loguru import logger
-
-from ...memory_cache.config import get_thread_local_cache
-
-
-class CacheStrategy(ABC):
- """Abstract base class for cache invalidation strategies."""
-
- @abstractmethod
- def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
- """
- Invalidate cache entries based on the strategy.
-
- Args:
- user_id: User identifier
- namespace: Cache namespace
- keys: List of keys that changed
- """
- pass
-
-
-class KeyInvalidationStrategy(CacheStrategy):
- """Invalidate specific cache keys."""
-
- def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
- """Invalidate specific keys in the cache."""
- cache = get_thread_local_cache()
-
- for key in keys:
- try:
- # Invalidate the specific key (exact match)
- cache.invalidate(user_id, namespace, key)
- logger.debug(f"Invalidated cache key {namespace}:{key}")
- except Exception as e:
- logger.warning(f"Failed to invalidate key {key}: {e}")
-
-
-class PatternInvalidationStrategy(CacheStrategy):
- """Invalidate cache entries matching patterns."""
-
- def __init__(self, patterns: Optional[List[str]] = None):
- """
- Initialize with optional patterns.
-
- Args:
- patterns: List of patterns to match for invalidation
- """
- self.patterns = patterns or []
-
- def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
- """Invalidate entries matching patterns."""
- cache = get_thread_local_cache()
-
- # If no patterns, invalidate based on key prefixes
- if not self.patterns:
- # Generate patterns from keys (e.g., "llm.model" -> "llm.*")
- patterns = set()
- for key in keys:
- parts = key.split(".")
- if len(parts) > 1:
- # Invalidate the entire category
- patterns.add(f"{parts[0]}.*")
- patterns.add(f"{key}*")
- self.patterns = list(patterns)
-
- # Invalidate based on patterns
- for pattern in self.patterns:
- try:
- cache.invalidate(user_id, namespace, pattern)
- logger.debug(f"Invalidated cache pattern {namespace}:{pattern}")
- except Exception as e:
- logger.warning(f"Failed to invalidate pattern {pattern}: {e}")
-
-
-class HierarchicalInvalidationStrategy(CacheStrategy):
- """Invalidate cache entries based on hierarchical keys."""
-
- def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
- """Invalidate entries based on hierarchical relationships."""
- cache = get_thread_local_cache()
-
- # Build hierarchy patterns
- patterns = set()
- for key in keys:
- parts = key.split(".")
-
- # Add patterns for all levels
- for i in range(1, len(parts) + 1):
- partial_key = ".".join(parts[:i])
- patterns.add(f"{partial_key}*")
-
- # Now we can use pattern-based invalidation
- for pattern in patterns:
- try:
- cache.invalidate(user_id, namespace, pattern)
- logger.debug(f"Invalidated cache pattern {namespace}:{pattern}")
- except Exception as e:
- logger.warning(f"Failed to invalidate pattern {pattern}: {e}")
-
-
-class FullInvalidationStrategy(CacheStrategy):
- """Invalidate the entire namespace."""
-
- def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
- """Invalidate the entire namespace."""
- cache = get_thread_local_cache()
-
- try:
- cache.invalidate(user_id, namespace)
- logger.debug(
- f"Invalidated entire namespace {namespace} for user {user_id}"
- )
- except Exception as e:
- logger.warning(f"Failed to invalidate namespace {namespace}: {e}")
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index 800a5f9759..80f4ae3f20 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -89,7 +89,7 @@ def get_settings_manager(
Args:
db_session: Optional database session
- username: Optional username for caching (required for CachedSettingsManager)
+ username: Optional username for caching (required for SettingsManager)
Returns:
The appropriate settings manager instance.
@@ -107,14 +107,10 @@ def get_settings_manager(
username = "anonymous"
# Import here to avoid circular imports
- from ..settings import SettingsManager, CachedSettingsManager
+ from ..settings import SettingsManager
- # Use cached version if we have both session and username
- if db_session is not None and username is not None:
- return CachedSettingsManager(db_session, username)
- else:
- # Use regular version without caching
- return SettingsManager(db_session)
+ # Always use regular SettingsManager (now with built-in simple caching)
+ return SettingsManager(db_session)
def no_db_settings(func: Callable[..., Any]) -> Callable[..., Any]:
@@ -148,7 +144,7 @@ def no_db_settings(func: Callable[..., Any]) -> Callable[..., Any]:
return wrapper
-def get_db_setting(
+def get_setting_from_db_main_thread(
key: str, default_value: Any | None = None, username: str | None = None
) -> str | Dict[str, Any] | None:
"""
diff --git a/src/local_deep_research/utilities/get_settings_manager.py b/src/local_deep_research/utilities/get_settings_manager.py
index d7c5da077f..1af95eaebc 100644
--- a/src/local_deep_research/utilities/get_settings_manager.py
+++ b/src/local_deep_research/utilities/get_settings_manager.py
@@ -9,7 +9,7 @@ from typing import Optional
from sqlalchemy.orm import Session
from loguru import logger
-from ..settings import SettingsManager, CachedSettingsManager
+from local_deep_research.settings import SettingsManager
def get_settings_manager(
@@ -29,8 +29,8 @@ def get_settings_manager(
SettingsManager instance (cached or regular)
"""
if use_cache and user_id:
- logger.debug(f"Creating CachedSettingsManager for user {user_id}")
- return CachedSettingsManager(db_session, user_id)
+ logger.debug(f"Creating SettingsManager for user {user_id}")
+ return SettingsManager(db_session)
else:
logger.debug("Creating regular SettingsManager")
return SettingsManager(db_session)
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index d1ae165cde..79a1d36552 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -10,7 +10,7 @@ from functools import wraps
from flask import Blueprint, jsonify, request
from ..api.research_functions import analyze_documents
-from ..utilities.db_utils import get_db_setting
+from ..utilities.db_utils import get_setting_from_db_main_thread
# Create a blueprint for the API
api_blueprint = Blueprint("api_v1", __name__, url_prefix="/api/v1")
@@ -30,14 +30,14 @@ def api_access_control(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Check if API is enabled
- api_enabled = get_db_setting(
+ api_enabled = get_setting_from_db_main_thread(
"app.enable_api", True
) # Default to enabled
if not api_enabled:
return jsonify({"error": "API access is disabled"}), 403
# Implement rate limiting
- rate_limit = get_db_setting(
+ rate_limit = get_setting_from_db_main_thread(
"app.api_rate_limit", 60
) # Default 60 requests per minute
if rate_limit:
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 2a79dc4dc3..5cb448de52 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -52,7 +52,31 @@ def create_app():
)
# App configuration
- app.config["SECRET_KEY"] = "deep-research-secret-key"
+ # Generate or load a unique SECRET_KEY per installation
+ import secrets
+ from ..config.paths import get_data_directory
+
+ secret_key_file = os.path.join(get_data_directory(), ".secret_key")
+ if os.path.exists(secret_key_file):
+ try:
+ with open(secret_key_file, "r") as f:
+ app.config["SECRET_KEY"] = f.read().strip()
+ except Exception as e:
+ logger.warning(f"Could not read secret key file: {e}")
+ app.config["SECRET_KEY"] = secrets.token_hex(32)
+ else:
+ # Generate a new key on first run
+ new_key = secrets.token_hex(32)
+ try:
+ os.makedirs(os.path.dirname(secret_key_file), exist_ok=True)
+ with open(secret_key_file, "w") as f:
+ f.write(new_key)
+ os.chmod(secret_key_file, 0o600) # Secure file permissions
+ app.config["SECRET_KEY"] = new_key
+ logger.info("Generated new SECRET_KEY for this installation")
+ except Exception as e:
+ logger.warning(f"Could not save secret key file: {e}")
+ app.config["SECRET_KEY"] = new_key
app.config["SESSION_COOKIE_SECURE"] = False # Allow HTTP for local testing
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
@@ -272,7 +296,7 @@ def register_blueprints(app):
"""Root route - redirect to login if not authenticated"""
from flask import redirect, session, url_for
- from ..utilities.db_utils import get_db_setting
+ from ..utilities.db_utils import get_setting_from_db_main_thread
from .utils.templates import render_template_with_defaults
# Check if user is authenticated
@@ -281,14 +305,18 @@ def register_blueprints(app):
# Load current settings from database
settings = {
- "llm_provider": get_db_setting("llm.provider", "ollama"),
- "llm_model": get_db_setting("llm.model", ""),
- "llm_openai_endpoint_url": get_db_setting(
+ "llm_provider": get_setting_from_db_main_thread(
+ "llm.provider", "ollama"
+ ),
+ "llm_model": get_setting_from_db_main_thread("llm.model", ""),
+ "llm_openai_endpoint_url": get_setting_from_db_main_thread(
"llm.openai_endpoint.url", ""
),
- "search_tool": get_db_setting("search.tool", ""),
- "search_iterations": get_db_setting("search.iterations", 2),
- "search_questions_per_iteration": get_db_setting(
+ "search_tool": get_setting_from_db_main_thread("search.tool", ""),
+ "search_iterations": get_setting_from_db_main_thread(
+ "search.iterations", 2
+ ),
+ "search_questions_per_iteration": get_setting_from_db_main_thread(
"search.questions_per_iteration", 3
),
}
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 8c360fc970..5c8fd6c6c5 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -66,7 +66,7 @@ def login():
# Check if user has settings loaded (first login after migration)
try:
from ...database.models import Setting
- from ...settings import CachedSettingsManager
+ from local_deep_research.settings import SettingsManager
db_session = db_manager.get_session(username)
if db_session:
@@ -81,7 +81,7 @@ def login():
logger.info(
f"First login for {username} - loading default settings"
)
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
settings_manager.load_from_defaults_file(commit=True)
logger.info(f"Default settings loaded for user {username}")
except Exception as e:
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 79ab276f50..16458e8459 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -4,7 +4,6 @@ from flask import (
current_app,
jsonify,
request,
- session as flask_session,
)
from loguru import logger
@@ -23,7 +22,7 @@ from ..services.resource_service import (
delete_resource,
get_resources_for_research,
)
-from ...settings import CachedSettingsManager
+from local_deep_research.settings import SettingsManager
# Create blueprint
api_bp = Blueprint("api", __name__)
@@ -34,9 +33,8 @@ api_bp = Blueprint("api", __name__)
def get_current_config():
"""Get the current configuration from database settings."""
try:
- username = flask_session.get("username")
session = get_db_session()
- settings_manager = CachedSettingsManager(session, username)
+ settings_manager = SettingsManager(session)
config = {
"provider": settings_manager.get_setting(
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index 3f85e80f1f..0a40a95188 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -1,10 +1,10 @@
import json
import traceback
-from flask import Blueprint, jsonify, make_response
+from flask import Blueprint, jsonify, make_response, session, request
from ...database.models import ResearchHistory
-from ...utilities.db_utils import get_db_session
+from ...database.session_context import get_user_db_session
from ..auth.decorators import login_required
from ..models.database import (
get_logs_for_research,
@@ -32,15 +32,18 @@ def history_page():
@login_required
def get_history():
"""Get the research history JSON data"""
+ username = session.get("username")
+ if not username:
+ return jsonify({"status": "error", "message": "Not authenticated"}), 401
+
try:
- db_session = get_db_session()
- # Get all history records ordered by latest first
- results = (
- db_session.query(ResearchHistory)
- .order_by(ResearchHistory.created_at.desc())
- .all()
- )
- db_session.close()
+ with get_user_db_session(username) as db_session:
+ # Get all history records ordered by latest first
+ results = (
+ db_session.query(ResearchHistory)
+ .order_by(ResearchHistory.created_at.desc())
+ .all()
+ )
# Convert to list of dicts
history = []
@@ -144,11 +147,14 @@ def get_history():
@history_bp.route("/status/<string:research_id>")
@login_required
def get_research_status(research_id):
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
- db_session.close()
+ username = session.get("username")
+ if not username:
+ return jsonify({"status": "error", "message": "Not authenticated"}), 401
+
+ 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(
@@ -193,13 +199,44 @@ def get_research_status(research_id):
@login_required
def get_research_details(research_id):
"""Get detailed progress log for a specific research"""
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
- db_session.close()
+ from loguru import logger
+
+ logger.info(f"Details route accessed for research_id: {research_id}")
+ logger.info(f"Request headers: {dict(request.headers)}")
+ logger.info(f"Request URL: {request.url}")
+
+ username = session.get("username")
+ if not username:
+ logger.error("No username in session")
+ return jsonify({"status": "error", "message": "Not authenticated"}), 401
+
+ try:
+ with get_user_db_session(username) as db_session:
+ # Log all research IDs for this user
+ all_research = db_session.query(
+ ResearchHistory.id, ResearchHistory.query
+ ).all()
+ logger.info(
+ f"All research for user {username}: {[(r.id, r.query[:30]) for r in all_research]}"
+ )
+
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ logger.info(f"Research query result: {research}")
+ except Exception as e:
+ logger.error(f"Database error: {e}")
+ import traceback
+
+ logger.error(traceback.format_exc())
+ return jsonify(
+ {"status": "error", "message": f"Database error: {str(e)}"}
+ ), 500
if not research:
+ logger.error(f"Research not found for id: {research_id}")
return jsonify(
{"status": "error", "message": "Research not found"}
), 404
@@ -255,59 +292,59 @@ def get_report(research_id):
username = current_user()
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
-
- if not research:
- db_session.close()
- return jsonify({"status": "error", "message": "Report not found"}), 404
-
- try:
- # Get report using storage abstraction
- storage = get_report_storage(session=db_session)
- report_data = storage.get_report_with_metadata(research_id, username)
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory).filter_by(id=research_id).first()
+ )
- if not report_data:
- db_session.close()
+ if not research:
return jsonify(
- {"status": "error", "message": "Report content not found"}
+ {"status": "error", "message": "Report not found"}
), 404
- # Extract content and metadata
- content = report_data.get("content", "")
- stored_metadata = report_data.get("metadata", {})
+ try:
+ # Get report using storage abstraction
+ storage = get_report_storage(session=db_session)
+ report_data = storage.get_report_with_metadata(
+ research_id, username
+ )
- # Create an enhanced metadata dictionary with database fields
- enhanced_metadata = {
- "query": research.query,
- "mode": research.mode,
- "created_at": research.created_at,
- "completed_at": research.completed_at,
- "duration": research.duration_seconds,
- }
+ if not report_data:
+ return jsonify(
+ {"status": "error", "message": "Report content not found"}
+ ), 404
- # Merge with stored metadata
- enhanced_metadata.update(stored_metadata)
+ # Extract content and metadata
+ content = report_data.get("content", "")
+ stored_metadata = report_data.get("metadata", {})
- return jsonify(
- {
- "status": "success",
- "content": content,
+ # Create an enhanced metadata dictionary with database fields
+ enhanced_metadata = {
"query": research.query,
"mode": research.mode,
"created_at": research.created_at,
"completed_at": research.completed_at,
- "metadata": enhanced_metadata,
+ "duration": research.duration_seconds,
}
- )
- except Exception:
- return jsonify(
- {"status": "error", "message": "Failed to retrieve report"}
- ), 500
- finally:
- db_session.close()
+
+ # Merge with stored metadata
+ enhanced_metadata.update(stored_metadata)
+
+ return jsonify(
+ {
+ "status": "success",
+ "content": content,
+ "query": research.query,
+ "mode": research.mode,
+ "created_at": research.created_at,
+ "completed_at": research.completed_at,
+ "metadata": enhanced_metadata,
+ }
+ )
+ except Exception:
+ return jsonify(
+ {"status": "error", "message": "Failed to retrieve report"}
+ ), 500
@history_bp.route("/markdown/<string:research_id>")
@@ -319,45 +356,46 @@ def get_markdown(research_id):
username = current_user()
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
-
- if not research:
- db_session.close()
- return jsonify({"status": "error", "message": "Report not found"}), 404
-
- try:
- # Get report using storage abstraction
- storage = get_report_storage(session=db_session)
- content = storage.get_report(research_id, username)
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory).filter_by(id=research_id).first()
+ )
- if not content:
- db_session.close()
+ if not research:
return jsonify(
- {"status": "error", "message": "Report content not found"}
+ {"status": "error", "message": "Report not found"}
), 404
- return jsonify({"status": "success", "content": content})
- except Exception:
- return jsonify(
- {"status": "error", "message": "Failed to retrieve report"}
- ), 500
- finally:
- db_session.close()
+ try:
+ # Get report using storage abstraction
+ storage = get_report_storage(session=db_session)
+ content = storage.get_report(research_id, username)
+
+ if not content:
+ return jsonify(
+ {"status": "error", "message": "Report content not found"}
+ ), 404
+
+ return jsonify({"status": "success", "content": content})
+ except Exception:
+ return jsonify(
+ {"status": "error", "message": "Failed to retrieve report"}
+ ), 500
@history_bp.route("/logs/<string:research_id>")
@login_required
def get_research_logs(research_id):
"""Get logs for a specific research ID"""
+ username = session.get("username")
+ if not username:
+ return jsonify({"status": "error", "message": "Not authenticated"}), 401
+
# First check if the research exists
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
- db_session.close()
+ 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(
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index c29ce92e30..56312c5883 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -339,7 +339,7 @@ def get_rate_limiting_analytics(period="30d", username=None):
if not username:
return {
- "rate_limiting_analytics": {
+ "rate_limiting": {
"total_attempts": 0,
"successful_attempts": 0,
"failed_attempts": 0,
@@ -347,7 +347,8 @@ def get_rate_limiting_analytics(period="30d", username=None):
"rate_limit_events": 0,
"avg_wait_time": 0,
"avg_successful_wait": 0,
- "engine_stats": {},
+ "tracked_engines": 0,
+ "engine_stats": [],
"total_engines_tracked": 0,
"healthy_engines": 0,
"degraded_engines": 0,
@@ -356,79 +357,49 @@ def get_rate_limiting_analytics(period="30d", username=None):
}
}
- # Calculate date range
- days_map = {"7d": 7, "30d": 30, "90d": 90, "365d": 365, "all": None}
- days = days_map.get(period, 30)
+ # Calculate date range for timestamp filtering
+ import time
+
+ if period == "7d":
+ cutoff_time = time.time() - (7 * 24 * 3600)
+ elif period == "30d":
+ cutoff_time = time.time() - (30 * 24 * 3600)
+ elif period == "3m":
+ cutoff_time = time.time() - (90 * 24 * 3600)
+ elif period == "1y":
+ cutoff_time = time.time() - (365 * 24 * 3600)
+ else: # all
+ cutoff_time = 0
with get_user_db_session(username) as session:
- # Get current rate limit estimates
- estimates = session.query(RateLimitEstimate).all()
+ # Get rate limit attempts
+ rate_limit_query = session.query(RateLimitAttempt)
- # Get recent attempts for analytics
- attempts_query = session.query(RateLimitAttempt)
- if days:
- cutoff_timestamp = (
- datetime.now() - timedelta(days=days)
- ).timestamp()
- attempts_query = attempts_query.filter(
- RateLimitAttempt.timestamp >= cutoff_timestamp
+ # Apply time filter
+ if cutoff_time > 0:
+ rate_limit_query = rate_limit_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
)
- attempts = attempts_query.all()
-
- # Calculate analytics
- total_attempts = len(attempts)
- successful_attempts = len([a for a in attempts if a.success])
+ # Get rate limit statistics
+ total_attempts = rate_limit_query.count()
+ successful_attempts = rate_limit_query.filter(
+ RateLimitAttempt.success
+ ).count()
failed_attempts = total_attempts - successful_attempts
- # Engine-specific analytics
- engine_stats = {}
- for estimate in estimates:
- engine_attempts = [
- a for a in attempts if a.engine_type == estimate.engine_type
- ]
- engine_success = len([a for a in engine_attempts if a.success])
- engine_total = len(engine_attempts)
-
- engine_stats[estimate.engine_type] = {
- "base_wait_seconds": round(estimate.base_wait_seconds, 2),
- "min_wait_seconds": round(estimate.min_wait_seconds, 2),
- "max_wait_seconds": round(estimate.max_wait_seconds, 2),
- "success_rate": round(estimate.success_rate * 100, 1),
- "total_attempts": estimate.total_attempts,
- "recent_attempts": engine_total,
- "recent_success_rate": round(
- (engine_success / engine_total * 100)
- if engine_total > 0
- else 0,
- 1,
- ),
- "last_updated": datetime.fromtimestamp(
- estimate.last_updated
- ).strftime("%Y-%m-%d %H:%M:%S"),
- "status": "healthy"
- if estimate.success_rate > 0.8
- else "degraded"
- if estimate.success_rate > 0.5
- else "poor",
- }
+ # Count rate limiting events (failures with RateLimitError)
+ rate_limit_events = rate_limit_query.filter(
+ ~RateLimitAttempt.success,
+ RateLimitAttempt.error_type == "RateLimitError",
+ ).count()
- # Overall success rate trend
- success_rate = round(
- (successful_attempts / total_attempts * 100)
- if total_attempts > 0
- else 0,
- 1,
+ logger.info(
+ f"Rate limit attempts in database: total={total_attempts}, successful={successful_attempts}"
)
- # Rate limiting events (failures)
- rate_limit_events = len(
- [
- a
- for a in attempts
- if not a.success and a.error_type == "RateLimitError"
- ]
- )
+ # Get all attempts for detailed calculations
+ attempts = rate_limit_query.all()
# Calculate average wait times
if attempts:
@@ -447,45 +418,146 @@ def get_rate_limiting_analytics(period="30d", username=None):
avg_wait_time = 0
avg_successful_wait = 0
- return {
- "rate_limiting_analytics": {
+ # Get tracked engines - count distinct engine types from attempts
+ tracked_engines_query = session.query(
+ func.count(func.distinct(RateLimitAttempt.engine_type))
+ )
+ if cutoff_time > 0:
+ tracked_engines_query = tracked_engines_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
+ )
+ tracked_engines = tracked_engines_query.scalar() or 0
+
+ # Get engine-specific stats from attempts
+ engine_stats = []
+
+ # Get distinct engine types from attempts
+ engine_types_query = session.query(
+ RateLimitAttempt.engine_type
+ ).distinct()
+ if cutoff_time > 0:
+ engine_types_query = engine_types_query.filter(
+ RateLimitAttempt.timestamp >= cutoff_time
+ )
+ engine_types = [row.engine_type for row in engine_types_query.all()]
+
+ for engine_type in engine_types:
+ engine_attempts_list = [
+ a for a in attempts if a.engine_type == engine_type
+ ]
+ engine_attempts = len(engine_attempts_list)
+ engine_success = len(
+ [a for a in engine_attempts_list if a.success]
+ )
+
+ # Get estimate if exists
+ estimate = (
+ session.query(RateLimitEstimate)
+ .filter(RateLimitEstimate.engine_type == engine_type)
+ .first()
+ )
+
+ # Calculate recent success rate
+ recent_success_rate = (
+ (engine_success / engine_attempts * 100)
+ if engine_attempts > 0
+ else 0
+ )
+
+ # Determine status based on success rate
+ if estimate:
+ status = (
+ "healthy"
+ if estimate.success_rate > 0.8
+ else "degraded"
+ if estimate.success_rate > 0.5
+ else "poor"
+ )
+ else:
+ status = (
+ "healthy"
+ if recent_success_rate > 80
+ else "degraded"
+ if recent_success_rate > 50
+ else "poor"
+ )
+
+ engine_stat = {
+ "engine": engine_type,
+ "base_wait": estimate.base_wait_seconds
+ if estimate
+ else 0.0,
+ "base_wait_seconds": round(
+ estimate.base_wait_seconds if estimate else 0.0, 2
+ ),
+ "min_wait_seconds": round(
+ estimate.min_wait_seconds if estimate else 0.0, 2
+ ),
+ "max_wait_seconds": round(
+ estimate.max_wait_seconds if estimate else 0.0, 2
+ ),
+ "success_rate": round(estimate.success_rate * 100, 1)
+ if estimate
+ else recent_success_rate,
+ "total_attempts": estimate.total_attempts
+ if estimate
+ else engine_attempts,
+ "recent_attempts": engine_attempts,
+ "recent_success_rate": round(recent_success_rate, 1),
+ "attempts": engine_attempts,
+ "status": status,
+ }
+
+ if estimate:
+ from datetime import datetime
+
+ engine_stat["last_updated"] = datetime.fromtimestamp(
+ estimate.last_updated
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ else:
+ engine_stat["last_updated"] = "Never"
+
+ engine_stats.append(engine_stat)
+
+ logger.info(
+ f"Tracked engines: {tracked_engines}, engine_stats: {engine_stats}"
+ )
+
+ result = {
+ "rate_limiting": {
"total_attempts": total_attempts,
"successful_attempts": successful_attempts,
"failed_attempts": failed_attempts,
- "success_rate": success_rate,
+ "success_rate": (successful_attempts / total_attempts * 100)
+ if total_attempts > 0
+ else 0,
"rate_limit_events": rate_limit_events,
- "avg_wait_time": round(avg_wait_time, 2),
- "avg_successful_wait": round(avg_successful_wait, 2),
+ "avg_wait_time": round(float(avg_wait_time), 2),
+ "avg_successful_wait": round(float(avg_successful_wait), 2),
+ "tracked_engines": tracked_engines,
"engine_stats": engine_stats,
- "total_engines_tracked": len(estimates),
+ "total_engines_tracked": tracked_engines,
"healthy_engines": len(
- [
- s
- for s in engine_stats.values()
- if s["status"] == "healthy"
- ]
+ [s for s in engine_stats if s["status"] == "healthy"]
),
"degraded_engines": len(
- [
- s
- for s in engine_stats.values()
- if s["status"] == "degraded"
- ]
+ [s for s in engine_stats if s["status"] == "degraded"]
),
"poor_engines": len(
- [
- s
- for s in engine_stats.values()
- if s["status"] == "poor"
- ]
+ [s for s in engine_stats if s["status"] == "poor"]
),
}
}
+ logger.info(
+ f"DEBUG: Returning rate_limiting_analytics result: {result}"
+ )
+ return result
+
except Exception as e:
logger.exception(f"Error getting rate limiting analytics: {e}")
return {
- "rate_limiting_analytics": {
+ "rate_limiting": {
"total_attempts": 0,
"successful_attempts": 0,
"failed_attempts": 0,
@@ -493,7 +565,8 @@ def get_rate_limiting_analytics(period="30d", username=None):
"rate_limit_events": 0,
"avg_wait_time": 0,
"avg_successful_wait": 0,
- "engine_stats": {},
+ "tracked_engines": 0,
+ "engine_stats": [],
"total_engines_tracked": 0,
"healthy_engines": 0,
"degraded_engines": 0,
@@ -514,6 +587,7 @@ def metrics_dashboard():
@login_required
def api_metrics():
"""Get overall metrics data."""
+ logger.info("DEBUG: api_metrics endpoint called")
try:
# Get username from session
username = flask_session.get("username")
@@ -566,9 +640,14 @@ def api_metrics():
# Get strategy analytics
strategy_data = get_strategy_analytics(period, username)
+ logger.info(f"DEBUG: strategy_data keys: {list(strategy_data.keys())}")
# Get rate limiting analytics
rate_limiting_data = get_rate_limiting_analytics(period, username)
+ logger.info(f"DEBUG: rate_limiting_data: {rate_limiting_data}")
+ logger.info(
+ f"DEBUG: rate_limiting_data keys: {list(rate_limiting_data.keys())}"
+ )
# Combine metrics
combined_metrics = {
@@ -579,6 +658,13 @@ def api_metrics():
"user_satisfaction": user_satisfaction,
}
+ logger.info(
+ f"DEBUG: combined_metrics keys: {list(combined_metrics.keys())}"
+ )
+ logger.info(
+ f"DEBUG: combined_metrics['rate_limiting']: {combined_metrics.get('rate_limiting', 'NOT FOUND')}"
+ )
+
return jsonify(
{
"status": "success",
@@ -604,6 +690,7 @@ def api_metrics():
@login_required
def api_rate_limiting_metrics():
"""Get detailed rate limiting metrics."""
+ logger.info("DEBUG: api_rate_limiting_metrics endpoint called")
try:
username = flask_session.get("username")
period = request.args.get("period", "30d")
@@ -677,7 +764,7 @@ def api_current_rate_limits():
), 500
-@metrics_bp.route("/api/metrics/research/<int:research_id>")
+@metrics_bp.route("/api/metrics/research/<string:research_id>")
@login_required
def api_research_metrics(research_id):
"""Get metrics for a specific research."""
@@ -698,7 +785,7 @@ def api_research_metrics(research_id):
)
-@metrics_bp.route("/api/metrics/research/<int:research_id>/timeline")
+@metrics_bp.route("/api/metrics/research/<string:research_id>/timeline")
@login_required
def api_research_timeline_metrics(research_id):
"""Get timeline metrics for a specific research."""
@@ -721,7 +808,7 @@ def api_research_timeline_metrics(research_id):
)
-@metrics_bp.route("/api/metrics/research/<int:research_id>/search")
+@metrics_bp.route("/api/metrics/research/<string:research_id>/search")
@login_required
def api_research_search_metrics(research_id):
"""Get search metrics for a specific research."""
@@ -1249,7 +1336,7 @@ def api_cost_calculation():
return jsonify({"error": "An internal error occurred"}), 500
-@metrics_bp.route("/api/research-costs/<int:research_id>")
+@metrics_bp.route("/api/research-costs/<string:research_id>")
@login_required
def api_research_costs(research_id):
"""Get cost analysis for a specific research session."""
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index d005891406..426f45ebf7 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -236,15 +236,20 @@ def start_research():
# Get complete settings snapshot for this research
try:
- from ...settings import CachedSettingsManager
+ 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")
- settings_manager = CachedSettingsManager(g.db_session, username)
- # Get all current settings as a snapshot
- all_settings = settings_manager.get_all_settings()
+ # 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
@@ -274,10 +279,10 @@ def start_research():
temp_session = get_thread_session(username, password)
if temp_session:
username = session.get("username")
- settings_manager = CachedSettingsManager(
- temp_session, username
+ settings_manager = SettingsManager(temp_session)
+ all_settings = settings_manager.get_all_settings(
+ bypass_cache=True
)
- all_settings = settings_manager.get_all_settings()
research_meta["settings_snapshot"] = all_settings
logger.info(
f"Captured {len(all_settings)} settings using temporary session for research {research_id}"
diff --git a/src/local_deep_research/web/routes/research_routes_orm.py b/src/local_deep_research/web/routes/research_routes_orm.py
index b89e17335a..8f89e4cc1d 100644
--- a/src/local_deep_research/web/routes/research_routes_orm.py
+++ b/src/local_deep_research/web/routes/research_routes_orm.py
@@ -168,7 +168,7 @@ def start_research():
return jsonify({"status": "success", "research_id": research_id})
-@research_bp.route("/api/terminate/<int:research_id>", methods=["POST"])
+@research_bp.route("/api/terminate/<string:research_id>", methods=["POST"])
@login_required
def terminate_research(research_id):
"""Terminate research using ORM."""
@@ -249,7 +249,7 @@ def terminate_research(research_id):
db_session.close()
-@research_bp.route("/api/delete/<int:research_id>", methods=["DELETE"])
+@research_bp.route("/api/delete/<string:research_id>", methods=["DELETE"])
@login_required
def delete_research(research_id):
"""Delete research using ORM."""
@@ -403,7 +403,7 @@ def api_get_history():
db_session.close()
-@research_bp.route("/api/research/<int:research_id>")
+@research_bp.route("/api/research/<string:research_id>")
@login_required
def api_get_research(research_id):
"""Get research details using ORM."""
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 6e591ade53..afee795bb4 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -21,11 +21,11 @@ from ...config.paths import get_data_directory, get_database_path
from ...database.models import Setting, SettingType
from ...database.session_context import get_user_db_session
from ...utilities.db_utils import (
- get_db_setting,
+ get_setting_from_db_main_thread,
)
from ...utilities.url_utils import normalize_url
from ..auth.decorators import login_required
-from ...settings import CachedSettingsManager
+from ...settings import SettingsManager
from ..services.settings_service import (
create_or_update_setting,
set_setting,
@@ -42,13 +42,17 @@ def calculate_warnings():
try:
# Get current settings
- provider = get_db_setting("llm.provider", "ollama").lower()
- local_context = get_db_setting("llm.local_context_window_size", 4096)
+ provider = get_setting_from_db_main_thread(
+ "llm.provider", "ollama"
+ ).lower()
+ local_context = get_setting_from_db_main_thread(
+ "llm.local_context_window_size", 4096
+ )
logger.debug(f"Starting warning calculation - provider={provider}")
# Get dismissal settings
- dismiss_high_context = get_db_setting(
+ dismiss_high_context = get_setting_from_db_main_thread(
"app.warnings.dismiss_high_context", False
)
@@ -77,7 +81,7 @@ def calculate_warnings():
)
# Get additional warning settings
- dismiss_model_mismatch = get_db_setting(
+ dismiss_model_mismatch = get_setting_from_db_main_thread(
"app.warnings.dismiss_model_mismatch", False
)
@@ -85,7 +89,7 @@ def calculate_warnings():
# For now, we'll implement basic warnings that don't require form state
# Model mismatch warning (simplified - checking setting instead of form value)
- current_model = get_db_setting("llm.model", "")
+ current_model = get_setting_from_db_main_thread("llm.model", "")
if (
current_model
and "70b" in current_model.lower()
@@ -287,7 +291,7 @@ def save_all_settings():
if is_valid:
# Save the setting using the same session
- success = set_setting(key, value)
+ success = set_setting(key, value, db_session=db_session)
if success:
updated_settings.append(key)
@@ -329,7 +333,9 @@ def save_all_settings():
new_setting["ui_element"] = "textarea"
# Create the setting
- db_setting = create_or_update_setting(new_setting)
+ db_setting = create_or_update_setting(
+ new_setting, db_session=db_session
+ )
if db_setting:
created_settings.append(key)
@@ -476,7 +482,7 @@ def reset_to_defaults():
# Create settings manager with proper session context
username = session.get("username")
with get_user_db_session(username) as db_session:
- settings_mgr = CachedSettingsManager(db_session, username)
+ settings_mgr = SettingsManager(db_session)
# Import settings from default files
settings_mgr.load_from_defaults_file()
@@ -503,6 +509,86 @@ def reset_to_defaults():
)
+@settings_bp.route("/save_settings", methods=["POST"])
+@login_required
+def save_settings():
+ """Save all settings from the form using POST method - fallback when JavaScript is disabled"""
+ try:
+ username = session.get("username")
+
+ # Get form data
+ form_data = request.form.to_dict()
+
+ # Remove CSRF token from the data
+ form_data.pop("csrf_token", None)
+
+ with get_user_db_session(username) as db_session:
+ settings_manager = SettingsManager(db_session)
+
+ updated_count = 0
+ failed_count = 0
+
+ # Process each setting
+ for key, value in form_data.items():
+ try:
+ # Handle checkbox values
+ if value == "on":
+ value = True
+ elif value == "off" or value == "":
+ value = False
+
+ # Try to convert numeric values
+ if (
+ isinstance(value, str)
+ and value.replace(".", "").replace("-", "").isdigit()
+ ):
+ try:
+ if "." in value:
+ value = float(value)
+ else:
+ value = int(value)
+ except ValueError:
+ pass # Keep as string
+
+ # Save the setting
+ if settings_manager.set_setting(key, value, commit=False):
+ updated_count += 1
+ else:
+ failed_count += 1
+ logger.warning(f"Failed to save setting {key}")
+
+ except Exception as e:
+ logger.error(f"Error saving setting {key}: {e}")
+ failed_count += 1
+
+ # Commit all changes at once
+ try:
+ db_session.commit()
+ settings_manager.clear_cache()
+
+ flash(
+ f"Settings saved successfully! Updated {updated_count} settings.",
+ "success",
+ )
+ if failed_count > 0:
+ flash(
+ f"Warning: {failed_count} settings failed to save.",
+ "warning",
+ )
+
+ except Exception as e:
+ db_session.rollback()
+ logger.error(f"Failed to commit settings: {e}")
+ flash("Error saving settings. Please try again.", "error")
+
+ return redirect(url_for("settings.settings_page"))
+
+ except Exception:
+ logger.exception("Error in save_settings")
+ flash("An internal error occurred while saving settings.", "error")
+ return redirect(url_for("settings.settings_page"))
+
+
# API Routes
@settings_bp.route("/api", methods=["GET"])
@login_required
@@ -516,7 +602,7 @@ def api_get_all_settings():
with get_user_db_session(username) as db_session:
# Create settings manager with the session from context
# This ensures thread safety
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
# Get settings
settings = settings_manager.get_all_settings()
@@ -550,13 +636,8 @@ def api_get_db_setting(key):
try:
username = session.get("username")
- # Get setting
- value = get_db_setting(key)
- if value is None:
- return jsonify({"error": f"Setting not found: {key}"}), 404
-
with get_user_db_session(username) as db_session:
- # Get additional metadata from database using the same session
+ # Get setting from database using the same session
db_setting = (
db_session.query(Setting).filter(Setting.key == key).first()
)
@@ -578,11 +659,10 @@ def api_get_db_setting(key):
"visible": db_setting.visible,
"editable": db_setting.editable,
}
+ return jsonify(setting_data)
else:
- # Return minimal info
- setting_data = {"key": key, "value": value}
-
- return jsonify({"settings": setting_data})
+ # Setting not found
+ return jsonify({"error": f"Setting not found: {key}"}), 404
except Exception:
logger.exception(f"Error getting setting {key}")
return jsonify({"error": "Failed to retrieve settings"}), 500
@@ -621,8 +701,8 @@ def api_update_setting(key):
), 403
# Update setting
- # Note: set_setting will get its own session via get_settings_manager
- success = set_setting(key, value)
+ # Pass the db_session to avoid session lookup issues
+ success = set_setting(key, value, db_session=db_session)
if success:
response_data = {
"message": f"Setting {key} updated successfully"
@@ -678,7 +758,9 @@ def api_update_setting(key):
setting_dict[field] = data[field]
# Create setting
- db_setting = create_or_update_setting(setting_dict)
+ db_setting = create_or_update_setting(
+ setting_dict, db_session=db_session
+ )
if db_setting:
return (
@@ -713,7 +795,7 @@ def api_delete_setting(key):
with get_user_db_session(username) as db_session:
# Create settings manager with the session from context
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
# Check if setting exists
db_setting = (
@@ -744,7 +826,7 @@ def api_import_settings():
try:
username = session.get("username")
with get_user_db_session(username) as db_session:
- settings_manager = CachedSettingsManager(db_session, username)
+ settings_manager = SettingsManager(db_session)
success = settings_manager.load_from_defaults_file()
if success:
@@ -904,7 +986,7 @@ def api_get_available_models():
try:
logger.info("Attempting to connect to Ollama API")
- raw_base_url = get_db_setting(
+ raw_base_url = get_setting_from_db_main_thread(
"llm.ollama.url", "http://localhost:11434"
)
base_url = (
@@ -1070,8 +1152,12 @@ def api_get_available_models():
)
# Get the endpoint URL and API key from settings
- endpoint_url = get_db_setting("llm.openai_endpoint.url", "")
- api_key = get_db_setting("llm.openai_endpoint.api_key", "")
+ endpoint_url = get_setting_from_db_main_thread(
+ "llm.openai_endpoint.url", ""
+ )
+ api_key = get_setting_from_db_main_thread(
+ "llm.openai_endpoint.api_key", ""
+ )
if endpoint_url and api_key:
# Import OpenAI package here to avoid dependency issues if not installed
@@ -1183,7 +1269,7 @@ def api_get_available_models():
)
# Get the API key from settings
- api_key = get_db_setting("llm.openai.api_key", "")
+ api_key = get_setting_from_db_main_thread("llm.openai.api_key", "")
if api_key:
# Import OpenAI package here to avoid dependency issues if not installed
@@ -1250,7 +1336,9 @@ def api_get_available_models():
)
# Get the API key from settings
- api_key = get_db_setting("llm.anthropic.api_key", "")
+ api_key = get_setting_from_db_main_thread(
+ "llm.anthropic.api_key", ""
+ )
if api_key:
# Import Anthropic package here to avoid dependency issues if not installed
@@ -1369,15 +1457,13 @@ def api_get_available_search_engines():
from ...web_search_engines.search_engines_config import search_config
username = session.get("username")
- config = search_config(username=username)
+ search_engines = search_config(username=username)
# Extract search engines from config
engines_dict = {}
engine_options = []
- if config and "search_engines" in config:
- search_engines = config["search_engines"]
-
+ if search_engines:
# Format engines for API response
for engine_id, engine_data in search_engines.items():
engines_dict[engine_id] = {
@@ -1393,26 +1479,9 @@ def api_get_available_search_engines():
}
)
- # If no engines found, provide defaults from available engines
+ # If no engines found, log the issue but return empty list
if not engine_options:
- # Get default engines from the search config
- default_engines = {
- "searxng": "SearXNG (Local)",
- "ddg": "DuckDuckGo",
- "google": "Google",
- "bing": "Bing",
- "serper": "Serper API",
- }
-
- for engine_id, display_name in default_engines.items():
- engines_dict[engine_id] = {
- "display_name": display_name,
- "description": f"{display_name} search engine",
- "strengths": [],
- }
- engine_options.append(
- {"value": engine_id, "label": display_name}
- )
+ logger.warning("No search engines found in configuration")
return jsonify(
{"engines": engines_dict, "engine_options": engine_options}
@@ -1845,7 +1914,7 @@ def check_ollama_status():
"""Check if Ollama is running and available"""
try:
# Get Ollama URL from settings
- raw_base_url = get_db_setting(
+ raw_base_url = get_setting_from_db_main_thread(
"llm.ollama.url", "http://localhost:11434"
)
base_url = (
@@ -1997,7 +2066,7 @@ def get_bulk_settings():
result = {}
for key in requested:
try:
- value = get_db_setting(key)
+ value = get_setting_from_db_main_thread(key)
result[key] = {"value": value, "exists": value is not None}
except Exception as e:
logger.warning(f"Error getting setting {key}: {e}")
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 639d69fbc0..5015bcdc59 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -30,9 +30,9 @@ OUTPUT_DIR = get_research_outputs_directory()
def get_citation_formatter():
"""Get citation formatter with settings from thread context."""
# Import here to avoid circular imports
- from ...config.search_config import get_db_setting
+ from ...config.search_config import get_setting_from_snapshot
- citation_format = get_db_setting(
+ citation_format = get_setting_from_snapshot(
"report.citation_format", "domain_id_hyperlinks"
)
mode_map = {
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index 8193ae813b..0d6ce04f58 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -6,7 +6,9 @@ from ...database.models import Setting
from ...utilities.db_utils import get_settings_manager
-def set_setting(key: str, value: Any, commit: bool = True) -> bool:
+def set_setting(
+ key: str, value: Any, commit: bool = True, db_session=None
+) -> bool:
"""
Set a setting value
@@ -14,11 +16,12 @@ def set_setting(key: str, value: Any, commit: bool = True) -> bool:
key: Setting key
value: Setting value
commit: Whether to commit the change
+ db_session: Optional database session
Returns:
bool: True if successful
"""
- manager = get_settings_manager()
+ manager = get_settings_manager(db_session)
return manager.set_setting(key, value, commit)
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index 56281db76c..7c161606da 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -28,7 +28,11 @@
// Get research ID from URL
function getResearchIdFromUrl() {
- return URLBuilder.extractResearchIdFromPattern('details');
+ const id = URLBuilder.extractResearchIdFromPattern('details');
+ console.log('getResearchIdFromUrl called, extracted ID:', id);
+ console.log('Current URL:', window.location.href);
+ console.log('Current pathname:', window.location.pathname);
+ return id;
}
// Load research metrics data
@@ -43,13 +47,32 @@
// Load research details (includes strategy)
console.log('Fetching research details...');
- const detailsResponse = await fetch(URLBuilder.historyDetails(researchId));
+ console.log('Using research ID:', researchId);
+ const detailsUrl = URLBuilder.historyDetails(researchId);
+ console.log('Details URL:', detailsUrl);
+ console.log('Full URL being fetched:', window.location.origin + detailsUrl);
+ const detailsResponse = await fetch(detailsUrl);
console.log('Details response status:', detailsResponse.status);
+ console.log('Details response URL:', detailsResponse.url);
let researchDetails = null;
if (detailsResponse.ok) {
researchDetails = await detailsResponse.json();
console.log('Research details loaded:', researchDetails);
+ } else {
+ console.error('Failed to load research details:', detailsResponse.status);
+ const errorText = await detailsResponse.text();
+ console.error('Error response:', errorText);
+ try {
+ const errorJson = JSON.parse(errorText);
+ console.error('Error JSON:', errorJson);
+ if (errorJson.message) {
+ throw new Error(errorJson.message);
+ }
+ } catch (e) {
+ // Not JSON, use original text
+ }
+ throw new Error(`Failed to load research details: ${detailsResponse.status}`);
}
// Load research metrics
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index 01723f93c0..10776f1697 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -805,7 +805,7 @@
<div class="metric-value" id="total-examples">50</div>
<div class="metric-label">Total Examples</div>
<div style="margin-top: 10px; font-size: 0.9rem; color: var(--text-muted);">
- Estimated time: <span id="estimated-time">40-60 minutes</span>
+ Estimated time: <span id="estimated-time-preview">40-60 minutes</span>
</div>
</div>
</div>
@@ -1071,7 +1071,7 @@ function updateConfigSummary() {
const estimatedTime = estimatedMinutes < 60 ?
`${estimatedMinutes} minutes` :
`${Math.round(estimatedMinutes/60)} hour${estimatedMinutes >= 120 ? 's' : ''}`;
- document.getElementById('estimated-time').textContent = estimatedTime;
+ document.getElementById('estimated-time-preview').textContent = estimatedTime;
}
function validateConfiguration() {
@@ -1295,6 +1295,11 @@ function updateProgressDisplay(status) {
}
// Time estimates
+ console.log('Time estimation debug:', {
+ estimatedTime: estimatedTime,
+ estimated_time_remaining: status.estimated_time_remaining,
+ status: status
+ });
if (estimatedTime && status.estimated_time_remaining) {
const minutes = Math.round(status.estimated_time_remaining / 60);
estimatedTime.textContent = minutes > 0 ? `${minutes}m` : '<1m';
@@ -1493,57 +1498,57 @@ async function loadCurrentSettings() {
const modelEl = document.getElementById('current-model');
// Set provider
- if (llmProviderData && llmProviderData.settings && llmProviderData.settings.value) {
- const provider = llmProviderData.settings.value;
- if (providerEl) providerEl.textContent = provider ? provider.toUpperCase() : 'Not set';
+ if (llmProviderData && llmProviderData.value) {
+ const provider = llmProviderData.value;
+ if (providerEl) providerEl.textContent = provider ? provider.toUpperCase() : 'ERROR: No value';
} else {
- if (providerEl) providerEl.textContent = 'Not set';
+ if (providerEl) providerEl.textContent = 'ERROR: Failed to load';
}
// Set model
- if (llmModelData && llmModelData.settings && llmModelData.settings.value) {
- const model = llmModelData.settings.value;
- if (modelEl) modelEl.textContent = model || 'Not set';
+ if (llmModelData && llmModelData.value) {
+ const model = llmModelData.value;
+ if (modelEl) modelEl.textContent = model || 'ERROR: No value';
} else {
- if (modelEl) modelEl.textContent = 'Not set';
+ if (modelEl) modelEl.textContent = 'ERROR: Failed to load';
}
} catch (e) {
console.error('Error setting LLM display:', e);
}
// Display search tool and check for warnings
- if (searchToolData && searchToolData.settings && searchToolData.settings.value) {
- const searchTool = searchToolData.settings.value || 'Not set';
+ if (searchToolData && searchToolData.value) {
+ const searchTool = searchToolData.value || 'ERROR: No value';
document.getElementById('current-search-tool').textContent = searchTool;
// Check for search engine warnings
checkSearchEngineWarnings(searchTool);
} else {
- document.getElementById('current-search-tool').textContent = 'Not set';
+ document.getElementById('current-search-tool').textContent = 'ERROR: Failed to load';
}
// Display search iterations
- if (iterationsData && iterationsData.settings && iterationsData.settings.value !== null) {
+ if (iterationsData && iterationsData.value !== null) {
document.getElementById('current-iterations').textContent =
- iterationsData.settings.value || '8';
+ iterationsData.value || 'ERROR';
} else {
- document.getElementById('current-iterations').textContent = '8'; // default
+ document.getElementById('current-iterations').textContent = 'ERROR: Failed to load';
}
// Display questions per iteration
- if (questionsData && questionsData.settings && questionsData.settings.value !== null) {
+ if (questionsData && questionsData.value !== null) {
document.getElementById('current-questions').textContent =
- questionsData.settings.value || '5';
+ questionsData.value || 'ERROR';
} else {
- document.getElementById('current-questions').textContent = '5'; // default
+ document.getElementById('current-questions').textContent = 'ERROR: Failed to load';
}
// Display search strategy
- if (strategyData && strategyData.settings && strategyData.settings.value) {
+ if (strategyData && strategyData.value) {
document.getElementById('current-strategy').textContent =
- strategyData.settings.value || 'focused_iteration';
+ strategyData.value || 'ERROR: No value';
} else {
- document.getElementById('current-strategy').textContent = 'focused_iteration'; // default
+ document.getElementById('current-strategy').textContent = 'ERROR: Failed to load';
}
// Display evaluation settings (commented out as these elements don't exist)
@@ -1725,6 +1730,8 @@ function toggleText(id) {
// Chart initialization and management
function initializeCharts() {
+ console.log('Initializing charts...');
+
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
@@ -1810,7 +1817,7 @@ function initializeCharts() {
data: {
labels: [],
datasets: [{
- label: 'Processing Time (seconds)',
+ label: 'Processing Time (minutes)',
data: [],
borderColor: '#e91e63',
backgroundColor: 'rgba(233, 30, 99, 0.1)',
@@ -1828,7 +1835,7 @@ function initializeCharts() {
ticks: {
...chartOptions.scales.y.ticks,
callback: function(value) {
- return value + 's';
+ return value.toFixed(1) + 'm';
}
}
}
@@ -1870,28 +1877,41 @@ function initializeCharts() {
});
}
+
function updateCharts(status) {
if (!accuracyChart || !timingChart || !searchResultsChart || !status) return;
const currentExample = status.completed_examples;
if (currentExample <= 0) return;
+ console.log('updateCharts called with status:', status);
+ console.log('Accuracy values - overall:', status.overall_accuracy, 'running:', status.running_accuracy,
+ 'simpleqa:', status.simpleqa_accuracy, 'browsecomp:', status.browsecomp_accuracy);
+ console.log('Timing value - avg_time_per_example:', status.avg_time_per_example);
+
// Update accuracy chart
- if (status.overall_accuracy !== undefined) {
+ if (status.overall_accuracy !== undefined || status.running_accuracy !== undefined ||
+ status.simpleqa_accuracy !== undefined || status.browsecomp_accuracy !== undefined) {
// Add new data point
const labels = accuracyChart.data.labels;
+ const overallAcc = status.overall_accuracy !== null && status.overall_accuracy !== undefined ?
+ status.overall_accuracy :
+ (status.running_accuracy !== null && status.running_accuracy !== undefined ? status.running_accuracy : 0);
+ const simpleqaAcc = status.simpleqa_accuracy !== null && status.simpleqa_accuracy !== undefined ? status.simpleqa_accuracy : 0;
+ const browsecompAcc = status.browsecomp_accuracy !== null && status.browsecomp_accuracy !== undefined ? status.browsecomp_accuracy : 0;
+
if (!labels.includes(currentExample)) {
labels.push(currentExample);
- accuracyChart.data.datasets[0].data.push(status.overall_accuracy || 0);
- accuracyChart.data.datasets[1].data.push(status.simpleqa_accuracy || 0);
- accuracyChart.data.datasets[2].data.push(status.browsecomp_accuracy || 0);
+ accuracyChart.data.datasets[0].data.push(overallAcc);
+ accuracyChart.data.datasets[1].data.push(simpleqaAcc);
+ accuracyChart.data.datasets[2].data.push(browsecompAcc);
} else {
// Update existing data point
const index = labels.indexOf(currentExample);
if (index >= 0) {
- accuracyChart.data.datasets[0].data[index] = status.overall_accuracy || 0;
- accuracyChart.data.datasets[1].data[index] = status.simpleqa_accuracy || 0;
- accuracyChart.data.datasets[2].data[index] = status.browsecomp_accuracy || 0;
+ accuracyChart.data.datasets[0].data[index] = overallAcc;
+ accuracyChart.data.datasets[1].data[index] = simpleqaAcc;
+ accuracyChart.data.datasets[2].data[index] = browsecompAcc;
}
}
@@ -1904,17 +1924,18 @@ function updateCharts(status) {
accuracyChart.update('none');
}
- // Update timing chart
+ // Update timing chart (convert seconds to minutes)
if (status.avg_time_per_example !== undefined) {
const timingLabels = timingChart.data.labels;
+ const avgTimeMinutes = (status.avg_time_per_example / 60) || 0; // Convert to minutes
if (!timingLabels.includes(currentExample)) {
timingLabels.push(currentExample);
- timingChart.data.datasets[0].data.push(status.avg_time_per_example || 0);
+ timingChart.data.datasets[0].data.push(avgTimeMinutes);
} else {
// Update existing data point
const index = timingLabels.indexOf(currentExample);
if (index >= 0) {
- timingChart.data.datasets[0].data[index] = status.avg_time_per_example || 0;
+ timingChart.data.datasets[0].data[index] = avgTimeMinutes;
}
}
diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.html
index 294d7cf7eb..f0e3778acd 100644
--- a/src/local_deep_research/web/templates/pages/metrics.html
+++ b/src/local_deep_research/web/templates/pages/metrics.html
@@ -1766,7 +1766,7 @@
// Display rate limiting data in the dashboard
function displayRateLimitingData(rateLimitData) {
- if (!rateLimitData || !rateLimitData.rate_limiting_analytics) {
+ if (!rateLimitData || !rateLimitData.rate_limiting) {
// No rate limiting data available, show zeros
document.getElementById('rate-limit-success-rate').textContent = '0%';
document.getElementById('rate-limit-events').textContent = '0';
@@ -1779,7 +1779,7 @@
return;
}
- const analytics = rateLimitData.rate_limiting_analytics;
+ const analytics = rateLimitData.rate_limiting;
// Update overview cards
document.getElementById('rate-limit-success-rate').textContent = `${analytics.success_rate}%`;
@@ -1827,11 +1827,11 @@
</div>
<div>
<div style="color: var(--text-secondary);">Last Updated:</div>
- <div style="font-weight: 600;">${formatTime(stats.last_updated)}</div>
+ <div style="font-weight: 600;">${stats.last_updated === 'Never' ? 'No rate limits yet' : formatTime(stats.last_updated)}</div>
</div>
</div>
<div style="margin-top: 0.75rem; font-size: 0.75rem; color: var(--text-secondary);">
- Range: ${stats.min_wait_seconds}s - ${stats.max_wait_seconds}s
+ ${stats.base_wait_seconds === 0 ? 'No rate limit estimates yet' : `Range: ${stats.min_wait_seconds}s - ${stats.max_wait_seconds}s`}
</div>
`;
@@ -1854,6 +1854,9 @@
// Format time for display
function formatTime(timeString) {
try {
+ if (timeString === 'Never' || !timeString) {
+ return 'No rate limits yet';
+ }
const date = new Date(timeString);
const now = new Date();
const diffHours = (now - date) / (1000 * 60 * 60);
@@ -1866,7 +1869,7 @@
return `${Math.floor(diffHours / 24)}d ago`;
}
} catch {
- return timeString;
+ return 'No rate limits yet';
}
}
diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.html
index 6c9881b482..89dae531d3 100644
--- a/src/local_deep_research/web/templates/settings_dashboard.html
+++ b/src/local_deep_research/web/templates/settings_dashboard.html
@@ -56,7 +56,9 @@
<div class="settings-tab" data-tab="app">Application</div>
</div>
- <form id="settings-form" class="settings-form">
+ <form id="settings-form" class="settings-form" method="POST" action="{{ url_for('settings.save_settings') }}">
+ <!-- JavaScript intercepts and uses save_all_settings endpoint, form action is fallback -->
+ <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div id="settings-content">
<div class="loading-spinner centered">
<div class="spinner"></div>
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index aed335b846..d2c0066c53 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -2,11 +2,10 @@ from typing import Any, Dict, List, Optional
from loguru import logger
-from ...utilities.db_utils import get_db_setting
+from ...config.search_config import get_setting_from_snapshot
from ...web.services.socket_service import SocketIOService
from ..search_engine_base import BaseSearchEngine
from ..search_engine_factory import create_search_engine
-from ..search_engines_config import search_config
from .search_engine_wikipedia import WikipediaSearchEngine
@@ -24,6 +23,7 @@ class MetaSearchEngine(BaseSearchEngine):
max_engines_to_try: int = 3,
max_filtered_results: Optional[int] = None,
engine_selection_callback=None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
**kwargs,
):
"""
@@ -35,6 +35,7 @@ class MetaSearchEngine(BaseSearchEngine):
use_api_key_services: Whether to include services that require API keys
max_engines_to_try: Maximum number of engines to try before giving up
max_filtered_results: Maximum number of results to keep after filtering
+ settings_snapshot: Settings snapshot for thread context
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with the LLM, max_filtered_results, and max_results
@@ -46,6 +47,7 @@ class MetaSearchEngine(BaseSearchEngine):
self.use_api_key_services = use_api_key_services
self.max_engines_to_try = max_engines_to_try
+ self.settings_snapshot = settings_snapshot
# Cache for engine instances
self.engine_cache = {}
@@ -63,12 +65,53 @@ class MetaSearchEngine(BaseSearchEngine):
max_filtered_results=max_filtered_results,
)
+ def _get_search_config(self) -> Dict[str, Any]:
+ """Get search config from settings_snapshot or fallback to self._get_search_config()"""
+ if self.settings_snapshot:
+ # Extract search engine configs from settings snapshot
+ config_data = {}
+ for key, value in self.settings_snapshot.items():
+ if key.startswith("search.engine.web."):
+ parts = key.split(".")
+ if len(parts) >= 4:
+ engine_name = parts[3]
+ if engine_name not in config_data:
+ config_data[engine_name] = {}
+ remaining_key = (
+ ".".join(parts[4:]) if len(parts) > 4 else ""
+ )
+ if remaining_key:
+ config_data[engine_name][remaining_key] = (
+ value.get("value")
+ if isinstance(value, dict)
+ else value
+ )
+
+ # Also check for auto engine
+ if "search.engine.auto.class_name" in self.settings_snapshot:
+ config_data["auto"] = {}
+ for key, value in self.settings_snapshot.items():
+ if key.startswith("search.engine.auto."):
+ remaining_key = key.replace("search.engine.auto.", "")
+ config_data["auto"][remaining_key] = (
+ value.get("value")
+ if isinstance(value, dict)
+ else value
+ )
+ return config_data
+ else:
+ # Fallback to search_config if no snapshot
+ return self._get_search_config()
+
def _get_available_engines(self) -> List[str]:
"""Get list of available engines, excluding 'meta' and 'auto', based on user settings"""
# Filter out 'meta' and 'auto' and check API key availability
available = []
- for name, config_ in search_config().items():
+ # Get search config using helper method
+ config_data = self._get_self._get_search_config()
+
+ for name, config_ in config_data.items():
if name in ["meta", "auto"]:
continue
@@ -89,7 +132,11 @@ class MetaSearchEngine(BaseSearchEngine):
)
# Get setting from database, default to False if not found
- use_in_auto_search = get_db_setting(auto_search_setting, False)
+ use_in_auto_search = get_setting_from_snapshot(
+ auto_search_setting,
+ False,
+ settings_snapshot=self.settings_snapshot,
+ )
# Skip engines that aren't enabled for auto search
if not use_in_auto_search:
@@ -180,7 +227,7 @@ class MetaSearchEngine(BaseSearchEngine):
]
reliability_sorted = sorted(
engines_without_searxng,
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -195,7 +242,7 @@ class MetaSearchEngine(BaseSearchEngine):
# Return engines sorted by reliability
return sorted(
self.available_engines,
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -205,16 +252,16 @@ class MetaSearchEngine(BaseSearchEngine):
engines_info = []
for engine_name in self.available_engines:
try:
- if engine_name in search_config():
- strengths = search_config()[engine_name].get(
+ if engine_name in self._get_search_config():
+ strengths = self._get_search_config()[engine_name].get(
"strengths", "General search"
)
- weaknesses = search_config()[engine_name].get(
+ weaknesses = self._get_search_config()[engine_name].get(
"weaknesses", "None specified"
)
- description = search_config()[engine_name].get(
- "description", engine_name
- )
+ description = self._get_search_config()[
+ engine_name
+ ].get("description", engine_name)
engines_info.append(
f"- {engine_name}: {description}\n Strengths: {strengths}\n Weaknesses: {weaknesses}"
)
@@ -228,7 +275,7 @@ class MetaSearchEngine(BaseSearchEngine):
)
return sorted(
self.available_engines,
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -287,7 +334,7 @@ Example output: searxng,wikipedia,brave"""
if not valid_engines:
valid_engines = sorted(
self.available_engines,
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -300,7 +347,7 @@ Example output: searxng,wikipedia,brave"""
if "searxng" in self.available_engines:
return ["searxng"] + sorted(
[e for e in self.available_engines if e != "searxng"],
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -308,7 +355,7 @@ Example output: searxng,wikipedia,brave"""
else:
return sorted(
self.available_engines,
- key=lambda x: search_config()
+ key=lambda x: self._get_search_config()
.get(x, {})
.get("reliability", 0),
reverse=True,
@@ -410,7 +457,11 @@ Example output: searxng,wikipedia,brave"""
List of result dictionaries with full content
"""
# Check if we should get full content
- if get_db_setting("search.snippets_only", True):
+ if get_setting_from_snapshot(
+ "search.snippets_only",
+ True,
+ settings_snapshot=self.settings_snapshot,
+ ):
logger.info("Snippet-only mode, skipping full content retrieval")
return relevant_items
@@ -455,7 +506,11 @@ Example output: searxng,wikipedia,brave"""
self.max_filtered_results
)
- engine = create_search_engine(engine_name, **common_params)
+ engine = create_search_engine(
+ engine_name,
+ settings_snapshot=self.settings_snapshot,
+ **common_params,
+ )
except Exception:
logger.exception(
f"Error creating engine instance for {engine_name}"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 7a65de2512..81d0ec1403 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -25,6 +25,7 @@ class ArXivSearchEngine(BaseSearchEngine):
max_full_text: int = 1,
llm: Optional[BaseLLM] = None,
max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
): # Added this parameter
"""
Initialize the arXiv search engine.
@@ -38,11 +39,12 @@ class ArXivSearchEngine(BaseSearchEngine):
max_full_text: Maximum number of PDFs to download and process (default: 1)
llm: Language model for relevance filtering
max_filtered_results: Maximum number of results to keep after filtering
+ settings_snapshot: Settings snapshot for thread context
"""
# Initialize the journal reputation filter if needed.
content_filters = []
journal_filter = JournalReputationFilter.create_default(
- model=llm, engine_name="arxiv"
+ model=llm, engine_name="arxiv", settings_snapshot=settings_snapshot
)
if journal_filter is not None:
content_filters.append(journal_filter)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
index a45ef5c070..2befc8629e 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
@@ -25,6 +25,7 @@ class BraveSearchEngine(BaseSearchEngine):
llm: Optional[BaseLLM] = None,
include_full_content: bool = True,
max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
**kwargs,
):
"""
@@ -41,6 +42,7 @@ class BraveSearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
include_full_content: Whether to include full webpage content in results
max_filtered_results: Maximum number of results to keep after filtering
+ settings_snapshot: Settings snapshot for thread context
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
@@ -66,11 +68,14 @@ class BraveSearchEngine(BaseSearchEngine):
}
# Get API key - check params, env vars, or database
- from ...utilities.db_utils import get_db_setting
+ from ...config.search_config import get_setting_from_snapshot
brave_api_key = api_key
if not brave_api_key:
- brave_api_key = get_db_setting("search.engine.web.brave.api_key")
+ brave_api_key = get_setting_from_snapshot(
+ "search.engine.web.brave.api_key",
+ settings_snapshot=settings_snapshot,
+ )
if not brave_api_key:
raise ValueError(
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index bc8c5da3ee..dd22aabd38 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -93,17 +93,17 @@ class GooglePSESearchEngine(BaseSearchEngine):
self.region = region
# API key and Search Engine ID - check params, env vars, or database
- from ...utilities.db_utils import get_db_setting
+ from ...utilities.db_utils import get_setting_from_db_main_thread
self.api_key = api_key
if not self.api_key:
- self.api_key = get_db_setting(
+ self.api_key = get_setting_from_db_main_thread(
"search.engine.web.google_pse.api_key"
)
self.search_engine_id = search_engine_id
if not self.search_engine_id:
- self.search_engine_id = get_db_setting(
+ self.search_engine_id = get_setting_from_db_main_thread(
"search.engine.web.google_pse.engine_id"
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
index db7903ed59..1d831b5edf 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
@@ -31,7 +31,7 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
from loguru import logger
from ...config import search_config
-from ...utilities.db_utils import get_db_setting
+from ...utilities.db_utils import get_setting_from_db_main_thread
from ...utilities.url_utils import normalize_url
from ..search_engine_base import BaseSearchEngine
@@ -168,7 +168,7 @@ class LocalEmbeddingManager:
if self.embedding_model_type == "ollama":
# Use Ollama for embeddings
if not self.ollama_base_url:
- raw_ollama_base_url = get_db_setting(
+ raw_ollama_base_url = get_setting_from_db_main_thread(
"llm.ollama.url", "http://localhost:11434"
)
self.ollama_base_url = (
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
index 4626e4a5f3..548de9fad5 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
@@ -25,6 +25,7 @@ class SerpAPISearchEngine(BaseSearchEngine):
llm: Optional[BaseLLM] = None,
include_full_content: bool = False,
max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
**kwargs,
):
"""
@@ -41,6 +42,7 @@ class SerpAPISearchEngine(BaseSearchEngine):
llm: Language model for relevance filtering
include_full_content: Whether to include full webpage content in results
max_filtered_results: Maximum number of results to keep after filtering
+ settings_snapshot: Settings snapshot for thread context
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
@@ -66,12 +68,13 @@ class SerpAPISearchEngine(BaseSearchEngine):
}
# Get API key - check params, env vars, or database
- from ...utilities.db_utils import get_db_setting
+ from ...config.search_config import get_setting_from_snapshot
serpapi_api_key = api_key
if not serpapi_api_key:
- serpapi_api_key = get_db_setting(
- "search.engine.web.serpapi.api_key"
+ serpapi_api_key = get_setting_from_snapshot(
+ "search.engine.web.serpapi.api_key",
+ settings_snapshot=settings_snapshot,
)
if not serpapi_api_key:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
index 4a7d1cf717..6f4a9b2d06 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
@@ -29,6 +29,7 @@ class TavilySearchEngine(BaseSearchEngine):
search_depth: str = "basic",
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
**kwargs,
):
"""
@@ -47,6 +48,7 @@ class TavilySearchEngine(BaseSearchEngine):
search_depth: "basic" or "advanced" - controls search quality vs speed
include_domains: List of domains to include in search
exclude_domains: List of domains to exclude from search
+ settings_snapshot: Settings snapshot for thread context
**kwargs: Additional parameters (ignored but accepted for compatibility)
"""
# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
@@ -61,11 +63,14 @@ class TavilySearchEngine(BaseSearchEngine):
self.exclude_domains = exclude_domains or []
# Get API key - check params, database, or env vars
- from ...utilities.db_utils import get_db_setting
+ from ...config.search_config import get_setting_from_snapshot
tavily_api_key = api_key
if not tavily_api_key:
- tavily_api_key = get_db_setting("search.engine.web.tavily.api_key")
+ tavily_api_key = get_setting_from_snapshot(
+ "search.engine.web.tavily.api_key",
+ settings_snapshot=settings_snapshot,
+ )
if not tavily_api_key:
tavily_api_key = os.environ.get("TAVILY_API_KEY")
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
index 3973d56c8c..2a54122e30 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
@@ -16,7 +16,7 @@ from tenacity.wait import wait_base
from ..tracker import get_tracker
from ..exceptions import RateLimitError
from .detection import is_llm_rate_limit_error, extract_retry_after
-from ....utilities.db_utils import get_db_setting
+from ....utilities.db_utils import get_setting_from_db_main_thread
class AdaptiveLLMWait(wait_base):
@@ -77,7 +77,9 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
def _should_rate_limit(self) -> bool:
"""Check if rate limiting should be applied to this LLM."""
# Check LLM-specific switch (disabled by default, independent of search rate limiting)
- if not get_db_setting("rate_limiting.llm_enabled", False):
+ if not get_setting_from_db_main_thread(
+ "rate_limiting.llm_enabled", False
+ ):
return False
# Don't rate limit local models
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 5078e6fec5..e7ecbd8ea0 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -11,7 +11,10 @@ from typing import Dict, List, Optional, Tuple
from loguru import logger
from ...database.models import RateLimitAttempt, RateLimitEstimate
-from ...utilities.db_utils import get_db_session, get_db_setting
+from ...utilities.db_utils import (
+ get_db_session,
+ get_setting_from_db_main_thread,
+)
from ...config.thread_settings import get_settings_context
@@ -51,19 +54,31 @@ class AdaptiveRateLimitTracker:
else:
# Fall back to database settings if not in thread
self.memory_window = int(
- get_db_setting("rate_limiting.memory_window", 100)
+ get_setting_from_db_main_thread(
+ "rate_limiting.memory_window", 100
+ )
)
self.exploration_rate = float(
- get_db_setting("rate_limiting.exploration_rate", 0.1)
+ get_setting_from_db_main_thread(
+ "rate_limiting.exploration_rate", 0.1
+ )
)
self.learning_rate = float(
- get_db_setting("rate_limiting.learning_rate", 0.3)
+ get_setting_from_db_main_thread(
+ "rate_limiting.learning_rate", 0.3
+ )
)
self.decay_per_day = float(
- get_db_setting("rate_limiting.decay_per_day", 0.95)
+ get_setting_from_db_main_thread(
+ "rate_limiting.decay_per_day", 0.95
+ )
+ )
+ self.enabled = bool(
+ get_setting_from_db_main_thread("rate_limiting.enabled", True)
+ )
+ profile = get_setting_from_db_main_thread(
+ "rate_limiting.profile", "balanced"
)
- self.enabled = bool(get_db_setting("rate_limiting.enabled", True))
- profile = get_db_setting("rate_limiting.profile", "balanced")
# Apply rate limiting profile
self._apply_profile(profile)
@@ -112,30 +127,62 @@ class AdaptiveRateLimitTracker:
)
return
- try:
- session = get_db_session()
- if session:
- estimates = session.query(RateLimitEstimate).all()
-
- for estimate in estimates:
- # Apply decay for old estimates
- age_hours = (time.time() - estimate.last_updated) / 3600
- decay = self.decay_per_day ** (age_hours / 24)
-
- self.current_estimates[estimate.engine_type] = {
- "base": estimate.base_wait_seconds,
- "min": estimate.min_wait_seconds,
- "max": estimate.max_wait_seconds,
- "confidence": decay,
- }
-
- logger.debug(
- f"Loaded estimate for {estimate.engine_type}: base={estimate.base_wait_seconds:.2f}s, confidence={decay:.2f}"
- )
+ # During initialization, we don't have user context yet
+ # Mark that we need to load estimates when user context becomes available
+ self._estimates_loaded = False
+ logger.debug(
+ "Rate limit estimates will be loaded on-demand when user context is available"
+ )
- except Exception as e:
- logger.warning(f"Could not load rate limit estimates: {e}")
- # Continue with empty estimates - they'll be learned
+ def _ensure_estimates_loaded(self) -> None:
+ """Load estimates from user's encrypted database if not already loaded."""
+ if self._estimates_loaded:
+ return
+
+ # Try to get research context from search tracker
+ from ...metrics.search_tracker import get_search_tracker
+
+ tracker = get_search_tracker()
+ context = tracker._get_research_context()
+ username = context.get("username")
+ password = context.get("user_password")
+
+ if username and password:
+ try:
+ # Use thread-safe metrics writer to read from user's encrypted database
+ from ...database.thread_metrics import metrics_writer
+
+ # Set password for this thread
+ metrics_writer.set_user_password(username, password)
+
+ with metrics_writer.get_session(username) as session:
+ estimates = session.query(RateLimitEstimate).all()
+
+ for estimate in estimates:
+ # Apply decay for old estimates
+ age_hours = (time.time() - estimate.last_updated) / 3600
+ decay = self.decay_per_day ** (age_hours / 24)
+
+ self.current_estimates[estimate.engine_type] = {
+ "base": estimate.base_wait_seconds,
+ "min": estimate.min_wait_seconds,
+ "max": estimate.max_wait_seconds,
+ "confidence": decay,
+ }
+
+ logger.debug(
+ f"Loaded estimate for {estimate.engine_type}: base={estimate.base_wait_seconds:.2f}s, confidence={decay:.2f}"
+ )
+
+ self._estimates_loaded = True
+ logger.info(
+ f"Loaded {len(estimates)} rate limit estimates from encrypted database"
+ )
+
+ except Exception as e:
+ logger.warning(f"Could not load rate limit estimates: {e}")
+ # Mark as loaded anyway to avoid repeated attempts
+ self._estimates_loaded = True
def get_wait_time(self, engine_type: str) -> float:
"""
@@ -152,6 +199,9 @@ class AdaptiveRateLimitTracker:
if not self.enabled:
return 0.1
+ # Ensure estimates are loaded from database
+ self._ensure_estimates_loaded()
+
if engine_type not in self.current_estimates:
# First time seeing this engine - start optimistic and learn from real responses
# Use engine-specific optimistic defaults only for what we know for sure
@@ -208,38 +258,72 @@ class AdaptiveRateLimitTracker:
"""
# If rate limiting is disabled, don't record outcomes
if not self.enabled:
+ logger.info(
+ f"Rate limiting disabled - not recording outcome for {engine_type}"
+ )
return
+
+ logger.info(
+ f"Recording rate limit outcome for {engine_type}: success={success}, wait_time={wait_time}s"
+ )
timestamp = time.time()
# Skip database operations in fallback mode
if not os.environ.get("LDR_USE_FALLBACK_LLM", ""):
- try:
- # Save to database
- session = get_db_session()
- if session:
- attempt = RateLimitAttempt(
- engine_type=engine_type,
- timestamp=timestamp,
- wait_time=wait_time,
- retry_count=retry_count,
- success=success,
- error_type=error_type,
+ # Try to get research context from search tracker (for username/password)
+ from ...metrics.search_tracker import get_search_tracker
+
+ tracker = get_search_tracker()
+ context = tracker._get_research_context()
+ username = context.get("username")
+ password = context.get("user_password")
+
+ if username and password:
+ try:
+ # Use thread-safe metrics writer to save to user's encrypted database
+ from ...database.thread_metrics import metrics_writer
+
+ # Set password for this thread
+ logger.info(f"Setting password for user {username}")
+ metrics_writer.set_user_password(username, password)
+
+ with metrics_writer.get_session(username) as session:
+ attempt = RateLimitAttempt(
+ engine_type=engine_type,
+ timestamp=timestamp,
+ wait_time=wait_time,
+ retry_count=retry_count,
+ success=success,
+ error_type=error_type,
+ )
+ session.add(attempt)
+
+ logger.info(
+ f"Rate limit attempt recorded to encrypted DB for {engine_type}: "
+ f"success={success}, wait_time={wait_time}s, username={username}"
)
- session.add(attempt)
- session.commit()
- except Exception as e:
- logger.exception(f"Failed to record rate limit outcome: {e}")
+ except Exception as e:
+ logger.exception(
+ f"Failed to record rate limit outcome: {e}"
+ )
+ else:
+ logger.debug(
+ f"Skipping rate limit record - no user context for {engine_type}"
+ )
# Update in-memory tracking
if engine_type not in self.recent_attempts:
- # Get current memory window setting
- from ...utilities.db_utils import get_db_setting
-
- current_memory_window = int(
- get_db_setting(
- "rate_limiting.memory_window", self.memory_window
+ # Get current memory window setting from thread context
+ settings_context = get_settings_context()
+ if settings_context:
+ current_memory_window = int(
+ settings_context.get_setting(
+ "rate_limiting.memory_window", self.memory_window
+ )
)
- )
+ else:
+ current_memory_window = self.memory_window
+
self.recent_attempts[engine_type] = deque(
maxlen=current_memory_window
)
@@ -263,6 +347,9 @@ class AdaptiveRateLimitTracker:
engine_type not in self.recent_attempts
or len(self.recent_attempts[engine_type]) < 3
):
+ logger.info(
+ f"Not updating estimate for {engine_type} - only {len(self.recent_attempts.get(engine_type, []))} attempts (need 3)"
+ )
return
attempts = list(self.recent_attempts[engine_type])
@@ -285,14 +372,17 @@ class AdaptiveRateLimitTracker:
# Update estimate with learning rate (exponential moving average)
if engine_type in self.current_estimates:
old_base = self.current_estimates[engine_type]["base"]
- # Get current learning rate from settings
- from ...utilities.db_utils import get_db_setting
-
- current_learning_rate = float(
- get_db_setting(
- "rate_limiting.learning_rate", self.learning_rate
+ # Get current learning rate from settings context
+ settings_context = get_settings_context()
+ if settings_context:
+ current_learning_rate = float(
+ settings_context.get_setting(
+ "rate_limiting.learning_rate", self.learning_rate
+ )
)
- )
+ else:
+ current_learning_rate = self.learning_rate
+
new_base = (
1 - current_learning_rate
) * old_base + current_learning_rate * new_base
@@ -316,41 +406,59 @@ class AdaptiveRateLimitTracker:
success_rate = len(successful_waits) / len(attempts) if attempts else 0
if not os.environ.get("LDR_USE_FALLBACK_LLM", ""):
- try:
- session = get_db_session()
- if session:
- # Check if estimate exists
- estimate = (
- session.query(RateLimitEstimate)
- .filter_by(engine_type=engine_type)
- .first()
- )
-
- if estimate:
- # Update existing estimate
- estimate.base_wait_seconds = new_base
- estimate.min_wait_seconds = min_wait
- estimate.max_wait_seconds = max_wait
- estimate.last_updated = time.time()
- estimate.total_attempts = len(attempts)
- estimate.success_rate = success_rate
- else:
- # Create new estimate
- estimate = RateLimitEstimate(
- engine_type=engine_type,
- base_wait_seconds=new_base,
- min_wait_seconds=min_wait,
- max_wait_seconds=max_wait,
- last_updated=time.time(),
- total_attempts=len(attempts),
- success_rate=success_rate,
+ # Try to get research context from search tracker
+ from ...metrics.search_tracker import get_search_tracker
+
+ tracker = get_search_tracker()
+ context = tracker._get_research_context()
+ username = context.get("username")
+ password = context.get("user_password")
+
+ if username and password:
+ try:
+ # Use thread-safe metrics writer to save to user's encrypted database
+ from ...database.thread_metrics import metrics_writer
+
+ # Set password for this thread if not already set
+ metrics_writer.set_user_password(username, password)
+
+ with metrics_writer.get_session(username) as session:
+ # Check if estimate exists
+ estimate = (
+ session.query(RateLimitEstimate)
+ .filter_by(engine_type=engine_type)
+ .first()
)
- session.add(estimate)
-
- session.commit()
- except Exception as e:
- logger.exception(f"Failed to persist rate limit estimate: {e}")
+ if estimate:
+ # Update existing estimate
+ estimate.base_wait_seconds = new_base
+ estimate.min_wait_seconds = min_wait
+ estimate.max_wait_seconds = max_wait
+ estimate.last_updated = time.time()
+ estimate.total_attempts = len(attempts)
+ estimate.success_rate = success_rate
+ else:
+ # Create new estimate
+ estimate = RateLimitEstimate(
+ engine_type=engine_type,
+ base_wait_seconds=new_base,
+ min_wait_seconds=min_wait,
+ max_wait_seconds=max_wait,
+ last_updated=time.time(),
+ total_attempts=len(attempts),
+ success_rate=success_rate,
+ )
+ session.add(estimate)
+
+ except Exception as e:
+ logger.exception(
+ f"Failed to persist rate limit estimate: {e}"
+ )
+ else:
+ logger.debug(
+ "Skipping rate limit estimate save - no user context"
+ )
logger.info(
f"Updated rate limit for {engine_type}: {new_base:.2f}s "
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 8d791190bf..a2f112a7d0 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -82,7 +82,9 @@ class BaseSearchEngine(ABC):
# Rate limiting attributes
self.engine_type = self.__class__.__name__
self.rate_tracker = get_tracker()
- self._last_wait_time = None
+ self._last_wait_time = (
+ 0.0 # Default to 0 for successful searches without rate limiting
+ )
self._last_results_count = 0
@property
@@ -229,10 +231,10 @@ class BaseSearchEngine(ABC):
self._last_results_count = results_count
# Record success if we get here and rate limiting is enabled
- if (
- self.rate_tracker.enabled
- and self._last_wait_time is not None
- ):
+ if self.rate_tracker.enabled:
+ logger.info(
+ f"Recording successful search for {self.engine_type}: wait_time={self._last_wait_time}s, results={results_count}"
+ )
self.rate_tracker.record_outcome(
self.engine_type,
self._last_wait_time,
@@ -240,6 +242,10 @@ class BaseSearchEngine(ABC):
retry_count=1, # First attempt succeeded
search_result_count=results_count,
)
+ else:
+ logger.info(
+ f"Rate limiting disabled, not recording search for {self.engine_type}"
+ )
return results
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.py
index 699703257b..6ff05738be 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
@@ -182,6 +182,10 @@ def create_search_engine(
k: v for k, v in all_params.items() if k in engine_init_params[1:]
}
+ # Always pass settings_snapshot if the engine accepts it
+ if "settings_snapshot" in engine_init_params[1:] and settings_snapshot:
+ filtered_params["settings_snapshot"] = settings_snapshot
+
# Add LLM if required
if engine_config.get("requires_llm", False):
filtered_params["llm"] = llm
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.py
index 07302948a7..53feb0bcf4 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
@@ -8,7 +8,7 @@ from typing import Any, Dict, List
from loguru import logger
-from ..utilities.db_utils import get_db_setting
+from ..utilities.db_utils import get_setting_from_db_main_thread
from .default_search_engines import get_default_elasticsearch_config
@@ -53,9 +53,11 @@ def search_config(username: str = None) -> Dict[str, Any]:
"""
# Extract search engine definitions
- config_data = get_db_setting("search.engine.web", {}, username=username)
+ config_data = get_setting_from_db_main_thread(
+ "search.engine.web", {}, username=username
+ )
search_engines = _extract_per_engine_config(config_data)
- search_engines["auto"] = get_db_setting(
+ search_engines["auto"] = get_setting_from_db_main_thread(
"search.engine.auto", {}, username=username
)
@@ -94,7 +96,7 @@ def search_config(username: str = None) -> Dict[str, Any]:
search_engines["elasticsearch"] = get_default_elasticsearch_config()
# Register local document collections
- local_collections_data = get_db_setting(
+ local_collections_data = get_setting_from_db_main_thread(
"search.engine.local", {}, username=username
)
local_collections_data = _extract_per_engine_config(local_collections_data)
@@ -122,12 +124,12 @@ def search_config(username: str = None) -> Dict[str, Any]:
"requires_llm": True,
}
engine_config_prefix = f"search.engine.local.{collection}"
- engine_config["module_path"] = get_db_setting(
+ engine_config["module_path"] = get_setting_from_db_main_thread(
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(
+ engine_config["class_name"] = get_setting_from_db_main_thread(
f"{engine_config_prefix}.class_name",
"LocalSearchEngine",
username=username,
@@ -141,10 +143,6 @@ def search_config(username: str = None) -> Dict[str, Any]:
search_engines[collection] = engine_config
logger.info("Registered local document collections as search engines")
- # Ensure the meta search engine is still available at the end if it exists
- if "auto" in search_engines:
- meta_config = search_engines["auto"]
- search_engines["auto"] = meta_config
return search_engines
@@ -155,7 +153,7 @@ def default_search_engine(username: str = None) -> str:
The configured default search engine.
"""
- return get_db_setting(
+ return get_setting_from_db_main_thread(
"search.engine.DEFAULT_SEARCH_ENGINE", "wikipedia", username=username
)
@@ -166,7 +164,7 @@ def local_search_engines(username: str = None) -> List[str]:
A list of the enabled local search engines.
"""
- local_collections_data = get_db_setting(
+ local_collections_data = get_setting_from_db_main_thread(
"search.engine.local", {}, username=username
)
local_collections_data = _extract_per_engine_config(local_collections_data)
diff --git a/tests/TEST_ORGANIZATION.md b/tests/TEST_ORGANIZATION.md
new file mode 100644
index 0000000000..6a6103ced5
--- /dev/null
+++ b/tests/TEST_ORGANIZATION.md
@@ -0,0 +1,84 @@
+# Test Organization Guide
+
+## API Key Test Suite Structure
+
+### Core Tests (Keep These)
+
+#### 1. **test_api_key_integrated.js** (NEW)
+- **Purpose**: Main comprehensive test combining all best practices
+- **Features**: Dialog detection, CSRF handling, API + UI testing, persistence checks
+- **Use Case**: Primary test for CI/CD and debugging user selection issues
+
+#### 2. **test_api_key_settings.js**
+- **Purpose**: Mocha/Chai framework test with advanced dialog detection
+- **Features**: Screenshot capture on dialogs, full registration flow
+- **Use Case**: Framework-based testing, dialog debugging
+
+#### 3. **test_api_key_with_auth.js**
+- **Purpose**: Authentication and password validation testing
+- **Features**: Strong password checks, registration fallback
+- **Use Case**: Auth flow testing
+
+#### 4. **test_api_key_detailed_debug.js**
+- **Purpose**: Interactive debugging with visible browser
+- **Features**: DevTools open, network logging, keeps browser open
+- **Use Case**: Manual debugging of issues
+
+#### 5. **test_api_key_fixed.js**
+- **Purpose**: Pure API testing without UI interaction
+- **Features**: Direct API calls only, isolates backend issues
+- **Use Case**: Backend API verification
+
+#### 6. **test_api_key_simple_verify.js**
+- **Purpose**: Quick smoke test
+- **Features**: Minimal checks, fast execution
+- **Use Case**: Pre-commit hooks, quick CI checks
+
+#### 7. **test_api_key_functionality.js**
+- **Purpose**: Model and provider testing
+- **Features**: Checks model availability, provider switching
+- **Use Case**: LLM integration testing
+
+#### 8. **test_api_key_with_csrf.js**
+- **Purpose**: CSRF token handling
+- **Features**: Multiple CSRF detection methods
+- **Use Case**: Security testing
+
+### Running Tests
+
+```bash
+# Quick smoke test
+node tests/ui_tests/test_api_key_simple_verify.js
+
+# Full test suite
+node tests/ui_tests/test_api_key_integrated.js
+
+# Debug mode (opens browser with devtools)
+DEBUG=true node tests/ui_tests/test_api_key_detailed_debug.js
+
+# API-only test (no UI)
+node tests/ui_tests/test_api_key_fixed.js
+
+# Framework test with Mocha
+cd tests && npm test test_api_key_settings.js
+```
+
+### Test Selection Guide
+
+- **Debugging user selection dialog**: Use `test_api_key_integrated.js` or `test_api_key_settings.js`
+- **Quick verification**: Use `test_api_key_simple_verify.js`
+- **API issues**: Use `test_api_key_fixed.js`
+- **Authentication problems**: Use `test_api_key_with_auth.js`
+- **Manual debugging**: Use `DEBUG=true test_api_key_detailed_debug.js`
+
+### Files Moved to Backup
+
+The following duplicate files were moved to `backup/test_cleanup_2025_01_04/`:
+- test_api_key_simple.js (duplicate of settings test)
+- test_api_key_user_ldr1.js (minor variation)
+- test_api_key_error.js (error cases covered in integrated)
+- test_api_key_final.js (superseded by integrated)
+- test_api_key_persistence.js (persistence covered in integrated)
+- test_api_key_ui_settings.js (UI covered in integrated)
+- test_fresh_user_api_key.js (covered in integrated)
+- test_create_apitest.js (user creation covered elsewhere)
diff --git a/tests/langchain_integration/test_custom_langchain_llm.py b/tests/langchain_integration/test_custom_langchain_llm.py
index 6426094a44..2cd05cab5f 100644
--- a/tests/langchain_integration/test_custom_langchain_llm.py
+++ b/tests/langchain_integration/test_custom_langchain_llm.py
@@ -15,8 +15,8 @@ from local_deep_research.api.research_functions import (
quick_summary,
detailed_research,
)
-from local_deep_research.settings import CachedSettingsManager
from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.settings import SettingsManager
class CustomTestLLM(LLM):
@@ -259,7 +259,7 @@ class TestCustomLangChainLLM:
with get_user_db_session(
username="testuser", password="testpass"
) as session:
- settings_manager = CachedSettingsManager(session, "testuser")
+ settings_manager = SettingsManager(session, "testuser")
settings_snapshot = settings_manager.get_all_settings()
custom_llm = CustomTestLLM()
diff --git a/tests/package.json b/tests/package.json
index 4f36ad03b7..1f50058004 100644
--- a/tests/package.json
+++ b/tests/package.json
@@ -1,5 +1,11 @@
{
"dependencies": {
- "puppeteer": "^24.9.0"
+ "puppeteer": "^24.9.0",
+ "chai": "^4.3.10",
+ "mocha": "^10.2.0"
+ },
+ "scripts": {
+ "test:api-key": "mocha test_api_key_settings.js",
+ "test:api-key:debug": "HEADLESS=false mocha test_api_key_settings.js"
}
}
diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.py
index 061c1be3e9..0dc4ffdc26 100644
--- a/tests/test_api_key_configuration.py
+++ b/tests/test_api_key_configuration.py
@@ -12,7 +12,7 @@ from local_deep_research.config.llm_config import (
is_anthropic_available,
is_openai_endpoint_available,
)
-from local_deep_research.settings import CachedSettingsManager
+from local_deep_research.settings import SettingsManager
class TestAPIKeyConfiguration:
@@ -27,7 +27,7 @@ class TestAPIKeyConfiguration:
@pytest.fixture
def settings_manager(self, mock_db_session):
"""Create a settings manager with mock session."""
- return CachedSettingsManager(mock_db_session, "testuser")
+ return SettingsManager(mock_db_session)
def _get_base_settings(self):
"""Get base settings that all tests need."""
diff --git a/tests/test_api_key_settings.js b/tests/test_api_key_settings.js
new file mode 100644
index 0000000000..5774e78cb5
--- /dev/null
+++ b/tests/test_api_key_settings.js
@@ -0,0 +1,268 @@
+const puppeteer = require('puppeteer');
+const { expect } = require('chai');
+
+const BASE_URL = process.env.BASE_URL || 'http://localhost:5000';
+const TEST_USER = `test_user_${Date.now()}`;
+const TEST_PASSWORD = 'testpass123';
+const TEST_API_KEY = 'sk-or-v1-test1234567890abcdef';
+
+describe('API Key Settings Test', function() {
+ this.timeout(60000); // 60 second timeout
+
+ let browser;
+ let page;
+ let dialogMessages = [];
+
+ before(async () => {
+ browser = await puppeteer.launch({
+ headless: process.env.HEADLESS !== 'false',
+ args: ['--no-sandbox', '--disable-setuid-sandbox'],
+ devtools: process.env.DEBUG === 'true'
+ });
+ page = await browser.newPage();
+
+ // Set viewport
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Capture console logs
+ page.on('console', msg => {
+ console.log(`Browser console [${msg.type()}]:`, msg.text());
+ });
+
+ // Capture any dialogs (alert, confirm, prompt)
+ page.on('dialog', async dialog => {
+ const message = dialog.message();
+ const type = dialog.type();
+ console.log(`Dialog detected [${type}]: ${message}`);
+ dialogMessages.push({ type, message });
+
+ // Take a screenshot when dialog appears
+ try {
+ await page.screenshot({
+ path: `dialog_${type}_${Date.now()}.png`,
+ fullPage: true
+ });
+ } catch (e) {
+ console.error('Failed to capture dialog screenshot:', e);
+ }
+
+ // Accept the dialog to continue
+ await dialog.accept();
+ });
+
+ // Capture page errors
+ page.on('pageerror', error => {
+ console.error('Page error:', error.message);
+ });
+ });
+
+ after(async () => {
+ if (browser) {
+ await browser.close();
+ }
+ });
+
+ it('should register a new user', async () => {
+ await page.goto(`${BASE_URL}/register`);
+
+ // Fill registration form
+ await page.waitForSelector('#username');
+ await page.type('#username', TEST_USER);
+ await page.type('#password', TEST_PASSWORD);
+ await page.type('#confirm_password', TEST_PASSWORD);
+
+ // Submit form
+ await page.click('button[type="submit"]');
+
+ // Wait for redirect to login or dashboard
+ await page.waitForNavigation();
+
+ // Check if we need to login after registration
+ if (page.url().includes('/login')) {
+ await page.type('#username', TEST_USER);
+ await page.type('#password', TEST_PASSWORD);
+ await page.click('button[type="submit"]');
+ await page.waitForNavigation();
+ }
+
+ console.log('User registered and logged in successfully');
+ });
+
+ it('should navigate to settings and capture current API key state', async () => {
+ // Navigate to settings
+ await page.goto(`${BASE_URL}/settings`);
+ await page.waitForSelector('.settings-form', { timeout: 10000 });
+
+ // Wait for settings to load
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Find the API key field
+ const apiKeySelector = 'input[name="llm.openai_endpoint.api_key"], input[id*="openai-endpoint-api-key"]';
+ await page.waitForSelector(apiKeySelector);
+
+ // Get current value
+ const currentValue = await page.$eval(apiKeySelector, el => el.value);
+ console.log('Current API key value:', currentValue);
+
+ // Take screenshot of initial state
+ await page.screenshot({
+ path: 'settings_initial_state.png',
+ fullPage: true
+ });
+
+ expect(dialogMessages.length).to.equal(0, 'No dialogs should appear on initial load');
+ });
+
+ it('should enter API key and capture any dialogs', async () => {
+ dialogMessages = []; // Reset dialog messages
+
+ const apiKeySelector = 'input[name="llm.openai_endpoint.api_key"], input[id*="openai-endpoint-api-key"]';
+
+ // Clear the field first
+ await page.click(apiKeySelector, { clickCount: 3 });
+ await page.keyboard.press('Backspace');
+
+ // Type the new API key
+ console.log('Typing API key...');
+ await page.type(apiKeySelector, TEST_API_KEY);
+
+ // Wait a bit to see if any dialog appears
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Check if any dialogs appeared while typing
+ if (dialogMessages.length > 0) {
+ console.log('Dialogs captured while typing:', dialogMessages);
+ }
+
+ // Verify the value was entered
+ const enteredValue = await page.$eval(apiKeySelector, el => el.value);
+ console.log('Entered API key value:', enteredValue);
+ expect(enteredValue).to.equal(TEST_API_KEY);
+ });
+
+ it('should save settings and capture any dialogs', async () => {
+ dialogMessages = []; // Reset dialog messages
+
+ // Find and click save button
+ const saveButtonSelector = 'button[type="submit"]:not([type="reset"])';
+ await page.waitForSelector(saveButtonSelector);
+
+ console.log('Clicking save button...');
+
+ // Take screenshot before save
+ await page.screenshot({
+ path: 'settings_before_save.png',
+ fullPage: true
+ });
+
+ await page.click(saveButtonSelector);
+
+ // Wait for save to complete
+ await new Promise(resolve => setTimeout(resolve, 3000));
+
+ // Check if any dialogs appeared during save
+ if (dialogMessages.length > 0) {
+ console.log('Dialogs captured during save:', dialogMessages);
+
+ // If there's a user selection dialog, this is the bug
+ const userDialog = dialogMessages.find(d =>
+ d.message.toLowerCase().includes('user') ||
+ d.message.toLowerCase().includes('which')
+ );
+
+ if (userDialog) {
+ console.error('BUG DETECTED: User selection dialog appeared!');
+ console.error('Dialog details:', userDialog);
+ }
+ }
+
+ // Take screenshot after save
+ await page.screenshot({
+ path: 'settings_after_save.png',
+ fullPage: true
+ });
+ });
+
+ it('should verify API key was saved correctly', async () => {
+ // Reload the page to check if the key persisted
+ await page.reload();
+ await page.waitForSelector('.settings-form', { timeout: 10000 });
+
+ // Wait for settings to load
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ const apiKeySelector = 'input[name="llm.openai_endpoint.api_key"], input[id*="openai-endpoint-api-key"]';
+ await page.waitForSelector(apiKeySelector);
+
+ // Get the value after reload
+ const savedValue = await page.$eval(apiKeySelector, el => el.value);
+ console.log('API key value after reload:', savedValue);
+
+ // Check if it's still the placeholder or actual key
+ if (savedValue === 'OPENAI_ENDPOINT_API_KEY') {
+ console.error('BUG: API key was not saved! Still showing placeholder.');
+ } else if (savedValue === TEST_API_KEY) {
+ console.log('SUCCESS: API key was saved correctly!');
+ } else if (savedValue === '********' || savedValue.includes('*')) {
+ console.log('API key appears to be masked for security');
+
+ // Try to make a research request to verify it works
+ await verifyApiKeyWorks(page);
+ }
+
+ // Take final screenshot
+ await page.screenshot({
+ path: 'settings_final_state.png',
+ fullPage: true
+ });
+ });
+
+ it('should test research with the saved API key', async () => {
+ // Navigate to research page
+ await page.goto(`${BASE_URL}/`);
+ await page.waitForSelector('#queryInput', { timeout: 10000 });
+
+ // Enter a test query
+ await page.type('#queryInput', 'test query');
+
+ // Select the provider
+ const providerSelector = 'select[name="model_provider"], #model_provider';
+ if (await page.$(providerSelector)) {
+ await page.select(providerSelector, 'openai_endpoint');
+ }
+
+ // Start research
+ await page.click('#submitBtn');
+
+ // Wait for response
+ await new Promise(resolve => setTimeout(resolve, 5000));
+
+ // Check for authentication errors
+ const pageContent = await page.content();
+ if (pageContent.includes('401') || pageContent.includes('authentication') || pageContent.includes('No auth credentials')) {
+ console.error('BUG: API key not working! Getting authentication error.');
+
+ // Take screenshot of error
+ await page.screenshot({
+ path: 'research_auth_error.png',
+ fullPage: true
+ });
+ } else {
+ console.log('API key appears to be working for research');
+ }
+ });
+});
+
+async function verifyApiKeyWorks(page) {
+ console.log('Verifying API key functionality...');
+ // This would make an actual API call to verify the key works
+ // For now, we'll just log that we would verify it
+}
+
+// Run the test
+if (require.main === module) {
+ console.log('Running API Key Settings Test...');
+ console.log(`Testing against: ${BASE_URL}`);
+ console.log('Set HEADLESS=false to see the browser');
+ console.log('Set DEBUG=true to open devtools');
+}
diff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.py
index ade3e46d75..075bb3d8f8 100644
--- a/tests/test_llm_provider_integration.py
+++ b/tests/test_llm_provider_integration.py
@@ -5,8 +5,7 @@ Tests the full flow from API key configuration to research execution.
import pytest
from unittest.mock import Mock, patch
-
-from local_deep_research.settings import CachedSettingsManager
+from local_deep_research.settings import SettingsManager
class TestLLMProviderIntegration:
@@ -97,16 +96,16 @@ class TestLLMProviderIntegration:
"""Test configuring OpenRouter API key through settings."""
# Create settings manager with patched methods
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_setting",
side_effect=mock_session._get_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"set_setting",
side_effect=mock_session._set_setting,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
# Update API key setting
new_api_key = "sk-openrouter-new-test-key"
@@ -127,11 +126,11 @@ class TestLLMProviderIntegration:
# Create settings manager with patched methods
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_all_settings",
side_effect=mock_session._get_all_settings,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
settings_snapshot = settings_manager.get_all_settings()
# Verify settings are correct - get_all_settings returns nested dicts
@@ -200,21 +199,21 @@ class TestLLMProviderIntegration:
from local_deep_research.config.llm_config import get_llm
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_setting",
side_effect=mock_session._get_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"set_setting",
side_effect=mock_session._set_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_all_settings",
side_effect=mock_session._get_all_settings,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
# Test 1: OpenRouter configuration
settings_manager.set_setting(
@@ -280,11 +279,11 @@ class TestLLMProviderIntegration:
)
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"set_setting",
side_effect=mock_session._set_setting,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
# With API key
settings_manager.set_setting(
@@ -307,21 +306,21 @@ class TestLLMProviderIntegration:
def test_custom_model_configuration(self, mock_session):
"""Test configuring custom models with API endpoints."""
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_setting",
side_effect=mock_session._get_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"set_setting",
side_effect=mock_session._set_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_all_settings",
side_effect=mock_session._get_all_settings,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
# Configure for a specific model on OpenRouter
settings_manager.set_setting(
@@ -375,16 +374,16 @@ class TestLLMProviderIntegration:
)
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"set_setting",
side_effect=mock_session._set_setting,
):
with patch.object(
- CachedSettingsManager,
+ SettingsManager,
"get_all_settings",
side_effect=mock_session._get_all_settings,
):
- settings_manager = CachedSettingsManager(None, "testuser")
+ settings_manager = SettingsManager(None)
settings_manager.set_setting("llm.provider", "openai_endpoint")
settings_manager.set_setting(
"llm.openai_endpoint.api_key", "sk-benchmark-key"
diff --git a/tests/test_openai_api_key_e2e.py b/tests/test_openai_api_key_e2e.py
index d7e2982fe8..50b1b0eb16 100755
--- a/tests/test_openai_api_key_e2e.py
+++ b/tests/test_openai_api_key_e2e.py
@@ -23,10 +23,10 @@ from typing import Optional
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from local_deep_research.settings import CachedSettingsManager
from local_deep_research.database.session_context import get_user_db_session
from local_deep_research.config.llm_config import get_llm
from local_deep_research.api.research_functions import quick_summary
+from local_deep_research.settings import SettingsManager
from loguru import logger
@@ -58,7 +58,7 @@ def test_openai_api_key(
# Step 2: Configure settings
print("\n2. Configuring OpenAI settings...")
- settings_manager = CachedSettingsManager(session, username)
+ settings_manager = SettingsManager(session, username)
# Set OpenAI as provider
settings_manager.set_setting("llm.provider", "openai")
diff --git a/tests/ui_tests/test_api_key_detailed_debug.js b/tests/ui_tests/test_api_key_detailed_debug.js
new file mode 100644
index 0000000000..26a1ae3e00
--- /dev/null
+++ b/tests/ui_tests/test_api_key_detailed_debug.js
@@ -0,0 +1,274 @@
+const puppeteer = require('puppeteer');
+const AuthHelper = require('./auth_helper');
+
+// Test changing API key with detailed debugging
+(async () => {
+ let browser;
+ let authHelper;
+ let page;
+
+ try {
+ console.log('=== Starting API Key Debug Test ===');
+
+ // Test configuration
+ const TEST_API_KEY_1 = 'test-api-key-12345';
+ const TEST_API_KEY_2 = 'changed-api-key-67890';
+ const BASE_URL = 'http://127.0.0.1:5000';
+ const API_KEY_SETTING = 'llm.openai_endpoint.api_key';
+
+ // Launch browser with visible window for debugging
+ browser = await puppeteer.launch({
+ headless: false,
+ args: ['--no-sandbox', '--disable-setuid-sandbox'],
+ devtools: true
+ });
+
+ page = await browser.newPage();
+
+ // Enable console logging from the page
+ page.on('console', msg => {
+ console.log(`[BROWSER CONSOLE ${msg.type()}]: ${msg.text()}`);
+ });
+
+ // Log network requests
+ page.on('request', request => {
+ if (request.url().includes('settings')) {
+ console.log(`[NETWORK REQUEST]: ${request.method()} ${request.url()}`);
+ }
+ });
+
+ // Log network responses
+ page.on('response', response => {
+ if (response.url().includes('settings')) {
+ console.log(`[NETWORK RESPONSE]: ${response.status()} ${response.url()}`);
+ }
+ });
+
+ // Initialize auth helper
+ authHelper = new AuthHelper(page, BASE_URL);
+
+ // Create test user
+ const timestamp = Date.now();
+ const testUsername = `api_test_${timestamp}`;
+ const testPassword = 'testpass123';
+
+ console.log(`\nCreating user: ${testUsername}`);
+ await authHelper.register(testUsername, testPassword);
+
+ const isAuthenticated = await authHelper.isLoggedIn();
+ if (!isAuthenticated) {
+ throw new Error('Failed to authenticate after registration');
+ }
+ console.log('✓ User authenticated successfully');
+
+ // Navigate to settings page to see what's there
+ console.log('\n📄 Navigating to settings page...');
+ await page.goto(`${BASE_URL}/settings`, { waitUntil: 'networkidle2' });
+
+ // Take a screenshot
+ await page.screenshot({ path: 'settings_page_debug.png', fullPage: true });
+ console.log('📸 Screenshot saved as settings_page_debug.png');
+
+ // Check page title and content
+ const pageTitle = await page.title();
+ console.log(`Page title: ${pageTitle}`);
+
+ // Check if we're on the settings page
+ const pageContent = await page.evaluate(() => {
+ return {
+ url: window.location.href,
+ hasSettingsForm: !!document.querySelector('.settings-form'),
+ hasApiKeyInput: !!document.querySelector('input[name*="api_key"]'),
+ formElements: Array.from(document.querySelectorAll('input[type="text"], input[type="password"]')).map(el => ({
+ name: el.name,
+ id: el.id,
+ placeholder: el.placeholder,
+ value: el.value ? '***' : 'empty'
+ }))
+ };
+ });
+ console.log('\nPage content analysis:', JSON.stringify(pageContent, null, 2));
+
+ // Test 1: Try to get current settings via API
+ console.log('\n🔍 Test 1: Getting current API key setting...');
+ const currentSetting = await page.evaluate(async (key) => {
+ console.log(`Fetching setting: ${key}`);
+ const response = await fetch(`/settings/api/${key}`, {
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json'
+ }
+ });
+ console.log(`Response status: ${response.status}`);
+ console.log(`Response headers:`, response.headers);
+
+ const text = await response.text();
+ console.log(`Response text (first 500 chars): ${text.substring(0, 500)}`);
+
+ if (response.status === 404) {
+ return { exists: false, status: 404 };
+ }
+
+ try {
+ const data = JSON.parse(text);
+ return {
+ exists: true,
+ status: response.status,
+ data: data
+ };
+ } catch (e) {
+ return {
+ exists: false,
+ status: response.status,
+ error: 'Failed to parse JSON',
+ responseText: text.substring(0, 500)
+ };
+ }
+ }, API_KEY_SETTING);
+
+ console.log('API Response:', JSON.stringify(currentSetting, null, 2));
+
+ // Test 2: Try to get all settings
+ console.log('\n🔍 Test 2: Getting all settings...');
+ const allSettings = await page.evaluate(async () => {
+ const response = await fetch(`/settings/api`, {
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json'
+ }
+ });
+ const text = await response.text();
+ console.log(`All settings response (first 1000 chars): ${text.substring(0, 1000)}`);
+
+ try {
+ return {
+ status: response.status,
+ data: JSON.parse(text)
+ };
+ } catch (e) {
+ return {
+ status: response.status,
+ error: 'Failed to parse JSON',
+ responseText: text.substring(0, 500)
+ };
+ }
+ });
+
+ console.log('All settings response:', JSON.stringify(allSettings, null, 2));
+
+ // Test 3: Check available endpoints
+ console.log('\n🔍 Test 3: Checking available models endpoint...');
+ const modelsCheck = await page.evaluate(async () => {
+ const response = await fetch(`/settings/api/available-models`, {
+ credentials: 'same-origin'
+ });
+ return {
+ status: response.status,
+ ok: response.ok,
+ url: response.url
+ };
+ });
+ console.log('Models endpoint check:', modelsCheck);
+
+ // Test 4: Try to update setting if we can access the API
+ if (currentSetting.exists || allSettings.status === 200) {
+ console.log(`\n📝 Test 4: Attempting to update API key to: ${TEST_API_KEY_1}`);
+ const updateResult = await page.evaluate(async (key, value) => {
+ const response = await fetch(`/settings/api/${key}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ },
+ credentials: 'same-origin',
+ body: JSON.stringify({
+ value: value
+ })
+ });
+
+ const text = await response.text();
+ console.log(`Update response (first 500 chars): ${text.substring(0, 500)}`);
+
+ try {
+ return {
+ ok: response.ok,
+ status: response.status,
+ data: JSON.parse(text)
+ };
+ } catch (e) {
+ return {
+ ok: response.ok,
+ status: response.status,
+ error: 'Failed to parse JSON',
+ responseText: text.substring(0, 500)
+ };
+ }
+ }, API_KEY_SETTING, TEST_API_KEY_1);
+
+ console.log('Update result:', JSON.stringify(updateResult, null, 2));
+ }
+
+ // Test 5: Try the bulk update endpoint
+ console.log('\n📝 Test 5: Trying bulk settings update...');
+ const bulkUpdate = await page.evaluate(async (apiKey) => {
+ const response = await fetch('/settings/save_all_settings', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'same-origin',
+ body: JSON.stringify({
+ 'llm.openai_endpoint.api_key': apiKey
+ })
+ });
+
+ const text = await response.text();
+ console.log(`Bulk update response: ${text.substring(0, 500)}`);
+
+ try {
+ return {
+ ok: response.ok,
+ status: response.status,
+ data: JSON.parse(text)
+ };
+ } catch (e) {
+ return {
+ ok: response.ok,
+ status: response.status,
+ error: 'Failed to parse JSON',
+ responseText: text.substring(0, 500)
+ };
+ }
+ }, TEST_API_KEY_1);
+
+ console.log('Bulk update result:', JSON.stringify(bulkUpdate, null, 2));
+
+ // Take final screenshot
+ await page.screenshot({ path: 'settings_page_final_debug.png', fullPage: true });
+ console.log('\n📸 Final screenshot saved as settings_page_final_debug.png');
+
+ console.log('\n=== Debug Test Completed ===');
+ console.log('Check the screenshots and logs for more details.');
+ console.log('Browser will remain open for manual inspection...');
+
+ // Keep browser open for 30 seconds for manual inspection
+ await new Promise(resolve => setTimeout(resolve, 30000));
+
+ } catch (error) {
+ console.error(`\n❌ Test failed: ${error.message}`);
+ console.error(error);
+
+ // Take error screenshot
+ if (page) {
+ await page.screenshot({ path: 'error_screenshot_debug.png', fullPage: true });
+ console.log('📸 Error screenshot saved as error_screenshot_debug.png');
+ }
+
+ process.exit(1);
+ } finally {
+ if (browser) {
+ await browser.close();
+ console.log('\nBrowser closed');
+ }
+ }
+})();
diff --git a/tests/ui_tests/test_api_key_integrated.js b/tests/ui_tests/test_api_key_integrated.js
new file mode 100644
index 0000000000..9ae611c7bb
--- /dev/null
+++ b/tests/ui_tests/test_api_key_integrated.js
@@ -0,0 +1,343 @@
+/**
+ * Integrated API Key Test Suite
+ *
+ * This test combines the best features from multiple test files:
+ * - Dialog detection from test_api_key_settings.js
+ * - CSRF handling from test_api_key_with_csrf.js
+ * - Strong password validation from test_api_key_with_auth.js
+ * - API-only testing from test_api_key_fixed.js
+ * - Persistence verification from test_api_key_persistence.js
+ */
+
+const puppeteer = require('puppeteer');
+const AuthHelper = require('./auth_helper');
+
+// Test configuration
+const TEST_USER = 'apitest_' + Date.now();
+const TEST_PASSWORD = 'TestPassword123!';
+const TEST_API_KEY = 'sk-test-integrated-key-' + Date.now();
+const BASE_URL = 'http://127.0.0.1:5000';
+const API_KEY_SETTING = 'llm.openai_endpoint.api_key';
+
+// Color codes for better output
+const colors = {
+ reset: '\x1b[0m',
+ bright: '\x1b[1m',
+ red: '\x1b[31m',
+ green: '\x1b[32m',
+ yellow: '\x1b[33m',
+ blue: '\x1b[34m',
+ magenta: '\x1b[35m',
+ cyan: '\x1b[36m'
+};
+
+function log(message, type = 'info') {
+ const timestamp = new Date().toISOString();
+ const typeColors = {
+ info: colors.blue,
+ success: colors.green,
+ error: colors.red,
+ warning: colors.yellow,
+ debug: colors.cyan
+ };
+
+ const color = typeColors[type] || colors.reset;
+ const symbol = {
+ info: 'ℹ',
+ success: '✓',
+ error: '✗',
+ warning: '⚠',
+ debug: '🔍'
+ }[type] || '•';
+
+ console.log(`${color}${symbol}${colors.reset} [${timestamp}] ${message}`);
+}
+
+// Helper to get CSRF token
+async function getCSRFToken(page) {
+ return await page.evaluate(() => {
+ // Try multiple methods to get CSRF token
+ const metaTag = document.querySelector('meta[name="csrf-token"]');
+ if (metaTag) return metaTag.content;
+
+ const csrfInput = document.querySelector('input[name="csrf_token"]');
+ if (csrfInput) return csrfInput.value;
+
+ // Check cookies
+ const cookies = document.cookie.split(';');
+ for (const cookie of cookies) {
+ const [name, value] = cookie.trim().split('=');
+ if (name === 'csrf_token' || name === 'X-CSRFToken') {
+ return value;
+ }
+ }
+
+ return null;
+ });
+}
+
+// Main test function
+(async () => {
+ let browser;
+ let authHelper;
+ const dialogMessages = [];
+
+ try {
+ log('Starting Integrated API Key Test Suite', 'info');
+
+ // Launch browser with debugging options
+ browser = await puppeteer.launch({
+ headless: process.env.DEBUG !== 'true',
+ devtools: process.env.DEBUG === 'true',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ const page = await browser.newPage();
+
+ // Enable console logging
+ page.on('console', msg => {
+ if (msg.type() === 'error') {
+ log(`[BROWSER ERROR] ${msg.text()}`, 'error');
+ }
+ });
+
+ // Dialog detection (critical for user selection bug)
+ page.on('dialog', async dialog => {
+ const message = dialog.message();
+ const type = dialog.type();
+ log(`Dialog detected! Type: ${type}, Message: ${message}`, 'warning');
+
+ dialogMessages.push({ type, message, timestamp: new Date() });
+
+ // Take screenshot when dialog appears
+ try {
+ await page.screenshot({
+ path: `dialog_screenshot_${Date.now()}.png`,
+ fullPage: true
+ });
+ } catch (e) {
+ log('Failed to capture screenshot during dialog', 'error');
+ }
+
+ // Auto-accept dialogs
+ await dialog.accept();
+ });
+
+ // Network request logging for debugging
+ if (process.env.DEBUG === 'true') {
+ page.on('request', request => {
+ if (request.url().includes('/settings/')) {
+ log(`[REQUEST] ${request.method()} ${request.url()}`, 'debug');
+ }
+ });
+
+ page.on('response', response => {
+ if (response.url().includes('/settings/')) {
+ log(`[RESPONSE] ${response.status()} ${response.url()}`, 'debug');
+ }
+ });
+ }
+
+ authHelper = new AuthHelper(page, BASE_URL);
+
+ // Test 1: Register new user with strong password validation
+ log('Test 1: User Registration', 'info');
+ try {
+ await authHelper.register(TEST_USER, TEST_PASSWORD);
+ log('User registered successfully', 'success');
+ } catch (error) {
+ if (error.message.includes('already exists')) {
+ log('User already exists, attempting login', 'warning');
+ await authHelper.login(TEST_USER, TEST_PASSWORD);
+ } else {
+ throw error;
+ }
+ }
+
+ // Test 2: Navigate to settings and wait for full load
+ log('Test 2: Navigate to Settings', 'info');
+ await page.goto(`${BASE_URL}/settings`, { waitUntil: 'networkidle2' });
+ await page.waitForSelector('input, button', { visible: true, timeout: 10000 });
+
+ // Test 3: Get CSRF token
+ log('Test 3: CSRF Token Handling', 'info');
+ const csrfToken = await getCSRFToken(page);
+ if (csrfToken) {
+ log(`CSRF token found: ${csrfToken.substring(0, 10)}...`, 'success');
+ } else {
+ log('No CSRF token found, continuing without it', 'warning');
+ }
+
+ // Test 4: API-only test (isolate backend from UI)
+ log('Test 4: API-only Backend Test', 'info');
+ const apiTestResult = await page.evaluate(async (key, value, token) => {
+ const headers = {
+ 'Content-Type': 'application/json',
+ };
+
+ if (token) {
+ headers['X-CSRFToken'] = token;
+ headers['X-CSRF-Token'] = token;
+ }
+
+ // First check if setting exists
+ const checkResponse = await fetch(`/settings/api/${key}`, {
+ method: 'GET',
+ credentials: 'same-origin'
+ });
+
+ // Update the setting
+ const updateResponse = await fetch(`/settings/api/${key}`, {
+ method: 'PUT',
+ headers: headers,
+ credentials: 'same-origin',
+ body: JSON.stringify({ value: value })
+ });
+
+ return {
+ checkStatus: checkResponse.status,
+ updateStatus: updateResponse.status,
+ updateOk: updateResponse.ok,
+ updateData: await updateResponse.json()
+ };
+ }, API_KEY_SETTING, TEST_API_KEY, csrfToken);
+
+ log(`API test result: ${JSON.stringify(apiTestResult)}`, 'info');
+
+ if (apiTestResult.updateOk) {
+ log('API key updated successfully via API', 'success');
+ } else {
+ log('API update failed, trying UI approach', 'warning');
+ }
+
+ // Test 5: UI-based update (fallback)
+ log('Test 5: UI-based API Key Update', 'info');
+
+ // Look for LLM Parameters tab
+ const llmTab = await page.$('a[href="#llm-parameters"], button:has-text("LLM Parameters")');
+ if (llmTab) {
+ await llmTab.click();
+ await page.waitForTimeout(1000);
+ }
+
+ // Find the API key input
+ const apiKeyInput = await page.$(`input[name="${API_KEY_SETTING}"]`);
+ if (apiKeyInput) {
+ await apiKeyInput.click({ clickCount: 3 });
+ await apiKeyInput.type(TEST_API_KEY);
+ log('API key entered in UI', 'success');
+ } else {
+ log('API key input not found', 'error');
+ }
+
+ // Find and click save button
+ let saveButton = await page.$('button[type="submit"]:not([type="reset"])');
+ if (!saveButton) {
+ // Alternative method to find save button
+ const buttons = await page.$$eval('button', btns =>
+ btns.map((btn, index) => ({
+ index,
+ text: btn.textContent.trim(),
+ type: btn.type
+ }))
+ );
+
+ const saveButtonInfo = buttons.find(b =>
+ b.text.toLowerCase().includes('save') && b.type !== 'reset'
+ );
+
+ if (saveButtonInfo) {
+ const allButtons = await page.$$('button');
+ saveButton = allButtons[saveButtonInfo.index];
+ }
+ }
+
+ if (saveButton) {
+ await saveButton.click();
+ log('Save button clicked', 'success');
+ await page.waitForTimeout(2000);
+ }
+
+ // Test 6: Verify persistence
+ log('Test 6: Persistence Verification', 'info');
+
+ // Reload page
+ await page.reload({ waitUntil: 'networkidle2' });
+
+ // Check if value persisted via API
+ const persistenceCheck = await page.evaluate(async (key) => {
+ const response = await fetch(`/settings/api/${key}`, {
+ method: 'GET',
+ credentials: 'same-origin'
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ return data.value;
+ }
+ return null;
+ }, API_KEY_SETTING);
+
+ if (persistenceCheck === TEST_API_KEY) {
+ log('✓ API key persisted successfully!', 'success');
+ } else {
+ log(`✗ API key not persisted. Expected: ${TEST_API_KEY}, Got: ${persistenceCheck}`, 'error');
+ }
+
+ // Test 7: Check dialog messages
+ if (dialogMessages.length > 0) {
+ log(`\n⚠️ ${dialogMessages.length} dialog(s) detected during test:`, 'warning');
+ dialogMessages.forEach((dialog, index) => {
+ log(` Dialog ${index + 1}: ${dialog.type} - "${dialog.message}"`, 'warning');
+ });
+ log('This might be the user selection bug!', 'error');
+ } else {
+ log('No dialogs detected during test', 'success');
+ }
+
+ // Test 8: Research functionality with API key
+ log('Test 8: Research Functionality Test', 'info');
+ await page.goto(BASE_URL, { waitUntil: 'networkidle2' });
+
+ const searchInput = await page.$('input[name="query"]');
+ if (searchInput) {
+ await searchInput.type('Test research query');
+ const submitButton = await page.$('button[type="submit"]');
+ if (submitButton) {
+ await submitButton.click();
+ await page.waitForTimeout(3000);
+
+ // Check if research started successfully
+ const currentUrl = page.url();
+ if (currentUrl.includes('/research/')) {
+ log('Research started successfully with API key', 'success');
+ } else {
+ log('Research may have failed', 'warning');
+ }
+ }
+ }
+
+ log('\n=== Test Summary ===', 'info');
+ log(`Total dialogs detected: ${dialogMessages.length}`, dialogMessages.length > 0 ? 'error' : 'success');
+ log(`API key persisted: ${persistenceCheck === TEST_API_KEY ? 'Yes' : 'No'}`, persistenceCheck === TEST_API_KEY ? 'success' : 'error');
+
+ } catch (error) {
+ log(`Test failed with error: ${error.message}`, 'error');
+ console.error(error);
+
+ // Take error screenshot
+ if (browser) {
+ const page = (await browser.pages())[0];
+ if (page) {
+ await page.screenshot({ path: 'error_screenshot.png', fullPage: true });
+ }
+ }
+ } finally {
+ if (browser && process.env.DEBUG !== 'true') {
+ await browser.close();
+ } else if (process.env.DEBUG === 'true') {
+ log('Browser kept open for debugging. Press Ctrl+C to exit.', 'info');
+ await new Promise(() => {}); // Keep process alive
+ }
+ }
+})();
diff --git a/tests/ui_tests/test_api_key_simple_verify.js b/tests/ui_tests/test_api_key_simple_verify.js
new file mode 100644
index 0000000000..a55ecb1116
--- /dev/null
+++ b/tests/ui_tests/test_api_key_simple_verify.js
@@ -0,0 +1,133 @@
+const puppeteer = require('puppeteer');
+const AuthHelper = require('./auth_helper');
+
+// Simple test to verify API key can be set and retrieved
+(async () => {
+ let browser;
+
+ try {
+ console.log('=== Simple API Key Verification Test ===\n');
+
+ const TEST_API_KEY = 'sk-test-' + Date.now();
+ const BASE_URL = 'http://127.0.0.1:5000';
+
+ browser = await puppeteer.launch({
+ headless: true,
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ const page = await browser.newPage();
+ const authHelper = new AuthHelper(page, BASE_URL);
+
+ // Create and authenticate user
+ const testUser = `test_${Date.now()}`;
+ await authHelper.register(testUser, 'testpass123');
+ console.log(`✓ User ${testUser} created\n`);
+
+ // Get CSRF token
+ await page.goto(`${BASE_URL}/settings`, { waitUntil: 'networkidle2' });
+ const csrfToken = await page.evaluate(() => {
+ const meta = document.querySelector('meta[name="csrf-token"]');
+ return meta ? meta.content : null;
+ });
+
+ if (!csrfToken) {
+ throw new Error('CSRF token not found');
+ }
+
+ // Test 1: Set API key
+ console.log('Test 1: Setting API key...');
+ const setResult = await page.evaluate(async (key, token) => {
+ const response = await fetch('/settings/api/llm.openai_endpoint.api_key', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': token
+ },
+ credentials: 'same-origin',
+ body: JSON.stringify({ value: key })
+ });
+ return {
+ status: response.status,
+ data: await response.json()
+ };
+ }, TEST_API_KEY, csrfToken);
+
+ console.log(`Status: ${setResult.status}`);
+ console.log(`Response: ${JSON.stringify(setResult.data)}\n`);
+
+ // Test 2: Get API key back
+ console.log('Test 2: Getting API key...');
+ const getResult = await page.evaluate(async () => {
+ const response = await fetch('/settings/api/llm.openai_endpoint.api_key', {
+ credentials: 'same-origin'
+ });
+ return await response.json();
+ });
+
+ console.log(`Retrieved value: ${getResult.value || 'empty'}`);
+ console.log(`Match: ${getResult.value === TEST_API_KEY ? '✓' : '✗'}\n`);
+
+ // Test 3: Get all settings to see if it's there
+ console.log('Test 3: Checking in all settings...');
+ const allSettings = await page.evaluate(async () => {
+ const response = await fetch('/settings/api', {
+ credentials: 'same-origin'
+ });
+ const data = await response.json();
+ return {
+ hasKey: 'llm.openai_endpoint.api_key' in data,
+ value: data['llm.openai_endpoint.api_key']?.value
+ };
+ });
+
+ console.log(`Found in all settings: ${allSettings.hasKey ? '✓' : '✗'}`);
+ console.log(`Value in all settings: ${allSettings.value || 'empty'}\n`);
+
+ // Test 4: Try alternative update method
+ console.log('Test 4: Using bulk update...');
+ const bulkResult = await page.evaluate(async (key, token) => {
+ const response = await fetch('/settings/save_all_settings', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': token
+ },
+ credentials: 'same-origin',
+ body: JSON.stringify({
+ 'llm.openai_endpoint.api_key': key + '-bulk'
+ })
+ });
+ return {
+ status: response.status,
+ data: await response.json()
+ };
+ }, TEST_API_KEY, csrfToken);
+
+ console.log(`Bulk update status: ${bulkResult.status}`);
+ console.log(`Bulk update response: ${JSON.stringify(bulkResult.data)}\n`);
+
+ // Verify bulk update
+ const bulkVerify = await page.evaluate(async () => {
+ const response = await fetch('/settings/api/llm.openai_endpoint.api_key', {
+ credentials: 'same-origin'
+ });
+ return await response.json();
+ });
+
+ console.log(`Value after bulk update: ${bulkVerify.value || 'empty'}`);
+ console.log(`Bulk update worked: ${bulkVerify.value === TEST_API_KEY + '-bulk' ? '✓' : '✗'}\n`);
+
+ // Summary
+ console.log('=== Summary ===');
+ console.log(`Individual PUT: ${getResult.value === TEST_API_KEY ? '✓ Working' : '✗ Not working'}`);
+ console.log(`Bulk POST: ${bulkVerify.value === TEST_API_KEY + '-bulk' ? '✓ Working' : '✗ Not working'}`);
+
+ } catch (error) {
+ console.error(`\n❌ Error: ${error.message}`);
+ } finally {
+ if (browser) {
+ await browser.close();
+ }
+ }
+})();