~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
[FEAT] add web interface and local db
hashedvikingebdb3c379c4e
diff --git a/.gitignore b/.gitignoreindex 4e6bd3611a..ac9a1b2854 100644--- a/.gitignore+++ b/.gitignore@@ -21,6 +21,7 @@ wheels/*.egg# Virtual Environment+.venv/venv/ENV/env/@@ -44,3 +45,6 @@ report.md# Logs*.loglogs/++.qodo/+research_history.db\ No newline at end of filediff --git a/app.py b/app.pynew file mode 100644index 0000000000..e460acb316--- /dev/null+++ b/app.py@@ -0,0 +1,793 @@+import os+import json+import time+import sqlite3+import threading+from datetime import datetime+from flask import Flask, render_template, request, jsonify, send_from_directory, Response, make_response+from flask_socketio import SocketIO, emit+from search_system import AdvancedSearchSystem+from report_generator import IntegratedReportGenerator+from dateutil import parser+import traceback++# Initialize Flask app+app = Flask(__name__, static_folder='static')+app.config['SECRET_KEY'] = 'deep-research-secret-key'++# Add improved Socket.IO configuration with better error handling+socketio = SocketIO(+ app,+ cors_allowed_origins="*",+ ping_timeout=60,+ ping_interval=25,+ async_mode='threading',+ reconnection=True,+ reconnection_attempts=5,+ logger=True, # Enable logging+ engineio_logger=True # Enable engine.io logging+)++# Active research processes and socket subscriptions+active_research = {}+socket_subscriptions = {}++# Add termination flags dictionary+termination_flags = {}++# Database setup+DB_PATH = 'research_history.db'++# Add Content Security Policy headers to allow Socket.IO to function[email protected]_request+def add_security_headers(response):+ # Define a permissive CSP for development that allows Socket.IO to function+ csp = (+ "default-src 'self'; "+ "connect-src 'self' ws: wss: http: https:; "+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' cdnjs.cloudflare.com cdn.jsdelivr.net unpkg.com; "+ "style-src 'self' 'unsafe-inline' cdnjs.cloudflare.com; "+ "font-src 'self' cdnjs.cloudflare.com; "+ "img-src 'self' data:; "+ "worker-src blob:; "+ "frame-src 'self';"+ )++ response.headers['Content-Security-Policy'] = csp+ response.headers['X-Content-Security-Policy'] = csp++ # Add CORS headers for API requests+ if request.path.startswith('/api/'):+ response.headers['Access-Control-Allow-Origin'] = '*'+ response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, OPTIONS'+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type'++ return response++# Initialize the database+def init_db():+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()++ # Create the table if it doesn't exist+ cursor.execute('''+ CREATE TABLE IF NOT EXISTS research_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ query TEXT NOT NULL,+ mode TEXT NOT NULL,+ status TEXT NOT NULL,+ created_at TEXT NOT NULL,+ completed_at TEXT,+ duration_seconds INTEGER,+ report_path TEXT,+ metadata TEXT,+ progress_log TEXT+ )+ ''')++ # Check if the duration_seconds column exists, add it if missing+ cursor.execute('PRAGMA table_info(research_history)')+ columns = [column[1] for column in cursor.fetchall()]++ if 'duration_seconds' not in columns:+ print("Adding missing 'duration_seconds' column to research_history table")+ cursor.execute('ALTER TABLE research_history ADD COLUMN duration_seconds INTEGER')++ conn.commit()+ conn.close()++# Helper function to calculate duration between created_at and completed_at timestamps+def calculate_duration(created_at_str):+ """+ Calculate duration in seconds between created_at timestamp and now.+ Handles various timestamp formats and returns None if calculation fails.+ """+ if not created_at_str:+ return None++ now = datetime.utcnow()+ duration_seconds = None++ try:+ # Proper parsing of ISO format+ if 'T' in created_at_str: # ISO format with T separator+ start_time = datetime.fromisoformat(created_at_str)+ else: # Older format without T+ # Try different formats+ try:+ start_time = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S.%f')+ except ValueError:+ try:+ start_time = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')+ except ValueError:+ # Last resort fallback+ start_time = datetime.fromisoformat(created_at_str.replace(' ', 'T'))++ # Ensure we're comparing UTC times+ duration_seconds = int((now - start_time).total_seconds())+ except Exception as e:+ print(f"Error calculating duration: {str(e)}")+ # Fallback method if parsing fails+ try:+ start_time_fallback = parser.parse(created_at_str)+ duration_seconds = int((now - start_time_fallback).total_seconds())+ except:+ print(f"Fallback duration calculation also failed for timestamp: {created_at_str}")++ return duration_seconds++# Initialize the database on startup+# @app.before_first_request # This is deprecated in newer Flask versions+def initialize():+ init_db()++# Call initialize immediately when app is created+initialize()+[email protected]('/')+def index():+ return render_template('index.html')+[email protected]('/static/<path:path>')+def serve_static(path):+ return send_from_directory('static', path)+[email protected]('/api/history', methods=['GET'])+def get_history():+ """Get the research history"""+ try:+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()++ # Get all history records ordered by latest first+ cursor.execute('SELECT * FROM research_history ORDER BY created_at DESC')+ results = cursor.fetchall()+ conn.close()++ # Convert to list of dicts+ history = []+ for result in results:+ item = dict(result)++ # Ensure all keys exist with default values+ if 'id' not in item:+ item['id'] = None+ if 'query' not in item:+ item['query'] = 'Untitled Research'+ if 'mode' not in item:+ item['mode'] = 'quick'+ if 'status' not in item:+ item['status'] = 'unknown'+ if 'created_at' not in item:+ item['created_at'] = None+ if 'completed_at' not in item:+ item['completed_at'] = None+ if 'duration_seconds' not in item:+ item['duration_seconds'] = None+ if 'report_path' not in item:+ item['report_path'] = None+ if 'metadata' not in item:+ item['metadata'] = '{}'+ if 'progress_log' not in item:+ item['progress_log'] = '[]'++ # Ensure timestamps are in ISO format+ if item['created_at'] and 'T' not in item['created_at']:+ try:+ # Convert to ISO format if it's not already+ dt = parser.parse(item['created_at'])+ item['created_at'] = dt.isoformat()+ except:+ pass++ if item['completed_at'] and 'T' not in item['completed_at']:+ try:+ # Convert to ISO format if it's not already+ dt = parser.parse(item['completed_at'])+ item['completed_at'] = dt.isoformat()+ except:+ pass++ # Recalculate duration based on timestamps if it's null but both timestamps exist+ if item['duration_seconds'] is None and item['created_at'] and item['completed_at']:+ try:+ start_time = parser.parse(item['created_at'])+ end_time = parser.parse(item['completed_at'])+ item['duration_seconds'] = int((end_time - start_time).total_seconds())+ except Exception as e:+ print(f"Error recalculating duration: {str(e)}")++ history.append(item)++ # Add CORS headers+ response = make_response(jsonify(history))+ response.headers.add('Access-Control-Allow-Origin', '*')+ response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')+ response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')+ return response+ except Exception as e:+ print(f"Error getting history: {str(e)}")+ print(traceback.format_exc())+ # Return empty array with CORS headers+ response = make_response(jsonify([]))+ response.headers.add('Access-Control-Allow-Origin', '*')+ response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')+ response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')+ return response+[email protected]('/api/start_research', methods=['POST'])+def start_research():+ data = request.json+ query = data.get('query')+ mode = data.get('mode', 'quick')++ if not query:+ return jsonify({'status': 'error', 'message': 'Query is required'}), 400++ # Check if there's any active research+ if active_research:+ return jsonify({+ 'status': 'error',+ 'message': 'Another research is already in progress. Please wait for it to complete.'+ }), 409++ # Create a record in the database with explicit UTC timestamp+ created_at = datetime.utcnow().isoformat()+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ 'INSERT INTO research_history (query, mode, status, created_at, progress_log) VALUES (?, ?, ?, ?, ?)',+ (query, mode, 'in_progress', created_at, json.dumps([{"time": created_at, "message": "Research started", "progress": 0}]))+ )+ research_id = cursor.lastrowid+ conn.commit()+ conn.close()++ # Start research process in a background thread+ thread = threading.Thread(+ target=run_research_process,+ args=(research_id, query, mode)+ )+ thread.daemon = True+ thread.start()++ active_research[research_id] = {+ 'thread': thread,+ 'progress': 0,+ 'status': 'in_progress',+ 'log': [{"time": created_at, "message": "Research started", "progress": 0}]+ }++ return jsonify({+ 'status': 'success',+ 'research_id': research_id+ })+[email protected]('/api/research/<int:research_id>')+def get_research_status(research_id):+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))+ result = dict(cursor.fetchone() or {})+ conn.close()++ if not result:+ return jsonify({'status': 'error', 'message': 'Research not found'}), 404++ # Add progress information+ if research_id in active_research:+ result['progress'] = active_research[research_id]['progress']+ result['log'] = active_research[research_id]['log']+ elif result.get('status') == 'completed':+ result['progress'] = 100+ try:+ result['log'] = json.loads(result.get('progress_log', '[]'))+ except:+ result['log'] = []+ else:+ result['progress'] = 0+ try:+ result['log'] = json.loads(result.get('progress_log', '[]'))+ except:+ result['log'] = []++ return jsonify(result)+[email protected]('/api/research/<int:research_id>/details')+def get_research_details(research_id):+ """Get detailed progress log for a specific research"""+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))+ result = dict(cursor.fetchone() or {})+ conn.close()++ if not result:+ return jsonify({'status': 'error', 'message': 'Research not found'}), 404++ try:+ # Get the progress log+ progress_log = json.loads(result.get('progress_log', '[]'))+ except:+ progress_log = []++ # If this is an active research, get the latest log+ if research_id in active_research:+ progress_log = active_research[research_id]['log']++ return jsonify({+ 'status': 'success',+ 'research_id': research_id,+ 'query': result.get('query'),+ 'mode': result.get('mode'),+ 'status': result.get('status'),+ 'progress': active_research.get(research_id, {}).get('progress', 100 if result.get('status') == 'completed' else 0),+ 'created_at': result.get('created_at'),+ 'completed_at': result.get('completed_at'),+ 'log': progress_log+ })+[email protected]('/api/report/<int:research_id>')+def get_report(research_id):+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))+ result = dict(cursor.fetchone() or {})+ conn.close()++ if not result or not result.get('report_path'):+ return jsonify({'status': 'error', 'message': 'Report not found'}), 404++ try:+ with open(result['report_path'], 'r', encoding='utf-8') as f:+ content = f.read()+ return jsonify({+ 'status': 'success',+ 'content': content,+ 'metadata': json.loads(result.get('metadata', '{}'))+ })+ except Exception as e:+ return jsonify({'status': 'error', 'message': str(e)}), 500+[email protected]('/research/details/<int:research_id>')+def research_details_page(research_id):+ """Render the research details page"""+ return render_template('index.html')+[email protected]('connect')+def handle_connect():+ print(f"Client connected: {request.sid}")+[email protected]('disconnect')+def handle_disconnect():+ print(f"Client disconnected: {request.sid}")+ # Clean up subscriptions for this client+ for research_id, subscribers in list(socket_subscriptions.items()):+ if request.sid in subscribers:+ subscribers.remove(request.sid)+ if not subscribers:+ socket_subscriptions.pop(research_id, None)+[email protected]('subscribe_to_research')+def handle_subscribe(data):+ research_id = data.get('research_id')+ if research_id:+ if research_id not in socket_subscriptions:+ socket_subscriptions[research_id] = set()+ socket_subscriptions[research_id].add(request.sid)+ print(f"Client {request.sid} subscribed to research {research_id}")++ # Send current status immediately if available+ if research_id in active_research:+ progress = active_research[research_id]['progress']+ latest_log = active_research[research_id]['log'][-1] if active_research[research_id]['log'] else None++ if latest_log:+ emit(f'research_progress_{research_id}', {+ 'progress': progress,+ 'message': latest_log.get('message', 'Processing...'),+ 'status': 'in_progress',+ 'log_entry': latest_log+ })+[email protected]_error+def handle_socket_error(e):+ print(f"SocketIO error: {str(e)}")++def run_research_process(research_id, query, mode):+ try:+ system = AdvancedSearchSystem()++ # Set up progress callback+ def progress_callback(message, progress_percent, metadata):+ timestamp = datetime.utcnow().isoformat()+ log_entry = {+ "time": timestamp,+ "message": message,+ "progress": progress_percent,+ "metadata": metadata+ }++ # Check if termination was requested+ if research_id in termination_flags and termination_flags[research_id]:+ # Clean up and exit+ raise Exception("Research was terminated by user")++ # Update active research record+ if research_id in active_research:+ active_research[research_id]['log'].append(log_entry)+ if progress_percent is not None:+ active_research[research_id]['progress'] = progress_percent++ # Save to database (but not too frequently)+ if progress_percent is None or progress_percent % 10 == 0 or metadata.get('phase') in ['complete', 'iteration_complete']:+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ 'SELECT progress_log FROM research_history WHERE id = ?',+ (research_id,)+ )+ result = cursor.fetchone()+ if result:+ try:+ current_log = json.loads(result[0])+ except:+ current_log = []+ current_log.append(log_entry)+ cursor.execute(+ 'UPDATE research_history SET progress_log = ? WHERE id = ?',+ (json.dumps(current_log), research_id)+ )+ conn.commit()+ conn.close()++ # Emit socket event with try/except block to handle connection issues+ try:+ event_data = {+ 'progress': progress_percent,+ 'message': message,+ 'status': 'in_progress',+ 'log_entry': log_entry+ }++ # Emit to the specific research channel+ socketio.emit(f'research_progress_{research_id}', event_data)++ # Also emit to specific subscribers if available+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ for sid in socket_subscriptions[research_id]:+ try:+ socketio.emit(+ f'research_progress_{research_id}',+ event_data,+ room=sid+ )+ except Exception as sub_err:+ print(f"Error emitting to subscriber {sid}: {str(sub_err)}")++ except Exception as socket_error:+ # Log socket error but continue with the research process+ print(f"Socket emit error (non-critical): {str(socket_error)}")++ # Set the progress callback in the system+ system.set_progress_callback(progress_callback)++ # Run the search+ progress_callback("Starting research process", 5, {"phase": "init"})+ results = system.analyze_topic(query)+ progress_callback("Search complete, generating output", 80, {"phase": "output_generation"})++ # Generate output based on mode+ if mode == 'quick':+ # Quick Summary+ if results.get('findings'):+ initial_analysis = [finding['content'] for finding in results['findings']]+ summary = "\n\n".join(initial_analysis)++ # Save as markdown file+ output_dir = "research_outputs"+ if not os.path.exists(output_dir):+ os.makedirs(output_dir)++ safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[:50]+ safe_query = safe_query.replace(" ", "_").lower()+ report_path = os.path.join(output_dir, f"quick_summary_{safe_query}.md")++ with open(report_path, "w", encoding="utf-8") as f:+ f.write("# Quick Research Summary\n\n")+ f.write(f"Query: {query}\n\n")+ f.write(summary)+ f.write("\n\n## Research Metrics\n")+ f.write(f"- Search Iterations: {results['iterations']}\n")+ f.write(f"- Generated at: {datetime.utcnow().isoformat()}\n")++ # Update database+ metadata = {+ 'iterations': results['iterations'],+ 'generated_at': datetime.utcnow().isoformat()+ }++ # Calculate duration in seconds - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()++ # Use the helper function for consistent duration calculation+ duration_seconds = calculate_duration(result[0])++ # Update the record+ cursor.execute(+ 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?',+ ('completed', completed_at, duration_seconds, report_path, json.dumps(metadata), research_id)+ )+ conn.commit()+ conn.close()++ progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})+ else:+ # Full Report+ progress_callback("Generating detailed report...", 85, {"phase": "report_generation"})+ report_generator = IntegratedReportGenerator()+ final_report = report_generator.generate_report(results['findings'], query)+ progress_callback("Report generation complete", 95, {"phase": "report_complete"})++ # Save as markdown file+ output_dir = "research_outputs"+ if not os.path.exists(output_dir):+ os.makedirs(output_dir)++ safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[:50]+ safe_query = safe_query.replace(" ", "_").lower()+ report_path = os.path.join(output_dir, f"detailed_report_{safe_query}.md")++ with open(report_path, "w", encoding="utf-8") as f:+ f.write(final_report['content'])++ # Update database+ metadata = final_report['metadata']+ metadata['iterations'] = results['iterations']++ # Calculate duration in seconds - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()++ # Use the helper function for consistent duration calculation+ duration_seconds = calculate_duration(result[0])++ cursor.execute(+ 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?',+ ('completed', completed_at, duration_seconds, report_path, json.dumps(metadata), research_id)+ )+ conn.commit()+ conn.close()++ progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})++ # Clean up+ if research_id in active_research:+ del active_research[research_id]++ except Exception as e:+ # Handle error+ error_message = f"Research failed: {str(e)}"+ print(f"Research error: {error_message}")+ try:+ progress_callback(error_message, None, {"phase": "error", "error": str(e)})++ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()++ # If termination was requested, mark as suspended instead of failed+ status = 'suspended' if (research_id in termination_flags and termination_flags[research_id]) else 'failed'+ message = "Research was terminated by user" if status == 'suspended' else str(e)++ # Calculate duration up to termination point - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ duration_seconds = None+ cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()++ # Use the helper function for consistent duration calculation+ if result and result[0]:+ duration_seconds = calculate_duration(result[0])++ cursor.execute(+ 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, metadata = ? WHERE id = ?',+ (status, completed_at, duration_seconds, json.dumps({'error': message}), research_id)+ )+ conn.commit()+ conn.close()++ try:+ socketio.emit(f'research_progress_{research_id}', {+ 'status': status,+ 'error': message+ })++ # Also notify specific subscribers+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ for sid in socket_subscriptions[research_id]:+ try:+ socketio.emit(+ f'research_progress_{research_id}',+ {'status': status, 'error': message},+ room=sid+ )+ except Exception as sub_err:+ print(f"Error emitting to subscriber {sid}: {str(sub_err)}")++ except Exception as socket_error:+ print(f"Failed to emit error via socket: {str(socket_error)}")+ except Exception as inner_e:+ print(f"Error in error handler: {str(inner_e)}")++ # Clean up resources+ if research_id in active_research:+ del active_research[research_id]+ if research_id in termination_flags:+ del termination_flags[research_id]+[email protected]('/api/research/<int:research_id>/terminate', methods=['POST'])+def terminate_research(research_id):+ """Terminate an in-progress research process"""++ # Check if the research exists and is in progress+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute('SELECT status FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()++ if not result:+ conn.close()+ return jsonify({'status': 'error', 'message': 'Research not found'}), 404++ status = result[0]++ # If it's not in progress, return an error+ if status != 'in_progress':+ conn.close()+ return jsonify({'status': 'error', 'message': 'Research is not in progress'}), 400++ # Check if it's in the active_research dict+ if research_id not in active_research:+ # Update the status in the database+ cursor.execute('UPDATE research_history SET status = ? WHERE id = ?', ('suspended', research_id))+ conn.commit()+ conn.close()+ return jsonify({'status': 'success', 'message': 'Research terminated'})++ # Set the termination flag+ termination_flags[research_id] = True++ # Log the termination request - using UTC timestamp+ timestamp = datetime.utcnow().isoformat()+ log_entry = {+ "time": timestamp,+ "message": "Research termination requested by user",+ "progress": active_research[research_id]['progress'],+ "metadata": {"phase": "termination"}+ }++ active_research[research_id]['log'].append(log_entry)++ # Update the log in the database+ cursor.execute('SELECT progress_log FROM research_history WHERE id = ?', (research_id,))+ log_result = cursor.fetchone()+ if log_result:+ try:+ current_log = json.loads(log_result[0])+ except:+ current_log = []+ current_log.append(log_entry)+ cursor.execute(+ 'UPDATE research_history SET progress_log = ? WHERE id = ?',+ (json.dumps(current_log), research_id)+ )++ conn.commit()+ conn.close()++ # Emit a socket event for the termination request+ try:+ event_data = {+ 'status': 'terminating',+ 'message': 'Research termination requested by user'+ }++ socketio.emit(f'research_progress_{research_id}', event_data)++ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ for sid in socket_subscriptions[research_id]:+ try:+ socketio.emit(+ f'research_progress_{research_id}',+ event_data,+ room=sid+ )+ except Exception as err:+ print(f"Error emitting to subscriber {sid}: {str(err)}")++ except Exception as socket_error:+ print(f"Socket emit error (non-critical): {str(socket_error)}")++ return jsonify({'status': 'success', 'message': 'Research termination requested'})+[email protected]('/api/research/<int:research_id>/delete', methods=['DELETE'])+def delete_research(research_id):+ """Delete a research record"""+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()++ # First check if the research exists and is not in progress+ cursor.execute('SELECT status, report_path FROM research_history WHERE id = ?', (research_id,))+ result = cursor.fetchone()++ if not result:+ conn.close()+ return jsonify({'status': 'error', 'message': 'Research not found'}), 404++ status, report_path = result++ # Don't allow deleting research in progress+ if status == 'in_progress' and research_id in active_research:+ conn.close()+ return jsonify({+ 'status': 'error',+ 'message': 'Cannot delete research that is in progress'+ }), 400++ # Delete report file if it exists+ if report_path and os.path.exists(report_path):+ try:+ os.remove(report_path)+ except Exception as e:+ print(f"Error removing report file: {str(e)}")++ # Delete the database record+ cursor.execute('DELETE FROM research_history WHERE id = ?', (research_id,))+ conn.commit()+ conn.close()++ return jsonify({'status': 'success'})++if __name__ == '__main__':+ # Set server name explicitly to avoid DNS resolution issues+ socketio.run(app, debug=True, host='127.0.0.1', port=5000, allow_unsafe_werkzeug=True)\ No newline at end of filediff --git a/config.py b/config.pyindex 7362afd7d4..540bfaa564 100644--- a/config.py+++ b/config.py@@ -13,7 +13,7 @@ load_dotenv()# LLM ConfigurationDEFAULT_MODEL = "deepseek-r1:14b" # try to use the largest model that fits into your GPU memoryDEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 8000+MAX_TOKENS = 15000# Search System SettingsSEARCH_ITERATIONS = 3@@ -27,7 +27,7 @@ CONTEXT_CUT_OFF = 10000ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?# DDG FACT CHECK URLs-QUALITY_CHECK_DDG_URLS = True # Keep this True it improves quality of the results in my experiance.+QUALITY_CHECK_DDG_URLS = True # Keep this True it improves quality of the results in my experience.# Search ConfigurationMAX_SEARCH_RESULTS = 40 # DuckDuckGoSearch seems to return only 4 results anyways.@@ -64,7 +64,7 @@ def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):return ChatOpenAI(model=model_name, api_key=api_key, **common_params)else:- return ChatOllama(model=model_name, **common_params)+ return ChatOllama(model=model_name, base_url="http://localhost:11434", **common_params)def get_search():diff --git a/requirements.txt b/requirements.txtindex 035a12a0ae..b632df916f 100644--- a/requirements.txt+++ b/requirements.txt@@ -10,3 +10,8 @@ typing_extensions>=4.12.2justextplaywrightbeautifulsoup4+# Web interface requirements+flask>=2.0.1+flask-cors>=3.0.10+flask-socketio>=5.1.1+sqlalchemy>=1.4.23diff --git a/search_system.py b/search_system.pyindex 9e1d299d58..15a87d898b 100644--- a/search_system.py+++ b/search_system.py@@ -1,4 +1,4 @@-from typing import Dict, List+from typing import Dict, List, Optional, Callablefrom datetime import datetimefrom utilities import remove_think_tags, format_findings_to_text, print_search_resultsimport os@@ -7,8 +7,6 @@ from citation_handler import CitationHandlerfrom datetime import datetime--class AdvancedSearchSystem:def __init__(self):self.search = get_search()@@ -18,10 +16,33 @@ class AdvancedSearchSystem:self.context_limit = 5000self.questions_by_iteration = {}self.citation_handler = CitationHandler(self.model)+ self.progress_callback = None++ def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:+ """Set a callback function to receive progress updates.++ Args:+ callback: Function that takes (message, progress_percent, metadata)+ """+ self.progress_callback = callback++ def _update_progress(self, message: str, progress_percent: int = None, metadata: dict = None) -> None:+ """Send a progress update via the callback if available.++ Args:+ message: Description of the current progress state+ progress_percent: Progress percentage (0-100), if applicable+ metadata: Additional data about the progress state+ """+ if self.progress_callback:+ self.progress_callback(message, progress_percent, metadata or {})def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:now = datetime.now()current_time = now.strftime("%Y-%m-%d")++ self._update_progress("Generating follow-up questions...", None, {"iteration": len(self.questions_by_iteration)})+if self.questions_by_iteration:prompt = f"""Critically reflect current knowledge (e.g., timeliness), what {self.questions_per_iteration} high-quality internet search questions remain unanswered to exactly answer the query?Query: {query}@@ -34,13 +55,23 @@ class AdvancedSearchSystem:prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {self.questions_per_iteration} high-quality internet search questions to exactly answer: {query}\n\n\nFormat: One question per line, e.g. \n Q: question1 \n Q: question2\n\n"response = self.model.invoke(prompt)- return [+ questions = [q.replace("Q:", "").strip()for q in remove_think_tags(response.content).split("\n")if q.strip().startswith("Q:")][: self.questions_per_iteration]++ self._update_progress(+ f"Generated {len(questions)} follow-up questions",+ None,+ {"questions": questions}+ )++ return questionsdef _compress_knowledge(self, current_knowledge: str, query: str) -> List[str]:+ self._update_progress("Compressing and summarizing knowledge...", None)+now = datetime.now()current_time = now.strftime("%Y-%m-%d")if self.questions_by_iteration:@@ -50,33 +81,65 @@ class AdvancedSearchSystem:Query: {query}\n\n\nFormat: text summary\n\n"""response = self.model.invoke(prompt)++ self._update_progress("Knowledge compression complete", None)return remove_think_tags(response.content)def analyze_topic(self, query: str) -> Dict:findings = []current_knowledge = ""iteration = 0+ total_iterations = self.max_iterations++ self._update_progress("Initializing research system", 5, {+ "phase": "init",+ "iterations_planned": total_iterations+ })while iteration < self.max_iterations:+ iteration_progress_base = (iteration / total_iterations) * 100+ self._update_progress(f"Starting iteration {iteration + 1} of {total_iterations}",+ int(iteration_progress_base),+ {"phase": "iteration_start", "iteration": iteration + 1})++ # Generate questions for this iterationquestions = self._get_follow_up_questions(current_knowledge, query)self.questions_by_iteration[iteration] = questions- for question in questions:++ question_count = len(questions)+ for q_idx, question in enumerate(questions):+ question_progress_base = iteration_progress_base + (((q_idx+1) / question_count) * (100/total_iterations) * 0.5)++ self._update_progress(f"Searching for: {question}",+ int(question_progress_base),+ {"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})+search_results = self.search.run(question)limited_knowledge = (current_knowledge[-self.context_limit :]if len(current_knowledge) > self.context_limitelse current_knowledge)++ self._update_progress(f"Found {len(search_results)} results for question: {question}",+ int(question_progress_base + 2),+ {"phase": "search_complete", "result_count": len(search_results)})+print("len search", len(search_results))- # print(search_results)+if len(search_results) == 0:continueprint_search_results(search_results) # only links+ self._update_progress(f"Analyzing results for: {question}",+ int(question_progress_base + 5),+ {"phase": "analysis"})+result = self.citation_handler.analyze_followup(question, search_results, limited_knowledge)+if result is not None:findings.append({@@ -88,11 +151,27 @@ class AdvancedSearchSystem:})current_knowledge += f"\n\n{result['content']}"++ self._update_progress(f"Analysis complete for question: {question}",+ int(question_progress_base + 10),+ {"phase": "analysis_complete"})iteration += 1++ self._update_progress(f"Compressing knowledge after iteration {iteration}",+ int((iteration / total_iterations) * 100 - 5),+ {"phase": "knowledge_compression"})+current_knowledge = self._compress_knowledge(current_knowledge, query)++ self._update_progress(f"Iteration {iteration} complete",+ int((iteration / total_iterations) * 100),+ {"phase": "iteration_complete", "iteration": iteration})+self._save_findings(findings, current_knowledge, query)+ self._update_progress("Research complete", 95, {"phase": "complete"})+return {"findings": findings,"iterations": iteration,@@ -100,6 +179,8 @@ class AdvancedSearchSystem:}def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):+ self._update_progress("Saving research findings...", None)+formatted_findings = format_findings_to_text(findings, current_knowledge, self.questions_by_iteration)@@ -116,3 +197,5 @@ class AdvancedSearchSystem:with open(filename, "w", encoding="utf-8") as text_file:text_file.write(formatted_findings)++ self._update_progress("Research findings saved", None, {"filename": filename})diff --git a/static/css/styles.css b/static/css/styles.cssnew file mode 100644index 0000000000..2fddd9dca7--- /dev/null+++ b/static/css/styles.css@@ -0,0 +1,955 @@+/* Modern AI-themed dark interface */+:root {+ --bg-primary: #121212;+ --bg-secondary: #1e1e2d;+ --bg-tertiary: #2a2a3a;+ --accent-primary: #6e4ff6;+ --accent-secondary: #9179f0;+ --accent-tertiary: #40bfff;+ --text-primary: #f5f5f5;+ --text-secondary: #c0c0cc;+ --text-muted: #8a8aa0;+ --border-color: #343452;+ --success-color: #0acf97;+ --warning-color: #f9bc0b;+ --error-color: #fa5c7c;+ --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);+ --glow-effect: 0 0 15px rgba(110, 79, 246, 0.3);+ --gradient-bg: linear-gradient(135deg, #2a2a3a 0%, #1e1e2d 100%);+}++/* Reset and Base Styles */+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++body {+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ background-color: var(--bg-primary);+ color: var(--text-primary);+ line-height: 1.6;+ overflow-x: hidden;+}++a {+ color: var(--accent-tertiary);+ text-decoration: none;+ transition: color 0.2s;+}++a:hover {+ color: var(--accent-secondary);+}++/* Layout */+.app-container {+ display: flex;+ min-height: 100vh;+}++/* Sidebar */+.sidebar {+ width: 240px;+ background-color: var(--bg-secondary);+ border-right: 1px solid var(--border-color);+ display: flex;+ flex-direction: column;+ position: fixed;+ height: 100vh;+ z-index: 10;+}++.sidebar-header {+ padding: 1.5rem;+ border-bottom: 1px solid var(--border-color);+}++.sidebar-header h2 {+ display: flex;+ align-items: center;+ font-weight: 600;+ font-size: 1.25rem;+ gap: 0.5rem;+ color: var(--accent-secondary);+}++.sidebar-header h2 i {+ color: var(--accent-primary);+}++.sidebar-nav {+ flex: 1;+ padding: 1rem 0;+}++.sidebar-nav ul {+ list-style: none;+}++.sidebar-nav li {+ padding: 0.75rem 1.5rem;+ margin-bottom: 0.25rem;+ cursor: pointer;+ display: flex;+ align-items: center;+ gap: 0.75rem;+ color: var(--text-secondary);+ border-left: 3px solid transparent;+ transition: all 0.2s;+}++.sidebar-nav li i {+ width: 20px;+}++.sidebar-nav li:hover {+ background-color: var(--bg-tertiary);+ color: var(--text-primary);+}++.sidebar-nav li.active {+ color: var(--accent-primary);+ background-color: rgba(110, 79, 246, 0.1);+ border-left-color: var(--accent-primary);+}++.sidebar-footer {+ padding: 1rem 1.5rem;+ border-top: 1px solid var(--border-color);+ color: var(--text-muted);+ font-size: 0.875rem;+ display: flex;+ justify-content: center;+}++/* Main Content */+.main-content {+ flex: 1;+ padding: 1.0rem 2rem 2rem 2rem;+ margin-left: 240px;+ width: calc(100% - 240px);+}++.page {+ display: none;+}++.page.active {+ display: block;+ animation: fadeIn 0.3s ease;+}++@keyframes fadeIn {+ from { opacity: 0; }+ to { opacity: 1; }+}++.page-header {+ margin-bottom: 1.5rem;+}++.page-header h1 {+ font-weight: 600;+ font-size: 1.75rem;+ color: var(--text-primary);+}++/* Cards */+.card {+ background-color: var(--bg-secondary);+ border-radius: 12px;+ box-shadow: var(--card-shadow);+ margin-bottom: 1.5rem;+ overflow: hidden;+ border: 1px solid var(--border-color);+}++.card-content {+ padding: 1.5rem;+}++/* Form Elements */+.form-group {+ margin-bottom: 1.5rem;+}++.form-group label {+ display: block;+ margin-bottom: 0.5rem;+ font-weight: 500;+ color: var(--text-secondary);+}++textarea, input[type="text"] {+ width: 100%;+ padding: 0.75rem;+ border-radius: 8px;+ border: 1px solid var(--border-color);+ background-color: var(--bg-tertiary);+ color: var(--text-primary);+ font-family: inherit;+ font-size: 0.95rem;+ resize: vertical;+ transition: border-color 0.2s, box-shadow 0.2s;+}++textarea:focus, input[type="text"]:focus {+ outline: none;+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.2);+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 0.5rem;+ padding: 0.75rem 1.25rem;+ border-radius: 8px;+ font-weight: 500;+ font-size: 0.95rem;+ cursor: pointer;+ transition: all 0.2s;+ border: none;+}++.btn-sm {+ padding: 0.5rem 1rem;+ font-size: 0.85rem;+}++.btn-primary {+ background-color: var(--accent-primary);+ color: white;+}++.btn-primary:hover {+ background-color: var(--accent-secondary);+ box-shadow: var(--glow-effect);+}++.btn-outline {+ background-color: transparent;+ color: var(--accent-tertiary);+ border: 1px solid var(--accent-tertiary);+}++.btn-outline:hover {+ background-color: rgba(64, 191, 255, 0.1);+}++.delete-btn {+ color: var(--error-color);+ border-color: var(--error-color);+}++.delete-btn:hover {+ background-color: rgba(250, 92, 124, 0.1);+}++.terminate-btn {+ color: #e74c3c;+ border-color: #e74c3c;+}++.terminate-btn:hover {+ background-color: rgba(231, 76, 60, 0.1);+}++.btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ pointer-events: none;+}++.form-actions {+ display: flex;+ justify-content: flex-end;+}++/* Mode Selection */+.mode-selection {+ display: flex;+ gap: 1rem;+}++.mode-option {+ flex: 1;+ background-color: var(--bg-tertiary);+ border-radius: 8px;+ padding: 1.25rem;+ border: 2px solid transparent;+ cursor: pointer;+ transition: all 0.2s;+ display: flex;+ align-items: center;+ gap: 1rem;+}++.mode-option:hover {+ background-color: var(--bg-primary);+}++.mode-option.active {+ border-color: var (--accent-primary);+ background-color: rgba(110, 79, 246, 0.1);+}++.mode-icon {+ width: 40px;+ height: 40px;+ background-color: var(--accent-primary);+ color: white;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 1.2rem;+}++.mode-option.active .mode-icon {+ background-color: var(--accent-secondary);+ box-shadow: var(--glow-effect);+}++.mode-info h3 {+ margin-bottom: 0.25rem;+ color: var(--text-primary);+}++.mode-info p {+ color: var(--text-muted);+ font-size: 0.85rem;+}++/* Progress Bar */+.progress-container {+ margin: 1.5rem 0;+ display: flex;+ align-items: center;+ gap: 1rem;+}++.progress-bar {+ flex: 1;+ height: 12px;+ background-color: var(--bg-tertiary);+ border-radius: 6px;+ overflow: hidden;+}++.progress-fill {+ height: 100%;+ width: 0%;+ background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));+ border-radius: 6px;+ transition: width 0.5s ease;+}++.progress-text {+ width: 60px;+ text-align: right;+ font-weight: 600;+ color: var(--accent-secondary);+}++.query-display {+ margin-bottom: 1.5rem;+}++.query-display h3 {+ color: var(--text-secondary);+ font-size: 1rem;+ margin-bottom: 0.5rem;+}++.query-display p {+ color: var(--text-primary);+ font-weight: 500;+}++.progress-info {+ color: var(--text-secondary);+ font-size: 0.9rem;+}++/* History List */+.history-list {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.history-item {+ background-color: var(--bg-tertiary);+ border-radius: 8px;+ padding: 1rem;+ border: 1px solid var(--border-color);+ transition: all 0.2s;+ cursor: pointer;+ position: relative;+}++.history-item:hover {+ border-color: var(--accent-tertiary);+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);+}++.history-item-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.5rem;+}++.history-item-title {+ font-weight: 500;+ color: var(--text-primary);+}++.history-item-status {+ font-size: 0.8rem;+ padding: 0.25rem 0.5rem;+ border-radius: 4px;+ font-weight: 500;+}++.status-completed {+ background-color: rgba(10, 207, 151, 0.15);+ color: var(--success-color);+}++.status-in-progress {+ background-color: rgba(249, 188, 11, 0.15);+ color: var(--warning-color);+}++.status-failed {+ background-color: rgba(250, 92, 124, 0.15);+ color: var(--error-color);+}++.status-suspended {+ color: #f39c12;+}++.status-terminating {+ background-color: rgba(231, 76, 60, 0.15);+ color: #e74c3c;+ animation: pulse 1.5s infinite;+}++@keyframes pulse {+ 0% { opacity: 0.7; }+ 50% { opacity: 1; }+ 100% { opacity: 0.7; }+}++.history-item-meta {+ display: flex;+ color: var(--text-muted);+ font-size: 0.85rem;+ margin-bottom: 0.75rem;+}++.history-item-date {+ margin-right: 1rem;+}++.history-item-mode {+ display: flex;+ align-items: center;+ gap: 0.25rem;+}++.history-item-actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.5rem;+ position: relative;+ z-index: 5;+}++.history-item-actions button {+ position: relative;+ z-index: 10;+}++/* Results Page */+.results-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.results-metadata {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ margin-bottom: 1.5rem;+ padding-bottom: 1rem;+ border-bottom: 1px solid var(--border-color);+}++.metadata-item {+ display: flex;+ flex-direction: column;+}++.metadata-label {+ font-size: 0.85rem;+ color: var(--text-muted);+ margin-bottom: 0.25rem;+}++.metadata-value {+ color: var(--text-primary);+ font-weight: 500;+}++.results-content {+ line-height: 1.7;+}++.results-content h1 {+ font-size: 1.75rem;+ margin: 1.5rem 0 1rem;+ color: var(--text-primary);+}++.results-content h2 {+ font-size: 1.5rem;+ margin: 1.25rem 0 0.75rem;+ color: var(--accent-tertiary);+}++.results-content h3 {+ font-size: 1.25rem;+ margin: 1rem 0 0.5rem;+ color: var(--accent-secondary);+}++.results-content p {+ margin-bottom: 1rem;+ color: var(--text-secondary);+}++.results-content ul,+.results-content ol {+ margin-bottom: 1rem;+ padding-left: 1.5rem;+ color: var(--text-secondary);+}++.results-content li {+ margin-bottom: 0.5rem;+}++.results-content code {+ background-color: var(--bg-tertiary);+ padding: 0.15rem 0.3rem;+ border-radius: 4px;+ font-family: 'SF Mono', 'Menlo', 'Monaco', 'Courier New', monospace;+ font-size: 0.9em;+}++.results-content pre {+ background-color: var(--bg-tertiary);+ border-radius: 8px;+ padding: 1rem;+ margin-bottom: 1rem;+ overflow-x: auto;+}++.results-content blockquote {+ border-left: 3px solid var(--accent-primary);+ padding-left: 1rem;+ margin-left: 0;+ margin-bottom: 1rem;+ color: var(--text-muted);+}++.results-content table {+ width: 100%;+ border-collapse: collapse;+ margin-bottom: 1rem;+}++.results-content th {+ background-color: var(--bg-tertiary);+ text-align: left;+ padding: 0.75rem;+ border-bottom: 2px solid var(--border-color);+ color: var(--accent-tertiary);+}++.results-content td {+ padding: 0.75rem;+ border-bottom: 1px solid var(--border-color);+ color: var(--text-secondary);+}++/* Research Details Page */+.research-metadata {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));+ gap: 1.5rem;+ margin-bottom: 1.5rem;+ padding-bottom: 1rem;+ border-bottom: 1px solid var(--border-color);+}++.detail-progress-container {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++.detail-progress-bar {+ flex: 1;+ height: 8px;+ background-color: var(--bg-tertiary);+ border-radius: 4px;+ overflow: hidden;+}++.detail-progress-fill {+ height: 100%;+ width: 0%;+ background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));+ border-radius: 4px;+ transition: width 0.5s ease;+}++.research-log-container {+ margin-top: 1.5rem;+}++.research-log-container h3 {+ margin-bottom: 1rem;+ color: var(--text-secondary);+ font-size: 1.1rem;+ font-weight: 500;+}++.research-log {+ max-height: 500px;+ overflow-y: auto;+ padding: 1rem;+ background-color: var(--bg-tertiary);+ border-radius: 8px;+ border: 1px solid var(--border-color);+}++.log-entry {+ padding: 0.75rem;+ border-bottom: 1px solid var(--border-color);+ display: flex;+ gap: 1rem;+}++.log-entry:last-child {+ border-bottom: none;+}++.log-entry-time {+ font-size: 0.8rem;+ color: var(--text-muted);+ min-width: 80px;+}++.log-entry-content {+ flex: 1;+}++.log-entry-message {+ color: var(--text-secondary);+ margin-bottom: 0.25rem;+}++.log-entry-progress {+ font-size: 0.85rem;+ color: var(--accent-secondary);+ font-weight: 500;+}++.detail-actions {+ margin-top: 1.5rem;+ display: flex;+ justify-content: center;+ gap: 1rem;+}++.phase-highlight {+ color: var(--accent-tertiary);+ font-weight: 500;+}++.phase-init {+ color: var(--accent-tertiary);+}++.phase-search {+ color: var(--accent-secondary);+}++.phase-analysis {+ color: var(--warning-color);+}++.phase-complete {+ color: var(--success-color);+}++.phase-error {+ color: var(--error-color);+}++.phase-termination {+ color: #e74c3c;+ font-weight: bold;+}++.empty-state {+ padding: 2rem;+ text-align: center;+ color: var(--text-muted);+ font-style: italic;+}++.error-message {+ padding: 1rem;+ background-color: rgba(250, 92, 124, 0.1);+ border: 1px solid var(--error-color);+ border-radius: 8px;+ color: var(--error-color);+ margin: 1rem 0;+ font-size: 0.9rem;+}++/* Loading Spinner */+.loading-spinner {+ padding: 2rem 0;+}++.loading-spinner.centered {+ display: flex;+ justify-content: center;+ align-items: center;+}++.spinner {+ width: 40px;+ height: 40px;+ border: 4px solid rgba(110, 79, 246, 0.2);+ border-left-color: var(--accent-primary);+ border-radius: 50%;+ animation: spin 1s linear infinite;+}++@keyframes spin {+ to { transform: rotate(360deg); }+}++/* Mobile Tab Bar */+.mobile-tab-bar {+ display: none; /* Hidden by default */+ position: fixed;+ bottom: 0;+ left: 0;+ right: 0;+ height: 60px;+ background-color: var(--bg-secondary);+ border-top: 1px solid var(--border-color);+ z-index: 1000;+ box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);+}++.mobile-tab-bar ul {+ display: flex;+ height: 100%;+ list-style: none;+ padding: 0;+ margin: 0;+ width: 100%;+}++.mobile-tab-bar li {+ flex: 1;+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ cursor: pointer;+ color: var(--text-secondary);+ transition: all 0.2s;+ padding: 0.5rem 0;+ min-width: 90px;+}++.mobile-tab-bar li i {+ font-size: 1.3rem;+ margin-bottom: 8px;+}++.mobile-tab-bar li span {+ font-size: 0.75rem;+ text-align: center;+ width: 100%;+}++.mobile-tab-bar li.active {+ color: var(--accent-primary);+}++.mobile-tab-bar li:hover {+ color: var(--text-primary);+}++/* Responsive */+@media (max-width: 991px) {+ .sidebar {+ width: 60px;+ overflow: hidden;+ }++ /* Hide all text in the logo and center icon */+ .sidebar-header {+ padding: 1rem 0;+ text-align: center;+ display: flex;+ align-items: center;+ justify-content: center;+ height: 60px;+ }++ .sidebar-header h2 {+ font-size: 0;+ display: flex;+ justify-content: center;+ width: 100%;+ }++ .sidebar-header h2 i {+ font-size: 1.4rem;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ /* Hide all text in nav items and center icons */+ .sidebar-nav {+ display: flex;+ flex-direction: column;+ padding-top: 0.5rem;+ }++ .sidebar-nav ul {+ width: 100%;+ }++ .sidebar-nav li {+ text-indent: -9999px;+ white-space: nowrap;+ padding: 1rem 0;+ text-align: center;+ height: 60px;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ .sidebar-nav li i {+ text-indent: 0;+ margin: 0;+ font-size: 1.3rem;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ /* Active state fix for icon view */+ .sidebar-nav li.active {+ border-left-width: 3px;+ }++ /* Hide footer */+ .sidebar-footer {+ display: none;+ }++ /* Adjust main content */+ .main-content {+ margin-left: 60px;+ width: calc(100% - 60px);+ }++ .mode-selection {+ flex-direction: column;+ }+}++@media (max-width: 767px) {+ body {+ padding-bottom: 60px; /* Add padding to body for the tab bar */+ }++ .main-content {+ padding: 1rem;+ padding-bottom: 70px; /* Add padding for the tab bar */+ margin-left: 0;+ width: 100%;+ }++ .sidebar {+ width: 0;+ transform: translateX(-100%);+ }++ .sidebar.active {+ width: 240px;+ transform: translateX(0);+ }++ /* Restore text in logo when sidebar is active on mobile */+ .sidebar.active .sidebar-header h2 {+ font-size: 1.25rem;+ }++ /* Restore text in nav items when sidebar is active on mobile */+ .sidebar.active .sidebar-nav li {+ text-indent: 0;+ padding: 0.75rem 1.5rem;+ text-align: left;+ }++ .sidebar.active .sidebar-nav li i {+ display: inline;+ width: 20px;+ margin-right: 0.75rem;+ font-size: 1rem;+ }++ .sidebar.active .sidebar-footer {+ display: flex;+ }++ /* Show mobile tab bar */+ .mobile-tab-bar {+ display: flex !important; /* Use !important to ensure it displays */+ }+}++.progress-status {+ margin-bottom: 1.25rem;+ padding: 0.5rem 0;+ font-weight: 500;+}++.progress-actions {+ display: flex;+ justify-content: center;+ margin-top: 1rem;+}\ No newline at end of filediff --git a/static/js/app.js b/static/js/app.jsnew file mode 100644index 0000000000..afd4121254--- /dev/null+++ b/static/js/app.js@@ -0,0 +1,1550 @@+// Main application functionality+document.addEventListener('DOMContentLoaded', () => {+ // Initialize socket.io connection with proper error handling and reconnection options+ const socket = io({+ reconnection: true,+ reconnectionAttempts: 5,+ reconnectionDelay: 1000,+ reconnectionDelayMax: 5000,+ timeout: 20000,+ autoConnect: true+ });++ // Socket connection event handlers+ socket.on('connect', () => {+ console.log('Socket.IO connected successfully');+ });++ socket.on('connect_error', (error) => {+ console.error('Socket.IO connection error:', error);+ // The connection will automatically try to reconnect due to our config+ });++ socket.on('reconnect', (attemptNumber) => {+ console.log(`Socket.IO reconnected after ${attemptNumber} attempts`);+ });++ socket.on('reconnect_error', (error) => {+ console.error('Socket.IO reconnection error:', error);+ });++ // Navigation+ const navItems = document.querySelectorAll('.sidebar-nav li');+ const mobileNavItems = document.querySelectorAll('.mobile-tab-bar li');+ const pages = document.querySelectorAll('.page');+ const mobileTabBar = document.querySelector('.mobile-tab-bar');++ // Handle responsive navigation based on screen size+ function handleResponsiveNavigation() {+ // Mobile tab bar should only be visible on small screens+ if (window.innerWidth <= 767) {+ if (mobileTabBar) {+ mobileTabBar.style.display = 'flex';+ }+ } else {+ if (mobileTabBar) {+ mobileTabBar.style.display = 'none';+ }+ }+ }++ // Call on initial load+ handleResponsiveNavigation();++ // Set up window resize listener+ window.addEventListener('resize', handleResponsiveNavigation);++ // Initialize modal research id+ let currentResearchId = null;+ let isResearchInProgress = false;++ // Expose the currentResearchId and termination function to the window object for the inline script+ window.currentResearchId = null;++ // Track termination status+ let isTerminating = false;++ // Check if we're on the history page and load history if needed+ const historyPage = document.getElementById('history');+ if (historyPage && historyPage.classList.contains('active')) {+ // Use setTimeout to ensure the DOM is fully loaded+ setTimeout(() => loadResearchHistory(), 100);+ }++ // Function to terminate research - exposed to window object+ async function terminateResearch(researchId) {+ if (!researchId) {+ console.error('No research ID provided for termination');+ return;+ }++ // Prevent multiple termination requests+ if (isTerminating) {+ console.log('Termination already in progress');+ return;+ }++ // Confirm with the user+ if (!confirm('Are you sure you want to terminate this research? This action cannot be undone.')) {+ return;+ }++ try {+ // Set terminating flag+ isTerminating = true;++ // Update UI to show we're processing+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.disabled = true;+ terminateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';+ }++ // Find all terminate buttons in history items and disable them+ const allTerminateBtns = document.querySelectorAll('.terminate-btn');+ allTerminateBtns.forEach(btn => {+ if (btn !== terminateBtn) {+ btn.disabled = true;+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';+ }+ });++ // Call the terminate API+ const response = await fetch(`/api/research/${researchId}/terminate`, {+ method: 'POST'+ });++ const data = await response.json();++ if (data.status === 'success') {+ // The UI will be updated via socket events or polling+ console.log('Termination request sent successfully');++ // If we're on the history page, update the status of this item+ if (document.getElementById('history').classList.contains('active')) {+ updateHistoryItemStatus(researchId, 'terminating', 'Terminating...');+ }+ } else {+ console.error('Termination request failed:', data.message);+ alert(`Failed to terminate research: ${data.message}`);++ // Reset the terminating flag+ isTerminating = false;++ // Reset the button+ if (terminateBtn) {+ terminateBtn.disabled = false;+ terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';+ }++ // Reset history button states+ const allTerminateBtns = document.querySelectorAll('.terminate-btn');+ allTerminateBtns.forEach(btn => {+ if (btn !== terminateBtn) {+ btn.disabled = false;+ btn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate';+ }+ });+ }+ } catch (error) {+ console.error('Error terminating research:', error);+ alert('An error occurred while trying to terminate the research.');++ // Reset the terminating flag+ isTerminating = false;++ // Reset the button+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.disabled = false;+ terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';+ }++ // Reset history button states+ const allTerminateBtns = document.querySelectorAll('.terminate-btn');+ allTerminateBtns.forEach(btn => {+ if (btn !== terminateBtn) {+ btn.disabled = false;+ btn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate';+ }+ });+ }+ }++ // Expose the terminate function to the window object+ window.terminateResearch = terminateResearch;++ // Function to switch pages+ function switchPage(pageId) {+ pages.forEach(page => {+ page.classList.remove('active');+ });++ const targetPage = document.getElementById(pageId);+ if (targetPage) {+ targetPage.classList.add('active');+ }++ // Update sidebar navigation active states+ navItems.forEach(item => {+ if (item.getAttribute('data-page') === pageId) {+ item.classList.add('active');+ } else {+ item.classList.remove('active');+ }+ });++ // Update mobile tab bar active states+ mobileNavItems.forEach(item => {+ if (item.getAttribute('data-page') === pageId) {+ item.classList.add('active');+ } else {+ item.classList.remove('active');+ }+ });+ }++ // Setup navigation click handlers+ navItems.forEach(item => {+ item.addEventListener('click', () => {+ const pageId = item.getAttribute('data-page');+ switchPage(pageId);++ // Load history data when navigating to history page+ if (pageId === 'history') {+ loadResearchHistory();+ }+ });+ });++ // Setup mobile navigation click handlers+ mobileNavItems.forEach(item => {+ item.addEventListener('click', () => {+ const pageId = item.getAttribute('data-page');+ switchPage(pageId);++ // Load history data when navigating to history page+ if (pageId === 'history') {+ loadResearchHistory();+ }+ });+ });++ // Handle logo click to return to home page+ const logoLink = document.getElementById('logo-link');+ if (logoLink) {+ logoLink.addEventListener('click', () => {+ switchPage('new-research');+ });+ }++ // Mode selection+ const modeOptions = document.querySelectorAll('.mode-option');+ let selectedMode = 'quick';++ modeOptions.forEach(option => {+ option.addEventListener('click', () => {+ modeOptions.forEach(opt => opt.classList.remove('active'));+ option.classList.add('active');+ selectedMode = option.getAttribute('data-mode');+ });+ });++ // Form submission+ const researchForm = document.getElementById('research-form');+ const startResearchBtn = document.getElementById('start-research-btn');++ researchForm.addEventListener('submit', async (e) => {+ e.preventDefault();++ if (isResearchInProgress) {+ alert('Another research is already in progress. Please wait for it to complete or check its status in the history tab.');+ return;+ }++ const queryInput = document.getElementById('query');+ const query = queryInput.value.trim();++ if (!query) {+ alert('Please enter a research query');+ return;+ }++ // Disable the start button while we attempt to start the research+ startResearchBtn.disabled = true;+ startResearchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';++ try {+ const response = await fetch('/api/start_research', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ query: query,+ mode: selectedMode+ })+ });++ const data = await response.json();++ if (data.status === 'success') {+ isResearchInProgress = true;+ currentResearchId = data.research_id;++ // Also update the window object+ window.currentResearchId = data.research_id;++ // Update the navigation to show Research in Progress+ updateNavigationBasedOnResearchStatus();++ // Update progress page+ document.getElementById('current-query').textContent = query;+ document.getElementById('progress-fill').style.width = '0%';+ document.getElementById('progress-percentage').textContent = '0%';+ document.getElementById('progress-status').textContent = 'Initializing research process...';++ // Navigate to progress page+ switchPage('research-progress');++ // Connect to socket for this research+ connectToResearchSocket(data.research_id);++ // Start polling for status+ pollResearchStatus(data.research_id);++ // Show the terminate button+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.style.display = 'inline-flex';+ terminateBtn.disabled = false;+ }+ } else {+ alert('Error starting research: ' + (data.message || 'Unknown error'));+ startResearchBtn.disabled = false;+ startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';+ }+ } catch (error) {+ console.error('Error:', error);+ alert('An error occurred while starting the research. Please try again.');+ startResearchBtn.disabled = false;+ startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';+ }+ });++ // Socket event handlers for research progress+ function connectToResearchSocket(researchId) {+ // Subscribe to the specific channel for this research+ socket.on(`research_progress_${researchId}`, (data) => {+ console.log('Research progress update:', data);++ // Update the progress UI+ if (data.progress) {+ updateProgressUI(data.progress, data.status, data.message);+ }++ // Update the log if we're on the details page+ if (data.log_entry && document.getElementById('research-details').classList.contains('active')) {+ updateDetailLogEntry(data.log_entry);+ }++ // If status is terminating, update the history item if visible+ if (data.status === 'terminating' && document.getElementById('history').classList.contains('active')) {+ updateHistoryItemStatus(researchId, 'terminating', 'Terminating...');+ }++ // Handle completion+ if (data.status === 'completed' || data.status === 'failed' || data.status === 'suspended') {+ isResearchInProgress = false;+ currentResearchId = null;++ // Always update the start research button state+ startResearchBtn.disabled = false;+ startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';++ // Reset terminating flag if it was suspended+ if (data.status === 'suspended') {+ isTerminating = false;+ }++ // Update navigation when research completes or is suspended+ updateNavigationBasedOnResearchStatus();++ // If history page is active, update the specific item in place+ if (document.getElementById('history').classList.contains('active')) {+ updateHistoryItemStatus(researchId, data.status);+ // Full refresh may still be needed to update duration info+ setTimeout(() => loadResearchHistory(), 500);+ }++ if (data.status === 'completed' && data.report_path) {+ // Navigate to results page if we're on the progress page+ if (document.getElementById('research-progress').classList.contains('active')) {+ loadResearch(researchId);+ }+ } else if (data.status === 'failed' || data.status === 'suspended') {+ // Update the progress UI with the error message+ const statusMessage = data.status === 'suspended' ?+ 'Research was terminated by user' :+ (data.error || 'Research failed');+ updateProgressUI(100, data.status, statusMessage);+ }+ }+ });+ }++ // Function to poll research status (as a backup to socket.io)+ function pollResearchStatus(researchId) {+ const interval = setInterval(async () => {+ try {+ const response = await fetch(`/api/research/${researchId}`);+ const data = await response.json();++ if (data.status === 'completed' || data.status === 'failed' || data.status === 'suspended') {+ clearInterval(interval);+ isResearchInProgress = false;+ currentResearchId = null;++ // Always update the start research button state+ startResearchBtn.disabled = false;+ startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';++ // Update navigation when research completes or is suspended+ updateNavigationBasedOnResearchStatus();++ // If history page is active, update the specific item in place+ if (document.getElementById('history').classList.contains('active')) {+ updateHistoryItemStatus(researchId, data.status);+ // Full refresh may still be needed to update duration info+ setTimeout(() => loadResearchHistory(), 500);+ }++ if (data.status === 'completed') {+ loadResearch(researchId);+ } else if (data.status === 'failed' || data.status === 'suspended') {+ const statusMessage = data.status === 'suspended' ?+ 'Research was terminated by user' :+ (data.metadata ? JSON.parse(data.metadata).error : 'Research failed');+ updateProgressUI(100, data.status, statusMessage);+ }+ } else {+ updateProgressUI(data.progress || 0, data.status);+ }+ } catch (error) {+ console.error('Error polling status:', error);+ }+ }, 3000); // Poll every 3 seconds+ }++ // Function to update the progress UI+ function updateProgressUI(progress, status, message) {+ const progressFill = document.getElementById('progress-fill');+ const progressPercentage = document.getElementById('progress-percentage');+ const progressStatus = document.getElementById('progress-status');++ if (progressFill && progressPercentage) {+ progressFill.style.width = `${progress}%`;+ progressPercentage.textContent = `${progress}%`;+ }++ if (progressStatus && message) {+ progressStatus.textContent = message;++ // Update status class+ progressStatus.className = 'progress-status';+ if (status) {+ progressStatus.classList.add(`status-${status}`);+ }+ }++ // Show/hide terminate button based on status+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ if (status === 'in_progress') {+ terminateBtn.style.display = 'inline-flex';+ terminateBtn.disabled = false;+ terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';+ } else if (status === 'terminating') {+ terminateBtn.style.display = 'inline-flex';+ terminateBtn.disabled = true;+ terminateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';+ } else {+ terminateBtn.style.display = 'none';+ }+ }+ }++ // Completely rewritten function to ensure reliable history loading+ async function loadResearchHistory() {+ const historyList = document.getElementById('history-list');++ // Make sure we have the history list element+ if (!historyList) {+ console.error('History list element not found');+ return;+ }++ historyList.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';++ try {+ // Basic fetch without any extras+ const response = await fetch('/api/history');++ if (!response.ok) {+ throw new Error(`API returned status ${response.status}: ${response.statusText}`);+ }++ const data = await response.json();++ // Clear the loading spinner+ historyList.innerHTML = '';++ // Handle empty data+ if (!data || !Array.isArray(data) || data.length === 0) {+ historyList.innerHTML = '<div class="empty-state">No research history found. Start a new research project!</div>';+ return;+ }++ // Display each history item+ data.forEach(item => {+ try {+ // Skip if item is invalid+ if (!item || !item.id) {+ return;+ }++ // Create container+ const historyItem = document.createElement('div');+ historyItem.className = 'history-item';+ historyItem.dataset.researchId = item.id;++ // Create header with title and status+ const header = document.createElement('div');+ header.className = 'history-item-header';++ const title = document.createElement('div');+ title.className = 'history-item-title';+ title.textContent = item.query || 'Untitled Research';++ const status = document.createElement('div');+ status.className = `history-item-status status-${item.status || 'unknown'}`;+ status.textContent = item.status ? (item.status.charAt(0).toUpperCase() + item.status.slice(1)) : 'Unknown';++ header.appendChild(title);+ header.appendChild(status);+ historyItem.appendChild(header);++ // Create meta section+ const meta = document.createElement('div');+ meta.className = 'history-item-meta';++ const date = document.createElement('div');+ date.className = 'history-item-date';+ try {+ // Use completed_at if available, fall back to created_at if not+ const dateToUse = item.completed_at || item.created_at;+ date.textContent = dateToUse ? formatDate(new Date(dateToUse)) : 'Unknown date';+ } catch (e) {+ date.textContent = item.completed_at || item.created_at || 'Unknown date';+ }++ const mode = document.createElement('div');+ mode.className = 'history-item-mode';+ const modeIcon = item.mode === 'quick' ? 'bolt' : 'microscope';+ const modeText = item.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';+ mode.innerHTML = `<i class="fas fa-${modeIcon}"></i> ${modeText}`;++ meta.appendChild(date);+ meta.appendChild(mode);+ historyItem.appendChild(meta);++ // Create actions section+ const actions = document.createElement('div');+ actions.className = 'history-item-actions';++ // View button+ const viewBtn = document.createElement('button');+ viewBtn.className = 'btn btn-sm btn-outline view-btn';++ if (item.status === 'completed') {+ viewBtn.innerHTML = '<i class="fas fa-eye"></i> View';+ viewBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ loadResearch(item.id);+ });++ // PDF button for completed research+ const pdfBtn = document.createElement('button');+ pdfBtn.className = 'btn btn-sm btn-outline pdf-btn';+ pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> PDF';+ pdfBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ generatePdfFromResearch(item.id);+ });+ actions.appendChild(pdfBtn);+ } else if (item.status === 'in_progress') {+ viewBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> In Progress';+ viewBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ navigateToResearchProgress({id: item.id, query: item.query, progress: 0});+ });+ } else {+ viewBtn.innerHTML = '<i class="fas fa-eye"></i> View';+ viewBtn.disabled = true;+ }++ actions.appendChild(viewBtn);++ // Delete button+ const deleteBtn = document.createElement('button');+ deleteBtn.className = 'btn btn-sm btn-outline delete-btn';+ deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';+ deleteBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ if (confirm(`Are you sure you want to delete this research: "${item.query}"?`)) {+ deleteResearch(item.id);+ }+ });+ actions.appendChild(deleteBtn);++ historyItem.appendChild(actions);++ // Add click handler for the entire item+ historyItem.addEventListener('click', (e) => {+ // Skip if clicking on a button+ if (e.target.closest('button')) {+ return;+ }++ if (item.status === 'completed') {+ loadResearch(item.id);+ } else if (item.status === 'in_progress') {+ navigateToResearchProgress({id: item.id, query: item.query, progress: 0});+ }+ });++ // Add to the history list+ historyList.appendChild(historyItem);+ } catch (itemError) {+ console.error('Error processing history item:', itemError, item);+ }+ });++ // Check if any research is in progress and update the start button state+ const inProgressResearch = data.find(item => item.status === 'in_progress');+ if (inProgressResearch) {+ isResearchInProgress = true;+ currentResearchId = inProgressResearch.id;+ if (startResearchBtn) {+ startResearchBtn.disabled = true;+ }+ } else {+ isResearchInProgress = false;+ if (startResearchBtn) {+ startResearchBtn.disabled = false;+ }+ }++ } catch (error) {+ console.error('Error loading history:', error);+ historyList.innerHTML = `+ <div class="error-message">+ Error loading history: ${error.message}+ </div>+ <div style="text-align: center; margin-top: 1rem;">+ <button id="retry-history-btn" class="btn btn-primary">+ <i class="fas fa-sync"></i> Retry+ </button>+ </div>`;++ const retryBtn = document.getElementById('retry-history-btn');+ if (retryBtn) {+ retryBtn.addEventListener('click', () => {+ loadResearchHistory();+ });+ }+ }++ // Add a fallback in case something goes wrong and the history list is still empty+ setTimeout(() => {+ if (historyList.innerHTML === '' || historyList.innerHTML.includes('loading-spinner')) {+ console.warn('History list is still empty or showing spinner after load attempt - applying fallback');+ historyList.innerHTML = `+ <div class="error-message">+ Something went wrong while loading the history.+ </div>+ <div style="text-align: center; margin-top: 1rem;">+ <button id="fallback-retry-btn" class="btn btn-primary">+ <i class="fas fa-sync"></i> Retry+ </button>+ </div>`;++ const fallbackRetryBtn = document.getElementById('fallback-retry-btn');+ if (fallbackRetryBtn) {+ fallbackRetryBtn.addEventListener('click', () => {+ loadResearchHistory();+ });+ }+ }+ }, 5000); // Check after 5 seconds+ }++ // Function to navigate to research progress+ function navigateToResearchProgress(research) {+ document.getElementById('current-query').textContent = research.query;+ document.getElementById('progress-fill').style.width = `${research.progress || 0}%`;+ document.getElementById('progress-percentage').textContent = `${research.progress || 0}%`;++ // Navigate to progress page+ switchPage('research-progress');++ // Connect to socket for this research+ connectToResearchSocket(research.id);++ // Start polling for status+ pollResearchStatus(research.id);+ }++ // Function to delete a research record+ async function deleteResearch(researchId) {+ try {+ const response = await fetch(`/api/research/${researchId}/delete`, {+ method: 'DELETE'+ });++ if (response.ok) {+ // Reload the history+ loadResearchHistory();+ } else {+ alert('Failed to delete research. Please try again.');+ }+ } catch (error) {+ console.error('Error deleting research:', error);+ alert('An error occurred while deleting the research.');+ }+ }++ // Function to load a specific research result+ async function loadResearch(researchId) {+ // Navigate to results page+ switchPage('research-results');++ const resultsContent = document.getElementById('results-content');+ resultsContent.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';++ try {+ // Load research details+ const detailsResponse = await fetch(`/api/research/${researchId}`);+ const details = await detailsResponse.json();++ // Display metadata+ document.getElementById('result-query').textContent = details.query;++ // Format date with duration if available+ let dateText = formatDate(new Date(details.completed_at || details.created_at));+ if (details.duration_seconds) {+ // Format duration+ let durationText = '';+ const duration = parseInt(details.duration_seconds);++ if (duration < 60) { // less than a minute+ durationText = `${duration}s`;+ } else if (duration < 3600) { // less than an hour+ durationText = `${Math.floor(duration / 60)}m ${duration % 60}s`;+ } else { // hours+ durationText = `${Math.floor(duration / 3600)}h ${Math.floor((duration % 3600) / 60)}m`;+ }++ dateText += ` (Duration: ${durationText})`;+ }+ document.getElementById('result-date').textContent = dateText;++ document.getElementById('result-mode').textContent = details.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';++ // Load the report content+ const reportResponse = await fetch(`/api/report/${researchId}`);+ const reportData = await reportResponse.json();++ if (reportData.status === 'success') {+ // Render markdown+ const renderedContent = marked.parse(reportData.content);+ resultsContent.innerHTML = renderedContent;++ // Apply syntax highlighting+ document.querySelectorAll('pre code').forEach((block) => {+ hljs.highlightElement(block);+ });+ } else {+ resultsContent.innerHTML = '<div class="error-message">Error loading report. Please try again later.</div>';+ }+ } catch (error) {+ console.error('Error loading research:', error);+ resultsContent.innerHTML = '<div class="error-message">Error loading research results. Please try again later.</div>';+ }+ }++ // Function to load research details page+ async function loadResearchDetails(researchId) {+ // Navigate to details page+ switchPage('research-details');++ // Initialize the research log area+ const researchLog = document.getElementById('research-log');+ researchLog.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';++ try {+ // Load research details+ const response = await fetch(`/api/research/${researchId}/details`);+ console.log('Research details API response status:', response.status);++ if (!response.ok) {+ console.error('API error:', response.status, response.statusText);+ researchLog.innerHTML = `<div class="error-message">Error loading research details. Status: ${response.status}</div>`;+ return;+ }++ const data = await response.json();+ console.log('Research details data:', data);++ if (data.status !== 'success') {+ researchLog.innerHTML = `<div class="error-message">Error loading research details: ${data.message || 'Unknown error'}</div>`;+ return;+ }++ // Display metadata+ document.getElementById('detail-query').textContent = data.query || 'N/A';+ document.getElementById('detail-status').textContent = capitalizeFirstLetter(data.status || 'unknown');+ document.getElementById('detail-status').className = `metadata-value status-${data.status || 'unknown'}`;+ document.getElementById('detail-mode').textContent = (data.mode === 'quick' ? 'Quick Summary' : 'Detailed Report') || 'N/A';++ // Update progress bar+ const progress = data.progress || 0;+ document.getElementById('detail-progress-fill').style.width = `${progress}%`;+ document.getElementById('detail-progress-percentage').textContent = `${progress}%`;++ // Render log entries+ renderLogEntries(data.log || []);++ // Set up socket connection for live updates if research is in progress+ if (data.status === 'in_progress') {+ connectToResearchSocket(researchId);+ }++ // Add appropriate actions based on research status+ const detailActions = document.getElementById('detail-actions');+ detailActions.innerHTML = '';++ if (data.status === 'completed') {+ const viewResultsBtn = document.createElement('button');+ viewResultsBtn.className = 'btn btn-primary';+ viewResultsBtn.innerHTML = '<i class="fas fa-eye"></i> View Results';+ viewResultsBtn.addEventListener('click', () => loadResearch(researchId));+ detailActions.appendChild(viewResultsBtn);++ // Add download PDF button+ const downloadPdfBtn = document.createElement('button');+ downloadPdfBtn.className = 'btn btn-outline';+ downloadPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';+ downloadPdfBtn.addEventListener('click', () => generatePdfFromResearch(researchId));+ detailActions.appendChild(downloadPdfBtn);+ } else if (data.status === 'in_progress') {+ const viewProgressBtn = document.createElement('button');+ viewProgressBtn.className = 'btn btn-primary';+ viewProgressBtn.innerHTML = '<i class="fas fa-sync"></i> View Live Progress';+ viewProgressBtn.addEventListener('click', () => {+ document.getElementById('current-query').textContent = data.query || '';++ // Navigate to progress page+ switchPage('research-progress');++ // Connect to socket+ connectToResearchSocket(researchId);+ });+ detailActions.appendChild(viewProgressBtn);+ }+ } catch (error) {+ console.error('Error loading research details:', error);+ researchLog.innerHTML = `<div class="error-message">Error loading research details: ${error.message}</div>`;+ }+ }++ // Function to render log entries+ function renderLogEntries(logEntries) {+ const researchLog = document.getElementById('research-log');+ researchLog.innerHTML = '';++ if (!logEntries || logEntries.length === 0) {+ researchLog.innerHTML = '<div class="empty-state">No log entries available.</div>';+ return;+ }++ try {+ // Use a document fragment for better performance+ const fragment = document.createDocumentFragment();+ const template = document.getElementById('log-entry-template');++ if (!template) {+ console.error('Log entry template not found');+ researchLog.innerHTML = '<div class="error-message">Error rendering log entries: Template not found</div>';+ return;+ }++ logEntries.forEach(entry => {+ if (!entry) return; // Skip invalid entries++ try {+ const clone = document.importNode(template.content, true);++ // Format the timestamp+ let timeStr = 'N/A';+ try {+ if (entry.time) {+ const time = new Date(entry.time);+ timeStr = time.toLocaleTimeString();+ }+ } catch (timeErr) {+ console.warn('Error formatting time:', timeErr);+ }++ const timeEl = clone.querySelector('.log-entry-time');+ if (timeEl) timeEl.textContent = timeStr;++ // Add message with phase highlighting if available+ const messageEl = clone.querySelector('.log-entry-message');+ if (messageEl) {+ let phaseClass = '';+ if (entry.metadata && entry.metadata.phase) {+ phaseClass = `phase-${entry.metadata.phase}`;+ }+ messageEl.textContent = entry.message || 'No message';+ messageEl.classList.add(phaseClass);+ }++ // Add progress information if available+ const progressEl = clone.querySelector('.log-entry-progress');+ if (progressEl) {+ if (entry.progress !== null && entry.progress !== undefined) {+ progressEl.textContent = `Progress: ${entry.progress}%`;+ } else {+ progressEl.textContent = '';+ }+ }++ fragment.appendChild(clone);+ } catch (entryError) {+ console.error('Error processing log entry:', entryError, entry);+ // Continue with other entries+ }+ });++ researchLog.appendChild(fragment);++ // Scroll to the bottom+ researchLog.scrollTop = researchLog.scrollHeight;+ } catch (error) {+ console.error('Error rendering log entries:', error);+ researchLog.innerHTML = '<div class="error-message">Error rendering log entries. Please try again later.</div>';+ }+ }++ // Function to update detail log with a new entry+ function updateDetailLogEntry(logEntry) {+ if (!logEntry || !document.getElementById('research-details').classList.contains('active')) {+ return;+ }++ const researchLog = document.getElementById('research-log');+ const template = document.getElementById('log-entry-template');+ const clone = document.importNode(template.content, true);++ // Format the timestamp+ const time = new Date(logEntry.time);+ clone.querySelector('.log-entry-time').textContent = time.toLocaleTimeString();++ // Add message with phase highlighting if available+ const messageEl = clone.querySelector('.log-entry-message');+ let phaseClass = '';+ if (logEntry.metadata && logEntry.metadata.phase) {+ phaseClass = `phase-${logEntry.metadata.phase}`;+ }+ messageEl.textContent = logEntry.message;+ messageEl.classList.add(phaseClass);++ // Add progress information if available+ const progressEl = clone.querySelector('.log-entry-progress');+ if (logEntry.progress !== null && logEntry.progress !== undefined) {+ progressEl.textContent = `Progress: ${logEntry.progress}%`;++ // Also update the progress bar in the details view+ document.getElementById('detail-progress-fill').style.width = `${logEntry.progress}%`;+ document.getElementById('detail-progress-percentage').textContent = `${logEntry.progress}%`;+ } else {+ progressEl.textContent = '';+ }++ researchLog.appendChild(clone);++ // Scroll to the bottom+ researchLog.scrollTop = researchLog.scrollHeight;+ }++ // Back to history button handlers+ document.getElementById('back-to-history').addEventListener('click', () => {+ const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');+ historyNav.click();+ });++ document.getElementById('back-to-history-from-details').addEventListener('click', () => {+ const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');+ historyNav.click();+ });++ // Helper functions+ function capitalizeFirstLetter(string) {+ return string.charAt(0).toUpperCase() + string.slice(1);+ }++ function formatDate(date) {+ // Ensure we're handling the date properly+ if (!(date instanceof Date) || isNaN(date)) {+ console.warn('Invalid date provided to formatDate:', date);+ return 'Invalid date';+ }++ // Get current year to compare with date year+ const currentYear = new Date().getFullYear();+ const dateYear = date.getFullYear();++ // Get month name, day, and time+ const month = date.toLocaleString('en-US', { month: 'short' });+ const day = date.getDate();+ const hours = date.getHours().toString().padStart(2, '0');+ const minutes = date.getMinutes().toString().padStart(2, '0');++ // Format like "Feb 25, 08:09" or "Feb 25, 2022, 08:09" if not current year+ if (dateYear === currentYear) {+ return `${month} ${day}, ${hours}:${minutes}`;+ } else {+ return `${month} ${day}, ${dateYear}, ${hours}:${minutes}`;+ }+ }++ // Check for active research on page load+ (async function checkActiveResearch() {+ try {+ const response = await fetch('/api/history');+ const history = await response.json();++ // Find in-progress research+ const activeResearch = history.find(item => item.status === 'in_progress');++ if (activeResearch) {+ isResearchInProgress = true;+ currentResearchId = activeResearch.id;+ window.currentResearchId = currentResearchId;++ // Check if we're on the new research page and redirect to progress+ const currentPage = Array.from(pages).find(page => page.classList.contains('active'));++ if (currentPage && currentPage.id === 'new-research') {+ // Navigate to progress page+ switchPage('research-progress');++ // Connect to socket for this research+ connectToResearchSocket(currentResearchId);++ // Start polling for updates+ pollResearchStatus(currentResearchId);+ }+ }+ } catch (error) {+ console.error('Error checking for active research:', error);+ }+ })();++ // Function to update progress UI from current research+ function updateProgressFromCurrentResearch() {+ if (!isResearchInProgress || !currentResearchId) return;++ // Fetch current status+ fetch(`/api/research/${currentResearchId}`)+ .then(response => response.json())+ .then(data => {+ document.getElementById('current-query').textContent = data.query || '';+ document.getElementById('progress-fill').style.width = `${data.progress || 0}%`;+ document.getElementById('progress-percentage').textContent = `${data.progress || 0}%`;++ // Connect to socket for this research+ connectToResearchSocket(currentResearchId);+ })+ .catch(error => {+ console.error('Error fetching research status:', error);+ });+ }++ // Function to update the sidebar navigation based on research status+ function updateNavigationBasedOnResearchStatus() {+ const newResearchNav = Array.from(navItems).find(item =>+ item.getAttribute('data-page') === 'new-research' ||+ (item.getAttribute('data-original-page') === 'new-research' &&+ item.getAttribute('data-page') === 'research-progress')+ );++ if (newResearchNav) {+ if (isResearchInProgress) {+ // Change text to "Research in Progress"+ newResearchNav.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Research in Progress';++ // Also update the listener to navigate to progress page+ if (newResearchNav.getAttribute('data-page') !== 'research-progress') {+ newResearchNav.setAttribute('data-original-page', 'new-research');+ newResearchNav.setAttribute('data-page', 'research-progress');+ }++ // If on new-research page, redirect to research-progress+ if (document.getElementById('new-research').classList.contains('active')) {+ pages.forEach(page => page.classList.remove('active'));+ document.getElementById('research-progress').classList.add('active');++ // Update the research progress page+ updateProgressFromCurrentResearch();+ }+ } else {+ // Reset to "New Research" if there's no active research+ newResearchNav.innerHTML = '<i class="fas fa-search"></i> New Research';++ // Reset the listener+ if (newResearchNav.hasAttribute('data-original-page')) {+ newResearchNav.setAttribute('data-page', newResearchNav.getAttribute('data-original-page'));+ newResearchNav.removeAttribute('data-original-page');+ }++ // If the terminate button is visible, hide it+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.style.display = 'none';+ terminateBtn.disabled = false;+ terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';+ }+ }++ // Make sure the navigation highlights the correct item+ navItems.forEach(item => {+ if (item === newResearchNav) {+ if (isResearchInProgress) {+ if (document.getElementById('research-progress').classList.contains('active')) {+ item.classList.add('active');+ }+ } else if (document.getElementById('new-research').classList.contains('active')) {+ item.classList.add('active');+ }+ }+ });+ }+ }++ // Function to update the research progress page from nav click+ function updateProgressPage() {+ if (!isResearchInProgress || !currentResearchId) {+ return;+ }++ // Update the progress page+ fetch(`/api/research/${currentResearchId}`)+ .then(response => response.json())+ .then(data => {+ // Update the query display+ document.getElementById('current-query').textContent = data.query;++ // Update the progress bar+ updateProgressUI(data.progress || 0, data.status);++ // Connect to socket for live updates+ connectToResearchSocket(currentResearchId);++ // Check if we need to show the terminate button+ if (data.status === 'in_progress') {+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.style.display = 'inline-flex';+ terminateBtn.disabled = false;+ }+ }+ })+ .catch(error => {+ console.error('Error fetching research status:', error);+ });+ }++ // Function to update a specific history item without reloading the whole list+ function updateHistoryItemStatus(researchId, status, statusText) {+ const historyList = document.getElementById('history-list');++ // Look for the item in the active research banner+ const activeBanner = historyList.querySelector(`.active-research-banner[data-research-id="${researchId}"]`);+ if (activeBanner) {+ const statusEl = activeBanner.querySelector('.history-item-status');+ if (statusEl) {+ statusEl.textContent = statusText || capitalizeFirstLetter(status);+ statusEl.className = 'history-item-status';+ statusEl.classList.add(`status-${status}`);+ }++ // Update buttons+ const terminateBtn = activeBanner.querySelector('.terminate-btn');+ if (terminateBtn) {+ terminateBtn.style.display = 'none';+ }++ const viewProgressBtn = activeBanner.querySelector('.view-progress-btn');+ if (viewProgressBtn) {+ if (status === 'suspended') {+ viewProgressBtn.innerHTML = '<i class="fas fa-pause-circle"></i> Suspended';+ } else if (status === 'failed') {+ viewProgressBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';+ }+ viewProgressBtn.disabled = true;+ }++ return;+ }++ // Look for the item in the regular list+ const historyItem = historyList.querySelector(`.history-item[data-research-id="${researchId}"]`);+ if (historyItem) {+ const statusEl = historyItem.querySelector('.history-item-status');+ if (statusEl) {+ statusEl.textContent = statusText || capitalizeFirstLetter(status);+ statusEl.className = 'history-item-status';+ statusEl.classList.add(`status-${status}`);+ }++ // Update view button+ const viewBtn = historyItem.querySelector('.view-btn');+ if (viewBtn) {+ if (status === 'suspended') {+ viewBtn.innerHTML = '<i class="fas fa-pause-circle"></i> Suspended';+ viewBtn.disabled = true;+ } else if (status === 'failed') {+ viewBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';+ viewBtn.disabled = true;+ }+ }+ }+ }++ // PDF Generation Functions+ function generatePdf() {+ const resultsContent = document.getElementById('results-content');+ const query = document.getElementById('result-query').textContent;+ const date = document.getElementById('result-date').textContent;+ const mode = document.getElementById('result-mode').textContent;++ // Show loading indicator+ const loadingIndicator = document.createElement('div');+ loadingIndicator.className = 'loading-spinner centered';+ loadingIndicator.innerHTML = '<div class="spinner"></div><p style="margin-top: 10px;">Generating PDF...</p>';+ resultsContent.parentNode.insertBefore(loadingIndicator, resultsContent);+ resultsContent.style.display = 'none';++ // Create a clone of the content for PDF generation+ const contentClone = resultsContent.cloneNode(true);+ contentClone.style.display = 'block';+ contentClone.style.position = 'absolute';+ contentClone.style.left = '-9999px';+ contentClone.style.width = '800px';++ // Apply PDF-specific styling for better readability+ contentClone.style.background = '#ffffff';+ contentClone.style.color = '#333333';+ contentClone.style.padding = '20px';++ // Improve visibility by adjusting styles specifically for PDF+ const applyPdfStyles = (element) => {+ // Set all text to dark color for better readability on white background+ element.querySelectorAll('*').forEach(el => {+ // Skip elements that already have inline color styles+ if (!el.style.color) {+ el.style.color = '#333333';+ }++ // Fix background colors+ if (el.style.backgroundColor &&+ (el.style.backgroundColor.includes('var(--bg') ||+ el.style.backgroundColor.includes('#121212') ||+ el.style.backgroundColor.includes('#1e1e2d') ||+ el.style.backgroundColor.includes('#2a2a3a'))) {+ el.style.backgroundColor = '#f8f8f8';+ }++ // Handle code blocks specifically+ if (el.tagName === 'PRE' || el.tagName === 'CODE') {+ el.style.backgroundColor = '#f5f5f5';+ el.style.border = '1px solid #e0e0e0';+ el.style.color = '#333333';+ }++ // Make links visible+ if (el.tagName === 'A') {+ el.style.color = '#0066cc';+ el.style.textDecoration = 'underline';+ }+ });++ // Fix specific syntax highlighting elements for PDF+ element.querySelectorAll('.hljs').forEach(hljs => {+ hljs.style.backgroundColor = '#f8f8f8';+ hljs.style.color = '#333333';++ // Fix common syntax highlighting colors for PDF+ hljs.querySelectorAll('.hljs-keyword').forEach(el => el.style.color = '#0000cc');+ hljs.querySelectorAll('.hljs-string').forEach(el => el.style.color = '#008800');+ hljs.querySelectorAll('.hljs-number').forEach(el => el.style.color = '#aa0000');+ hljs.querySelectorAll('.hljs-comment').forEach(el => el.style.color = '#888888');+ hljs.querySelectorAll('.hljs-function').forEach(el => el.style.color = '#880000');+ });+ };++ document.body.appendChild(contentClone);++ // Apply PDF-specific styles+ applyPdfStyles(contentClone);++ // Add title and metadata to the PDF content+ const headerDiv = document.createElement('div');+ headerDiv.innerHTML = `+ <h1 style="color: #6e4ff6; font-size: 24px; margin-bottom: 10px;">${query}</h1>+ <div style="margin-bottom: 20px; font-size: 14px; color: #666;">+ <p><strong>Generated:</strong> ${date}</p>+ <p><strong>Mode:</strong> ${mode}</p>+ <p><strong>Source:</strong> Deep Research Lab</p>+ </div>+ <hr style="margin-bottom: 20px; border: 1px solid #eee;">+ `;+ contentClone.insertBefore(headerDiv, contentClone.firstChild);++ setTimeout(() => {+ try {+ // Use window.jspdf which is from the UMD bundle+ const { jsPDF } = window.jspdf;+ const pdf = new jsPDF('p', 'pt', 'a4');+ const pdfWidth = pdf.internal.pageSize.getWidth();+ const pdfHeight = pdf.internal.pageSize.getHeight();+ const margin = 40;+ const contentWidth = pdfWidth - 2 * margin;++ // Create a more efficient PDF generation approach that keeps text selectable+ const generateTextBasedPDF = async () => {+ try {+ // Get all text elements and handle them differently than images and special content+ // Use html2canvas only for complex elements that can't be easily converted to text+ const elements = Array.from(contentClone.children);+ let currentY = margin;+ let pageNum = 1;++ // Function to add a page with header+ const addPageWithHeader = (pageNum) => {+ if (pageNum > 1) {+ pdf.addPage();+ }+ pdf.setFontSize(8);+ pdf.setTextColor(100, 100, 100);+ pdf.text(`Deep Research - ${query} - Page ${pageNum}`, margin, pdfHeight - 20);+ };++ addPageWithHeader(pageNum);++ // Process each element - for better quality combine text-based approach with canvas+ for (const element of elements) {+ // Simple text content can be handled directly by jsPDF+ if (element.tagName === 'P' && !element.querySelector('img, canvas, svg, code, pre')) {+ // Extract and add text content directly+ pdf.setFontSize(11);+ pdf.setTextColor(0, 0, 0);++ const text = element.textContent.trim();+ const textLines = pdf.splitTextToSize(text, contentWidth);++ // Check if we need a new page+ if (currentY + (textLines.length * 14) > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.text(textLines, margin, currentY + 12);+ currentY += (textLines.length * 14) + 10;+ }+ // Handle headings differently to maintain hierarchy+ else if (['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(element.tagName)) {+ // Extract and add heading text directly+ const fontSize = {+ 'H1': 24,+ 'H2': 20,+ 'H3': 16,+ 'H4': 14,+ 'H5': 12,+ 'H6': 11+ }[element.tagName];++ pdf.setFontSize(fontSize);+ pdf.setTextColor(0, 0, 0);++ const text = element.textContent.trim();+ const textLines = pdf.splitTextToSize(text, contentWidth);++ // Check if we need a new page+ if (currentY + (textLines.length * (fontSize + 4)) > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.text(textLines, margin, currentY + fontSize);+ currentY += (textLines.length * (fontSize + 4)) + 10;+ }+ // For complex elements like code, tables, images etc. use html2canvas+ else {+ const canvas = await html2canvas(element, {+ scale: 2, // Higher scale for better quality+ useCORS: true,+ logging: false,+ backgroundColor: '#FFFFFF'+ });++ const imgData = canvas.toDataURL('image/png');+ const imgHeight = (canvas.height * contentWidth) / canvas.width;++ // Check if we need a new page+ if (currentY + imgHeight > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ // Add image to PDF+ pdf.addImage(imgData, 'PNG', margin, currentY, contentWidth, imgHeight);+ currentY += imgHeight + 10;+ }+ }++ // Download the PDF+ const filename = `${query.replace(/[^a-z0-9]/gi, '_').substring(0, 30).toLowerCase()}_research.pdf`;+ pdf.save(filename);++ // Clean up+ document.body.removeChild(contentClone);+ resultsContent.style.display = 'block';+ loadingIndicator.remove();+ } catch (error) {+ console.error('Error generating PDF:', error);+ alert('An error occurred while generating the PDF. Please try again.');+ document.body.removeChild(contentClone);+ resultsContent.style.display = 'block';+ loadingIndicator.remove();+ }+ };++ generateTextBasedPDF();+ } catch (error) {+ console.error('Error initializing PDF generation:', error);+ alert('An error occurred while preparing the PDF. Please try again.');+ document.body.removeChild(contentClone);+ resultsContent.style.display = 'block';+ loadingIndicator.remove();+ }+ }, 100);+ }++ // Function to generate PDF from a specific research ID+ async function generatePdfFromResearch(researchId) {+ try {+ // Load research details+ const detailsResponse = await fetch(`/api/research/${researchId}`);+ const details = await detailsResponse.json();++ // Load the report content+ const reportResponse = await fetch(`/api/report/${researchId}`);+ const reportData = await reportResponse.json();++ if (reportData.status === 'success') {+ // Create a temporary container to render the content+ const tempContainer = document.createElement('div');+ tempContainer.className = 'results-content pdf-optimized';+ tempContainer.style.display = 'none';+ document.body.appendChild(tempContainer);++ // Render markdown with optimized styles for PDF+ const renderedContent = marked.parse(reportData.content);+ tempContainer.innerHTML = renderedContent;++ // Apply syntax highlighting+ tempContainer.querySelectorAll('pre code').forEach((block) => {+ hljs.highlightElement(block);+ });++ // Format date+ let dateText = formatDate(new Date(details.completed_at || details.created_at));+ if (details.duration_seconds) {+ let durationText = '';+ const duration = parseInt(details.duration_seconds);++ if (duration < 60) {+ durationText = `${duration}s`;+ } else if (duration < 3600) {+ durationText = `${Math.floor(duration / 60)}m ${duration % 60}s`;+ } else {+ durationText = `${Math.floor(duration / 3600)}h ${Math.floor((duration % 3600) / 60)}m`;+ }++ dateText += ` (Duration: ${durationText})`;+ }++ // Set up data for PDF generation+ document.getElementById('result-query').textContent = details.query;+ document.getElementById('result-date').textContent = dateText;+ document.getElementById('result-mode').textContent = details.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';++ // Replace the current content with our temporary content+ const resultsContent = document.getElementById('results-content');+ const originalContent = resultsContent.innerHTML;+ resultsContent.innerHTML = tempContainer.innerHTML;++ // Generate the PDF+ generatePdf();++ // Restore original content if we're not on the results page+ setTimeout(() => {+ if (!document.getElementById('research-results').classList.contains('active')) {+ resultsContent.innerHTML = originalContent;+ }+ document.body.removeChild(tempContainer);+ }, 500);++ } else {+ alert('Error loading report. Could not generate PDF.');+ }+ } catch (error) {+ console.error('Error generating PDF:', error);+ alert('An error occurred while generating the PDF. Please try again.');+ }+ }++ // Initialize the terminate button event listener+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.addEventListener('click', () => {+ if (confirm('Are you sure you want to terminate this research? This action cannot be undone.')) {+ if (currentResearchId) {+ terminateResearch(currentResearchId);+ }+ }+ });+ }++ // Initialize PDF download button+ const downloadPdfBtn = document.getElementById('download-pdf-btn');+ if (downloadPdfBtn) {+ downloadPdfBtn.addEventListener('click', generatePdf);+ }+});\ No newline at end of filediff --git a/templates/index.html b/templates/index.htmlnew file mode 100644index 0000000000..5448220170--- /dev/null+++ b/templates/index.html@@ -0,0 +1,296 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Deep Research Lab</title>+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">+ <!-- Change to CDN version that works in browsers -->+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">+ <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">+</head>+<body>+ <div class="app-container">+ <!-- Sidebar -->+ <aside class="sidebar">+ <div class="sidebar-header">+ <h2 id="logo-link" style="cursor: pointer;"><i class="fas fa-atom"></i> Deep Research</h2>+ </div>+ <nav class="sidebar-nav">+ <ul>+ <li class="active" data-page="new-research"><i class="fas fa-search"></i> New Research</li>+ <li data-page="history"><i class="fas fa-history"></i> History</li>+ </ul>+ </nav>+ <div class="sidebar-footer">+ <p>v0.0.1 | <i class="fas fa-brain"></i></p>+ </div>+ </aside>++ <!-- Main Content -->+ <main class="main-content">+ <!-- New Research Page -->+ <div class="page active" id="new-research">+ <div class="page-header">+ <h1>Start New Research</h1>+ </div>+ <div class="card research-card">+ <div class="card-content">+ <form id="research-form">+ <div class="form-group">+ <label for="query">Research Query</label>+ <textarea id="query" name="query" rows="3" placeholder="Enter your research topic or question..."></textarea>+ </div>+ <div class="form-group">+ <label>Research Mode</label>+ <div class="mode-selection">+ <div class="mode-option active" data-mode="quick">+ <div class="mode-icon"><i class="fas fa-bolt"></i></div>+ <div class="mode-info">+ <h3>Quick Summary</h3>+ <p>Generated in a few minutes</p>+ </div>+ </div>+ <div class="mode-option" data-mode="detailed">+ <div class="mode-icon"><i class="fas fa-microscope"></i></div>+ <div class="mode-info">+ <h3>Detailed Report</h3>+ <p>In-depth analysis (takes longer)</p>+ </div>+ </div>+ </div>+ </div>+ <div class="form-actions">+ <button type="submit" class="btn btn-primary" id="start-research-btn"><i class="fas fa-rocket"></i> Start Research</button>+ </div>+ </form>+ </div>+ </div>+ </div>++ <!-- History Page -->+ <div class="page" id="history">+ <div class="page-header">+ <h1>Research History</h1>+ </div>+ <div class="card">+ <div class="card-content">+ <div class="history-list" id="history-list">+ <!-- Will be populated dynamically -->+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Research Progress Page -->+ <div class="page" id="research-progress">+ <div class="page-header">+ <h1>Research in Progress</h1>+ </div>+ <div class="card">+ <div class="card-content">+ <div class="progress-info">+ <div class="current-query-container">+ <div class="current-query-label">Current Query:</div>+ <div id="current-query" class="current-query"></div>+ </div>+ <div class="progress-container">+ <div class="progress-bar">+ <div id="progress-fill" class="progress-fill"></div>+ </div>+ <div id="progress-percentage" class="progress-percentage">0%</div>+ </div>+ <div id="progress-status" class="progress-status">Initializing research process...</div>+ <div class="progress-actions">+ <button id="terminate-research-btn" class="btn btn-outline terminate-btn" style="display: none;">+ <i class="fas fa-stop-circle"></i> Terminate Research+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Research Details Page -->+ <div class="page" id="research-details">+ <div class="page-header">+ <div class="results-header">+ <h1>Research Details</h1>+ <div class="results-actions">+ <button class="btn btn-outline" id="back-to-history-from-details"><i class="fas fa-arrow-left"></i> Back to History</button>+ </div>+ </div>+ </div>+ <div class="card">+ <div class="card-content">+ <div class="research-metadata">+ <div class="metadata-item">+ <span class="metadata-label">Query:</span>+ <span id="detail-query" class="metadata-value"></span>+ </div>+ <div class="metadata-item">+ <span class="metadata-label">Status:</span>+ <span id="detail-status" class="metadata-value"></span>+ </div>+ <div class="metadata-item">+ <span class="metadata-label">Mode:</span>+ <span id="detail-mode" class="metadata-value"></span>+ </div>+ <div class="metadata-item">+ <span class="metadata-label">Progress:</span>+ <div class="detail-progress-container">+ <div class="detail-progress-bar">+ <div class="detail-progress-fill" id="detail-progress-fill"></div>+ </div>+ <span id="detail-progress-percentage">0%</span>+ </div>+ </div>+ </div>++ <div class="research-log-container">+ <h3>Research Progress Log</h3>+ <div class="research-log" id="research-log">+ <!-- Will be populated dynamically -->+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ </div>+ </div>+ </div>++ <div class="detail-actions" id="detail-actions">+ <!-- Conditionally shown based on research status -->+ </div>+ </div>+ </div>+ </div>++ <!-- Research Results Page -->+ <div class="page" id="research-results">+ <div class="page-header">+ <div class="results-header">+ <h1>Research Results</h1>+ <div class="results-actions">+ <button class="btn btn-outline" id="download-pdf-btn"><i class="fas fa-file-pdf"></i> Download PDF</button>+ <button class="btn btn-outline" id="back-to-history"><i class="fas fa-arrow-left"></i> Back to History</button>+ </div>+ </div>+ </div>+ <div class="card results-card">+ <div class="card-content">+ <div class="results-metadata">+ <div class="metadata-item">+ <span class="metadata-label">Query:</span>+ <span id="result-query" class="metadata-value"></span>+ </div>+ <div class="metadata-item">+ <span class="metadata-label">Generated:</span>+ <span id="result-date" class="metadata-value"></span>+ </div>+ <div class="metadata-item">+ <span class="metadata-label">Mode:</span>+ <span id="result-mode" class="metadata-value"></span>+ </div>+ </div>+ <div class="results-content" id="results-content">+ <!-- Will be populated dynamically -->+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>+ </div>++ <!-- Templates -->+ <template id="history-item-template">+ <div class="history-item">+ <div class="history-item-header">+ <div class="history-item-title"></div>+ <div class="history-item-status"></div>+ </div>+ <div class="history-item-meta">+ <div class="history-item-date"></div>+ <div class="history-item-mode"></div>+ </div>+ <div class="history-item-actions">+ <button class="btn btn-sm btn-outline view-btn"><i class="fas fa-eye"></i> View</button>+ <button class="btn btn-sm btn-outline pdf-btn" style="display: none;"><i class="fas fa-file-pdf"></i> PDF</button>+ <!-- Delete button will be added dynamically -->+ </div>+ </div>+ </template>++ <!-- Mobile Tab Bar -->+ <nav class="mobile-tab-bar">+ <ul>+ <li class="active" data-page="new-research">+ <i class="fas fa-search"></i>+ <span>Research</span>+ </li>+ <li data-page="history">+ <i class="fas fa-history"></i>+ <span>History</span>+ </li>+ </ul>+ </nav>++ <template id="log-entry-template">+ <div class="log-entry">+ <div class="log-entry-time"></div>+ <div class="log-entry-content">+ <div class="log-entry-message"></div>+ <div class="log-entry-progress"></div>+ </div>+ </div>+ </template>++ <!-- Updated Scripts with proper CDN versions -->+ <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.min.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js"></script>+ <!-- Update highlight.js to browser compatible version -->+ <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>+ <!-- PDF generation libraries -->+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>+ <script src="{{ url_for('static', filename='js/app.js') }}"></script>+ <script>+ document.addEventListener('DOMContentLoaded', function() {+ // Initialize the terminate button event listener+ const terminateBtn = document.getElementById('terminate-research-btn');+ if (terminateBtn) {+ terminateBtn.addEventListener('click', function() {+ // Get the current research ID from the page+ const currentResearchId = window.currentResearchId;+ if (currentResearchId) {+ window.terminateResearch(currentResearchId);+ } else {+ console.error('No active research ID found');+ alert('No active research found to terminate');+ }+ });+ }+ });++ // Configure marked to not use eval+ if (typeof marked !== 'undefined') {+ marked.setOptions({+ headerIds: false,+ mangle: false,+ smartypants: false+ });+ }++ // Configure html2canvas to avoid using eval if possible+ if (typeof html2canvas !== 'undefined') {+ // Disable features that might use eval+ window.html2canvas_noSandbox = true;+ }+ </script>+</body>+</html>\ No newline at end of file