~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
tried to resolve merge conflicts
LearningCircuitcdcb3b56c492
diff --cc src/local_deep_research/web/app.pyindex 530dc1b337,84ba240b10..ee37eb6542--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@@ -128,7 -85,7 +131,6 @@@ def handle_websocket_requests()# Return empty response to prevent further processingreturn '', 200--# Initialize the databasedef init_db():conn = sqlite3.connect(DB_PATH)cursor = conn.cursor()@@@ -157,9 -129,17 +174,17 @@@print("Adding missing 'duration_seconds' column to research_history table")cursor.execute('ALTER TABLE research_history ADD COLUMN duration_seconds INTEGER')+ # Check if the progress column exists, add it if missing+ if 'progress' not in columns:+ print("Adding missing 'progress' column to research_history table")+ cursor.execute('ALTER TABLE research_history ADD COLUMN progress INTEGER')++ # Enable foreign key support+ cursor.execute('PRAGMA foreign_keys = ON')+conn.commit()conn.close()--++# Helper function to calculate duration between created_at and completed_at timestampsdef calculate_duration(created_at_str):"""@@@ -200,7 -180,89 +225,89 @@@return duration_seconds+ # Add these helper functions after the calculate_duration function++++ def add_log_to_db(research_id, message, log_type='info', progress=None, metadata=None):+ """+ Store a log entry in the database++ Args:+ research_id: ID of the research+ message: Log message text+ log_type: Type of log (info, error, milestone)+ progress: Progress percentage (0-100)+ metadata: Additional metadata as dictionary (will be stored as JSON)+ """+ try:+ timestamp = datetime.utcnow().isoformat()+ metadata_json = json.dumps(metadata) if metadata else None++ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ 'INSERT INTO research_logs (research_id, timestamp, message, log_type, progress, metadata) '+ 'VALUES (?, ?, ?, ?, ?, ?)',+ (research_id, timestamp, message, log_type, progress, metadata_json)+ )+ conn.commit()+ conn.close()+ return True+ except Exception as e:+ print(f"Error adding log to database: {str(e)}")+ print(traceback.format_exc())+ return False++ def get_logs_for_research(research_id):+ """+ Retrieve all logs for a specific research ID++ Args:+ research_id: ID of the research++ Returns:+ List of log entries as dictionaries+ """+ try:+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute(+ 'SELECT * FROM research_logs WHERE research_id = ? ORDER BY timestamp ASC',+ (research_id,)+ )+ results = cursor.fetchall()+ conn.close()++ logs = []+ for result in results:+ log_entry = dict(result)+ # Parse metadata JSON if it exists+ if log_entry.get('metadata'):+ try:+ log_entry['metadata'] = json.loads(log_entry['metadata'])+ except:+ log_entry['metadata'] = {}+ else:+ log_entry['metadata'] = {}++ # Convert entry for frontend consumption+ formatted_entry = {+ 'time': log_entry['timestamp'],+ 'message': log_entry['message'],+ 'progress': log_entry['progress'],+ 'metadata': log_entry['metadata'],+ 'type': log_entry['log_type']+ }+ logs.append(formatted_entry)++ return logs+ except Exception as e:+ print(f"Error retrieving logs from database: {str(e)}")+ print(traceback.format_exc())+ return []-++# Initialize the database on startup-# @app.before_first_request # This is deprecated in newer Flask versionsdef initialize():init_db()@@@ -1090,249 -1315,45 +1360,288 @@@ def delete_research(research_id)conn.close()return jsonify({'status': 'success'})-- # Main settings page that links to specialized config pages+@research_bp.route('/settings', methods=['GET'])+def settings_page():+ """Main settings dashboard with links to specialized config pages"""+ return render_template('settings_dashboard.html')++@research_bp.route('/settings/main', methods=['GET'])+def main_config_page():+ """Edit main configuration with search parameters"""+ return render_template('main_config.html', main_file_path=MAIN_CONFIG_FILE)++@research_bp.route('/settings/llm', methods=['GET'])+def llm_config_page():+ """Edit LLM configuration using raw file editor"""+ return render_template('llm_config.html', llm_file_path=LLM_CONFIG_FILE)++@research_bp.route('/settings/collections', methods=['GET'])+def collections_config_page():+ """Edit local collections configuration using raw file editor"""+ return render_template('collections_config.html', collections_file_path=LOCAL_COLLECTIONS_FILE)++@research_bp.route('/settings/api_keys', methods=['GET'])+def api_keys_config_page():+ """Edit API keys configuration"""+ # Get the secrets file path+ secrets_file = CONFIG_DIR / ".secrets.toml"++ return render_template('api_keys_config.html', secrets_file_path=secrets_file)+# Add to the imports section+from local_deep_research.config import SEARCH_ENGINES_FILE++# Add a new route for search engines configuration page+@research_bp.route('/settings/search_engines', methods=['GET'])+def search_engines_config_page():+ """Edit search engines configuration using raw file editor"""+ # Read the current config file+ raw_config = ""+ try:+ with open(SEARCH_ENGINES_FILE, 'r') as f:+ raw_config = f.read()+ except Exception as e:+ flash(f'Error reading search engines configuration: {str(e)}', 'error')+ raw_config = "# Error reading configuration file"++ # Get list of engine names for display+ engine_names = []+ try:+ from local_deep_research.web_search_engines.search_engines_config import SEARCH_ENGINES+ engine_names = list(SEARCH_ENGINES.keys())+ engine_names.sort() # Alphabetical order+ except Exception as e:+ logger.error(f"Error getting engine names: {e}")++ return render_template('search_engines_config.html',+ search_engines_file_path=SEARCH_ENGINES_FILE,+ raw_config=raw_config,+ engine_names=engine_names)++# Add a route to save search engines configuration+@research_bp.route('/api/save_search_engines_config', methods=['POST'])+def save_search_engines_config():+ try:+ data = request.get_json()+ raw_config = data.get('raw_config', '')++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({'success': False, 'error': f'TOML syntax error: {str(e)}'})++ # Ensure directory exists+ os.makedirs(os.path.dirname(SEARCH_ENGINES_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{SEARCH_ENGINES_FILE}.bak"+ if os.path.exists(SEARCH_ENGINES_FILE):+ import shutil+ shutil.copy2(SEARCH_ENGINES_FILE, backup_path)++ # Write new config+ with open(SEARCH_ENGINES_FILE, 'w') as f:+ f.write(raw_config)++ return jsonify({'success': True})+ except Exception as e:+ return jsonify({'success': False, 'error': str(e)})+++# API endpoint to save raw LLM config+@research_bp.route('/api/save_llm_config', methods=['POST'])+def save_llm_config():+ try:+ data = request.get_json()+ raw_config = data.get('raw_config', '')++ # Validate Python syntax+ try:+ compile(raw_config, '<string>', 'exec')+ except SyntaxError as e:+ return jsonify({'success': False, 'error': f'Syntax error: {str(e)}'})++ # Ensure directory exists+ os.makedirs(os.path.dirname(LLM_CONFIG_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{LLM_CONFIG_FILE}.bak"+ if os.path.exists(LLM_CONFIG_FILE):+ import shutil+ shutil.copy2(LLM_CONFIG_FILE, backup_path)++ # Write new config+ with open(LLM_CONFIG_FILE, 'w') as f:+ f.write(raw_config)++ return jsonify({'success': True})+ except Exception as e:+ return jsonify({'success': False, 'error': str(e)})++# API endpoint to save raw collections config+@research_bp.route('/api/save_collections_config', methods=['POST'])+def save_collections_config():+ try:+ data = request.get_json()+ raw_config = data.get('raw_config', '')++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({'success': False, 'error': f'TOML syntax error: {str(e)}'})++ # Ensure directory exists+ os.makedirs(os.path.dirname(LOCAL_COLLECTIONS_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{LOCAL_COLLECTIONS_FILE}.bak"+ if os.path.exists(LOCAL_COLLECTIONS_FILE):+ import shutil+ shutil.copy2(LOCAL_COLLECTIONS_FILE, backup_path)++ # Write new config+ with open(LOCAL_COLLECTIONS_FILE, 'w') as f:+ f.write(raw_config)++ # Also trigger a reload in the collections system+ try:+ load_local_collections(reload=True)+ except Exception as reload_error:+ return jsonify({'success': True, 'warning': f'Config saved, but error reloading: {str(reload_error)}'})++ return jsonify({'success': True})+ except Exception as e:+ return jsonify({'success': False, 'error': str(e)})++# API endpoint to save raw main config+@research_bp.route('/api/save_main_config', methods=['POST'])+def save_raw_main_config():+ try:+ data = request.get_json()+ raw_config = data.get('raw_config', '')++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({'success': False, 'error': f'TOML syntax error: {str(e)}'})++ # Ensure directory exists+ os.makedirs(os.path.dirname(MAIN_CONFIG_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{MAIN_CONFIG_FILE}.bak"+ if os.path.exists(MAIN_CONFIG_FILE):+ import shutil+ shutil.copy2(MAIN_CONFIG_FILE, backup_path)++ # Write new config+ with open(MAIN_CONFIG_FILE, 'w') as f:+ f.write(raw_config)++ return jsonify({'success': True})+ except Exception as e:+ return jsonify({'success': False, 'error': str(e)})+@research_bp.route('/raw_config')+def get_raw_config():+ """Return the raw configuration file content"""+ try:+ # Determine which config file to load based on a query parameter+ config_type = request.args.get('type', 'main')++ if config_type == 'main':+ config_path = os.path.join(app.config['CONFIG_DIR'], 'config.toml')+ with open(config_path, 'r') as f:+ return f.read()+ elif config_type == 'llm':+ config_path = os.path.join(app.config['CONFIG_DIR'], 'llm_config.py')+ with open(config_path, 'r') as f:+ return f.read()+ elif config_type == 'collections':+ config_path = os.path.join(app.config['CONFIG_DIR'], 'collections.toml')+ with open(config_path, 'r') as f:+ return f.read()+ else:+ return "Unknown configuration type", 400+ except Exception as e:+ return str(e), 500+import os+import subprocess+import platform++@research_bp.route('/open_file_location', methods=['POST'])+def open_file_location():+ file_path = request.form.get('file_path')++ if not file_path:+ flash('No file path provided', 'error')+ return redirect(url_for('research.settings_page'))++ # Get the directory containing the file+ dir_path = os.path.dirname(os.path.abspath(file_path))++ # Open the directory in the file explorer+ try:+ if platform.system() == "Windows":+ subprocess.Popen(f'explorer "{dir_path}"')+ elif platform.system() == "Darwin": # macOS+ subprocess.Popen(["open", dir_path])+ else: # Linux+ subprocess.Popen(["xdg-open", dir_path])++ flash(f'Opening folder: {dir_path}', 'success')+ except Exception as e:+ flash(f'Error opening folder: {str(e)}', 'error')++ # Redirect back to the settings page+ if 'llm' in file_path:+ return redirect(url_for('research.llm_config_page'))+ elif 'collections' in file_path:+ return redirect(url_for('research.collections_config_page'))+ else:+ return redirect(url_for('research.main_config_page'))++ @research_bp.route('/api/research/<int:research_id>/logs')+ def get_research_logs(research_id):+ """Get logs for a specific research ID"""+ # First check if the research exists+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute('SELECT id FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()+ conn.close()++ if not result:+ return jsonify({'status': 'error', 'message': 'Research not found'}), 404++ # Retrieve logs from the database+ logs = get_logs_for_research(research_id)++ # Add any current logs from memory if this is an active research+ if research_id in active_research and active_research[research_id].get('log'):+ # Use the logs from memory temporarily until they're saved to the database+ memory_logs = active_research[research_id]['log']++ # Filter out logs that are already in the database+ # We'll compare timestamps to avoid duplicates+ db_timestamps = {log['time'] for log in logs}+ unique_memory_logs = [log for log in memory_logs if log['time'] not in db_timestamps]++ # Add unique memory logs to our return list+ logs.extend(unique_memory_logs)++ # Sort logs by timestamp+ logs.sort(key=lambda x: x['time'])++ return jsonify({+ 'status': 'success',+ 'logs': logs+ })+++++# Register the blueprintapp.register_blueprint(research_bp)diff --cc src/local_deep_research/web/static/css/styles.cssindex 51216ba4ff,988de35d66..4acaaaef16--- a/src/local_deep_research/web/static/css/styles.css+++ b/src/local_deep_research/web/static/css/styles.css@@@ -984,31 -995,6 +995,33 @@@ textarea:focus, input[type="text"]:focumargin-top: 1rem;}- <<<<<<< HEAD:src/local_deep_research/web/static/css/styles.css++/* File path styling from the first version */+.file-path {+ background-color: #1a1a1a;+ padding: 10px;+ border-radius: 4px;+ font-family: monospace;+ margin: 15px 0;+ word-break: break-all;+ border: 1px solid #333;+}++.config-example {+ background-color: #0a0a0a;+ padding: 15px;+ border-radius: 4px;+ font-family: monospace;+ margin: 15px 0;+ overflow-x: auto;+ border: 1px solid #333;+ color: #e6e6e6;+}++.mt-4 {+ margin-top: 20px;- =======++}++++/* Try again button styling from the second version */#try-again-btn {margin-top: 15px;display: flex;@@@ -1030,5 -1016,231 +1043,231 @@@#try-again-btn i {margin-right: 5px;- >>>>>>> main:static/css/styles.css+ }+-/* Collapsible Log Panel */++/* Collapsible Log Panel styles from the third version */+ .collapsible-log-panel {+ padding: 1.5rem;+ border: 1px solid var(--border-color);+ border-radius: 8px;+ background-color: var(--bg-tertiary);+ display: flex;+ flex-direction: column;+ max-height: 40vh; /* Maximum height of 40% of viewport */+ box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);+ padding: 0;+ margin: 0;+ /* Hide by default, only show on research-progress and research-results pages */+ display: none;+ }++ /* Only show log panel on research-progress and relevant pages */+ .page#research-progress.active ~ .collapsible-log-panel,+ .page#research-results.active ~ .collapsible-log-panel {+ display: flex;+ }++ /* Adjust for smaller screens */+ @media (max-width: 991px) {+ .collapsible-log-panel {+ left: 60px; /* Adjust for collapsed sidebar */+ }+ }++ @media (max-width: 767px) {+ .collapsible-log-panel {+ left: 0; /* Full width on mobile */+ bottom: 60px; /* Account for mobile tab bar */+ }+ }++ .log-panel-header {+ display: flex;+ align-items: center;+ padding: 0.75rem 1rem;+ background: var(--gradient-bg);+ cursor: pointer;+ user-select: none;+ transition: background-color 0.2s;+ z-index: 101;+ border-radius: 8px 8px 0 0;+ }++ .log-panel-header:hover {+ background-color: var(--bg-secondary);+ }++ .log-panel-header .toggle-icon {+ margin-right: 0.75rem;+ transition: transform 0.3s ease;+ }++ .log-panel-header.collapsed .toggle-icon {+ transform: rotate(-90deg);+ }++ .log-indicator {+ margin-left: auto;+ background-color: var(--accent-primary);+ color: white;+ border-radius: 12px;+ padding: 0.1rem 0.5rem;+ font-size: 0.75rem;+ min-width: 1.5rem;+ text-align: center;+ }++ .log-panel-content {+ display: flex;+ flex-direction: column;+ overflow: hidden;+ height: calc(40vh - 40px); /* Viewport height minus header */+ transition: height 0.3s ease;+ }++ .log-panel-content.collapsed {+ height: 0 !important;+ overflow: hidden;+ padding: 0;+ margin: 0;+ border: none;+ }++ .log-controls {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.5rem 1rem;+ border-bottom: 1px solid var(--border-color);+ background-color: rgba(0, 0, 0, 0.2);+ }++ .log-filter {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ }++ .log-filter select {+ background-color: var(--bg-secondary);+ color: var(--text-primary);+ border: 1px solid var(--border-color);+ padding: 0.25rem 0.5rem;+ border-radius: 4px;+ }++ .console-log {+ padding: 0.5rem;+ font-family: 'Consolas', 'Monaco', monospace;+ font-size: 0.85rem;+ line-height: 1.4;+ overflow-y: auto;+ height: 100%;+ }++ .console-log-entry {+ padding: 0.5rem;+ display: flex;+ align-items: flex-start;+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);+ }++ .console-log-entry:hover {+ background-color: rgba(0, 0, 0, 0.2);+ }++ .console-log-entry .log-timestamp {+ color: var(--text-muted);+ min-width: 4.5rem;+ margin-right: 0.5rem;+ font-size: 0.75rem;+ }++ .console-log-entry .log-badge {+ display: inline-block;+ padding: 0 0.4rem;+ margin-right: 0.5rem;+ border-radius: 3px;+ font-size: 0.7rem;+ text-transform: uppercase;+ font-weight: bold;+ line-height: 1.4;+ }++ .console-log-entry .log-message {+ flex: 1;+ word-break: break-word;+ padding-right: 0.5rem;+ padding-left: 0.5rem;+ }++ .console-log-entry.log-milestone .log-badge {+ background-color: var(--accent-primary);+ color: white;+ }++ .console-log-entry.log-error .log-badge {+ background-color: var(--error-color);+ color: white;+ }++ .console-log-entry.log-info .log-badge {+ background-color: var(--accent-tertiary);+ color: white;+ }++ .empty-log-message {+ color: var(--text-muted);+ padding: 1rem;+ text-align: center;+ font-style: italic;+ }++ /* Add warning message styling */+ .warning-message {+ background-color: rgba(255, 193, 7, 0.1);+ color: #ffc107;+ border-color: rgba(255, 193, 7, 0.2);+ }++ /* Update existing error message styling if needed */+ .error-message {+ display: none;+ margin: 15px 0;+ padding: 10px 15px;+ border-radius: 4px;+ border-left: 4px solid;+ background-color: rgba(220, 53, 69, 0.1);+ color: #dc3545;+ border-color: rgba(220, 53, 69, 0.2);+ font-weight: 500;+ }++ .filter-buttons {+ display: flex;+ gap: 4px;+ justify-content: flex-start;+ margin-top: 0;+ }++ .small-btn {+ font-size: 0.75rem;+ padding: 4px 8px;+ background-color: var(--bg-secondary);+ color: var(--text-secondary);+ border: 1px solid var(--border-color);+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.2s;+ }++ .small-btn:hover {+ background-color: rgba(110, 79, 246, 0.2);+ color: var(--text-primary);+ }++ .small-btn.selected {+ background-color: var(--accent-primary);+ color: white;+ border-color: var(--accent-primary);}