~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
refactor: split app.py into modular components and implement app factory pattern
hashedviking3d3bb0daa61c
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex 4adbed4ff0..37f10053d3 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -1,1946 +1,20 @@-import json-import loggingimport os-import platform-import sqlite3-import subprocess-import threading-import traceback-from datetime import datetime--import importlib_resources-import toml--# Move this import up to ensure it's available globally-from dateutil import parser-from flask import (- Blueprint,- Flask,- flash,- jsonify,- make_response,- redirect,- render_template,- request,- send_from_directory,- url_for,-)-from flask_socketio import SocketIO, emit+import logging-# Import the new configuration manager-from ..config import SEARCH_ENGINES_FILE, get_config_dir-from ..report_generator import IntegratedReportGenerator-from ..search_system import AdvancedSearchSystem+from .app_factory import create_app+from ..config import settings+# Initialize loggerlogger = logging.getLogger(__name__)-CONFIG_DIR = get_config_dir() / "config"-MAIN_CONFIG_FILE = CONFIG_DIR / "settings.toml"-LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"--# Set flag for tracking OpenAI availability - we'll check it only when needed-OPENAI_AVAILABLE = False--# Initialize Flask app-try:- from ..utilties.setup_utils import setup_user_directories-- # Configure logging- logging.basicConfig(level=logging.INFO)- logger = logging.getLogger(__name__)-- # Explicitly run setup- logger.info("Initializing configuration...")- setup_user_directories()-- # Get directories based on package installation- PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"- with importlib_resources.as_file(PACKAGE_DIR) as package_dir:- STATIC_DIR = (package_dir / "static").as_posix()- TEMPLATE_DIR = (package_dir / "templates").as_posix()-- # Setup logging- logging.basicConfig(level=logging.INFO)-- # Create directories and default configs if needed- setup_user_directories()-- # Initialize Flask app with package directories- app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)- print(f"Using package static path: {STATIC_DIR}")- print(f"Using package template path: {TEMPLATE_DIR}")-except Exception as e:- # Fallback for development- print(f"Package directories not found, using fallback paths: {str(e)}")- app = Flask(- __name__,- static_folder=os.path.abspath("static"),- template_folder=os.path.abspath("templates"),- )-app.config["SECRET_KEY"] = "deep-research-secret-key"--# Create a Blueprint for the research application-research_bp = Blueprint("research", __name__, url_prefix="/research")--# Add improved Socket.IO configuration with better error handling-socketio = SocketIO(- app,- cors_allowed_origins="*",- async_mode="threading",- path="/research/socket.io",- logger=True,- engineio_logger=True,- ping_timeout=20,- ping_interval=5,-)--# Active research processes and socket subscriptions-active_research = {}-socket_subscriptions = {}--# Add termination flags dictionary-termination_flags = {}--# Database setup-DB_PATH = "research_history.db"--# Output directory for research results-OUTPUT_DIR = "research_outputs"---# 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---# Add a middleware layer to handle abrupt disconnections[email protected]_request-def handle_websocket_requests():- if request.path.startswith("/research/socket.io"):- try:- if not request.environ.get("werkzeug.socket"):- return- except Exception as e:- print(f"WebSocket preprocessing error: {e}")- # Return empty response to prevent further processing- return "", 200---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,- progress INTEGER- )- """- )-- # Create a dedicated table for research logs- cursor.execute(- """- CREATE TABLE IF NOT EXISTS research_logs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- research_id INTEGER NOT NULL,- timestamp TEXT NOT NULL,- message TEXT NOT NULL,- log_type TEXT NOT NULL,- progress INTEGER,- metadata TEXT,- FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE- )- """- )-- # 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"- )-- # Check if the progress column exists, add it if missing- if "progress" not in columns:- print("Adding missing 'progress' column to research_history table")- cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")-- # Enable foreign key support- cursor.execute("PRAGMA foreign_keys = ON")-- conn.commit()- conn.close()---# Helper function to calculate duration between created_at and completed_at 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 Exception:- print(- f"Fallback duration calculation also failed for timestamp: {created_at_str}"- )-- return duration_seconds---# Add these helper functions after the calculate_duration function---def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):- """- Store a log entry in the database-- Args:- research_id: ID of the research- message: Log message text- log_type: Type of log (info, error, milestone)- progress: Progress percentage (0-100)- metadata: Additional metadata as dictionary (will be stored as JSON)- """- try:- timestamp = datetime.utcnow().isoformat()- metadata_json = json.dumps(metadata) if metadata else None-- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- cursor.execute(- "INSERT INTO research_logs (research_id, timestamp, message, log_type, progress, metadata) "- "VALUES (?, ?, ?, ?, ?, ?)",- (research_id, timestamp, message, log_type, progress, metadata_json),- )- conn.commit()- conn.close()- return True- except Exception as e:- print(f"Error adding log to database: {str(e)}")- print(traceback.format_exc())- return False---def get_logs_for_research(research_id):- """- Retrieve all logs for a specific research ID-- Args:- research_id: ID of the research-- Returns:- List of log entries as dictionaries- """- try:- conn = sqlite3.connect(DB_PATH)- conn.row_factory = sqlite3.Row- cursor = conn.cursor()- cursor.execute(- "SELECT * FROM research_logs WHERE research_id = ? ORDER BY timestamp ASC",- (research_id,),- )- results = cursor.fetchall()- conn.close()-- logs = []- for result in results:- log_entry = dict(result)- # Parse metadata JSON if it exists- if log_entry.get("metadata"):- try:- log_entry["metadata"] = json.loads(log_entry["metadata"])- except Exception:- log_entry["metadata"] = {}- else:- log_entry["metadata"] = {}-- # Convert entry for frontend consumption- formatted_entry = {- "time": log_entry["timestamp"],- "message": log_entry["message"],- "progress": log_entry["progress"],- "metadata": log_entry["metadata"],- "type": log_entry["log_type"],- }- logs.append(formatted_entry)-- return logs- except Exception as e:- print(f"Error retrieving logs from database: {str(e)}")- print(traceback.format_exc())- return []---# Initialize the database on startup-def initialize():- init_db()---# Call initialize immediately when app is created-initialize()---# Route for index page - keep this at root level for easy access[email protected]("/")-def root_index():- return redirect(url_for("research.index"))---# Update all routes with the research prefix-@research_bp.route("/")-def index():- return render_template("index.html")---@research_bp.route("/static/<path:path>")-def serve_static(path):- try:- print(f"Serving static file: {path}")- print(f"Static folder path: {app.static_folder}")- return send_from_directory(app.static_folder, path)- except Exception as e:- print(f"Error serving static file {path}: {str(e)}")- return f"Error serving file: {str(e)}", 404---@research_bp.route("/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 Exception:- 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 Exception:- 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---@research_bp.route("/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 that's actually still running- if active_research:- # Verify each active research is still valid- stale_research_ids = []- for research_id, research_data in list(active_research.items()):- # Check database status- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?", (research_id,)- )- result = cursor.fetchone()- conn.close()-- # If the research doesn't exist in DB or is not in_progress, it's stale- if not result or result[0] != "in_progress":- stale_research_ids.append(research_id)- # Also check if thread is still alive- elif (- not research_data.get("thread")- or not research_data.get("thread").is_alive()- ):- stale_research_ids.append(research_id)-- # Clean up any stale research processes- for stale_id in stale_research_ids:- print(f"Cleaning up stale research process: {stale_id}")- if stale_id in active_research:- del active_research[stale_id]- if stale_id in termination_flags:- del termination_flags[stale_id]-- # After cleanup, check if there's still active research- if active_research:- return (- jsonify(- {- "status": "error",- "message": "Another research is already in progress. Please wait for it to complete.",- }- ),- 409,- )-- # 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})---@research_bp.route("/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 Exception:- result["log"] = []- else:- result["progress"] = 0- try:- result["log"] = json.loads(result.get("progress_log", "[]"))- except Exception:- result["log"] = []-- return jsonify(result)---@research_bp.route("/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-- # Get logs from the dedicated log database- logs = get_logs_for_research(research_id)-- # If this is an active research, merge with any in-memory logs- if research_id in active_research:- # Use the logs from memory temporarily until they're saved to the database- memory_logs = active_research[research_id]["log"]-- # Filter out logs that are already in the database by timestamp- db_timestamps = {log["time"] for log in logs}- unique_memory_logs = [- log for log in memory_logs if log["time"] not in db_timestamps- ]-- # Add unique memory logs to our return list- logs.extend(unique_memory_logs)-- # Sort logs by timestamp- logs.sort(key=lambda x: x["time"])-- return jsonify(- {- "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": logs,- }- )---@research_bp.route("/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---@research_bp.route("/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():- try:- 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)- print(f"Removed empty subscription for research {research_id}")- except Exception as e:- print(f"Error handling disconnect: {e}")--[email protected]("subscribe_to_research")-def handle_subscribe(data):- research_id = data.get("research_id")- if research_id:- # First check if this research is still active- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?", (research_id,)- )- result = cursor.fetchone()- conn.close()-- # Only allow subscription to valid research- if result:- status = result[0]-- # Initialize subscription set if needed- if research_id not in socket_subscriptions:- socket_subscriptions[research_id] = set()-- # Add this client to the subscribers- 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,- },- )- elif status in ["completed", "failed", "suspended"]:- # Send final status for completed research- emit(- f"research_progress_{research_id}",- {- "progress": 100 if status == "completed" else 0,- "message": (- "Research completed successfully"- if status == "completed"- else (- "Research failed"- if status == "failed"- else "Research was suspended"- )- ),- "status": status,- "log_entry": {- "time": datetime.utcnow().isoformat(),- "message": f"Research is {status}",- "progress": 100 if status == "completed" else 0,- "metadata": {- "phase": (- "complete" if status == "completed" else "error"- )- },- },- },- )- else:- # Research not found- emit("error", {"message": f"Research ID {research_id} not found"})--[email protected]_error-def handle_socket_error(e):- print(f"Socket.IO error: {str(e)}")- # Don't propagate exceptions to avoid crashing the server- return False--[email protected]_error_default-def handle_default_error(e):- print(f"Unhandled Socket.IO error: {str(e)}")- # Don't propagate exceptions to avoid crashing the server- return False---# Function to clean up resources for a completed research-def cleanup_research_resources(research_id):- """Clean up resources for a completed research"""- print(f"Cleaning up resources for research {research_id}")-- # Get the current status from the database to determine the final status message- current_status = "completed" # Default- try:- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?", (research_id,)- )- result = cursor.fetchone()- if result and result[0]:- current_status = result[0]- conn.close()- except Exception as e:- print(f"Error retrieving research status during cleanup: {e}")-- # Remove from active research- if research_id in active_research:- del active_research[research_id]-- # Remove from termination flags- if research_id in termination_flags:- del termination_flags[research_id]-- # Send a final message to any remaining subscribers with explicit status- if research_id in socket_subscriptions and socket_subscriptions[research_id]:- # Use the proper status message based on database status- if current_status == "suspended" or current_status == "failed":- final_message = {- "status": current_status,- "message": f"Research was {current_status}",- "progress": 0, # For suspended research, show 0% not 100%- }- else:- final_message = {- "status": "completed",- "message": "Research process has ended and resources have been cleaned up",- "progress": 100,- }-- try:- print(- f"Sending final {current_status} socket message for research {research_id}"- )- # Use emit to all, not just subscribers- socketio.emit(f"research_progress_{research_id}", final_message)-- # Also emit to specific subscribers- for sid in socket_subscriptions[research_id]:- try:- socketio.emit(- f"research_progress_{research_id}", final_message, room=sid- )- except Exception as sub_err:- print(f"Error emitting to subscriber {sid}: {str(sub_err)}")- except Exception as e:- print(f"Error sending final cleanup message: {e}")-- # Don't immediately remove subscriptions - let clients disconnect naturally---def run_research_process(research_id, query, mode):- """Run the research process in the background for a given research ID"""- try:- # Check if this research has been terminated before we even start- if research_id in termination_flags and termination_flags[research_id]:- print(f"Research {research_id} was terminated before starting")- cleanup_research_resources(research_id)- return-- print(f"Starting research process for ID {research_id}, query: {query}")-- # Set up the AI Context Manager- output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")- os.makedirs(output_dir, exist_ok=True)-- # Set up progress callback- def progress_callback(message, progress_percent, metadata):- # FREQUENT TERMINATION CHECK: Check for termination at each callback- if research_id in termination_flags and termination_flags[research_id]:- # Explicitly set the status to suspended in the database- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- # Calculate duration up to termination point - using UTC consistently- now = datetime.utcnow()- completed_at = now.isoformat()-- # Get the start time from the database- cursor.execute(- "SELECT created_at FROM research_history WHERE id = ?",- (research_id,),- )- result = cursor.fetchone()-- # Calculate the duration- duration_seconds = (- calculate_duration(result[0]) if result and result[0] else None- )-- # Update the database with suspended status- cursor.execute(- "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",- ("suspended", completed_at, duration_seconds, research_id),- )- conn.commit()- conn.close()-- # Clean up resources- cleanup_research_resources(research_id)-- # Raise exception to exit the process- raise Exception("Research was terminated by user")-- timestamp = datetime.utcnow().isoformat()-- # Adjust progress based on research mode- adjusted_progress = progress_percent- if mode == "detailed" and metadata.get("phase") == "output_generation":- # For detailed mode, we need to adjust the progress range- # because detailed reports take longer after the search phase- adjusted_progress = min(80, progress_percent)- elif mode == "detailed" and metadata.get("phase") == "report_generation":- # Scale the progress from 80% to 95% for the report generation phase- # Map progress_percent values (0-100%) to the (80-95%) range- if progress_percent is not None:- normalized = progress_percent / 100- adjusted_progress = 80 + (normalized * 15)- elif mode == "quick" and metadata.get("phase") == "output_generation":- # For quick mode, ensure we're at least at 85% during output generation- adjusted_progress = max(85, progress_percent)- # Map any further progress within output_generation to 85-95% range- if progress_percent is not None and progress_percent > 0:- normalized = progress_percent / 100- adjusted_progress = 85 + (normalized * 10)-- # Don't let progress go backwards- if research_id in active_research and adjusted_progress is not None:- current_progress = active_research[research_id].get("progress", 0)- adjusted_progress = max(current_progress, adjusted_progress)-- log_entry = {- "time": timestamp,- "message": message,- "progress": adjusted_progress,- "metadata": metadata,- }-- # Check if termination was requested- if research_id in termination_flags and termination_flags[research_id]:- # Explicitly set the status to suspended in the database- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- # Calculate duration up to termination point - using UTC consistently- now = datetime.utcnow()- completed_at = now.isoformat()-- # Get the start time from the database- cursor.execute(- "SELECT created_at FROM research_history WHERE id = ?",- (research_id,),- )- result = cursor.fetchone()-- # Calculate the duration- duration_seconds = (- calculate_duration(result[0]) if result and result[0] else None- )-- # Update the database with suspended status- cursor.execute(- "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",- ("suspended", completed_at, duration_seconds, research_id),- )- conn.commit()- conn.close()-- # Clean up resources- cleanup_research_resources(research_id)-- # Raise exception to exit the process- 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 adjusted_progress is not None:- active_research[research_id]["progress"] = adjusted_progress-- # Determine log type for database storage- log_type = "info"- if metadata and metadata.get("phase"):- phase = metadata.get("phase")- if phase in ["complete", "iteration_complete"]:- log_type = "milestone"- elif phase == "error" or "error" in message.lower():- log_type = "error"-- # Always save logs to the new research_logs table- add_log_to_db(- research_id,- message,- log_type=log_type,- progress=adjusted_progress,- metadata=metadata,- )-- # Update progress in the research_history table (for backward compatibility)- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()-- # Update the progress and log separately to avoid race conditions with reading/writing the log- if adjusted_progress is not None:- cursor.execute(- "UPDATE research_history SET progress = ? WHERE id = ?",- (adjusted_progress, research_id),- )-- # Add the log entry to the progress_log- cursor.execute(- "SELECT progress_log FROM research_history WHERE id = ?",- (research_id,),- )- log_result = cursor.fetchone()-- if log_result:- try:- current_log = json.loads(log_result[0])- except Exception:- current_log = []-- current_log.append(log_entry)- cursor.execute(- "UPDATE research_history SET progress_log = ? WHERE id = ?",- (json.dumps(current_log), research_id),- )-- conn.commit()- conn.close()-- # Emit a socket event- try:- # Basic event data- event_data = {"message": message, "progress": adjusted_progress}-- # Add log entry in full format for detailed logging on client- if metadata:- event_data["log_entry"] = log_entry-- # Send to all subscribers and broadcast channel- socketio.emit(f"research_progress_{research_id}", event_data)-- if research_id in socket_subscriptions:- 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 e:- print(f"Socket emit error (non-critical): {str(e)}")-- # FUNCTION TO CHECK TERMINATION DURING LONG-RUNNING OPERATIONS- def check_termination():- if research_id in termination_flags and termination_flags[research_id]:- # Explicitly set the status to suspended in the database- conn = sqlite3.connect(DB_PATH)- cursor = conn.cursor()- now = datetime.utcnow()- completed_at = now.isoformat()-- cursor.execute(- "SELECT created_at FROM research_history WHERE id = ?",- (research_id,),- )- result = cursor.fetchone()- duration_seconds = (- calculate_duration(result[0]) if result and result[0] else None- )-- cursor.execute(- "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",- ("suspended", completed_at, duration_seconds, research_id),- )- conn.commit()- conn.close()-- # Clean up resources- cleanup_research_resources(research_id)-- # Raise exception to exit the process- raise Exception(- "Research was terminated by user during long-running operation"- )- return False # Not terminated-- # Set the progress callback in the system- system = AdvancedSearchSystem()- system.set_progress_callback(progress_callback)-- # Run the search- progress_callback("Starting research process", 5, {"phase": "init"})-- try:- results = system.analyze_topic(query)- if mode == "quick":- progress_callback(- "Search complete, preparing to generate summary...",- 85,- {"phase": "output_generation"},- )- else:- progress_callback(- "Search complete, generating output",- 80,- {"phase": "output_generation"},- )- except Exception as search_error:- # Better handling of specific search errors- error_message = str(search_error)- error_type = "unknown"-- # Extract error details for common issues- if "status code: 503" in error_message:- error_message = "Ollama AI service is unavailable (HTTP 503). Please check that Ollama is running properly on your system."- error_type = "ollama_unavailable"- elif "status code: 404" in error_message:- error_message = "Ollama model not found (HTTP 404). Please check that you have pulled the required model."- error_type = "model_not_found"- elif "status code:" in error_message:- # Extract the status code for other HTTP errors- status_code = error_message.split("status code:")[1].strip()- error_message = f"API request failed with status code {status_code}. Please check your configuration."- error_type = "api_error"- elif "connection" in error_message.lower():- error_message = "Connection error. Please check that your LLM service (Ollama/API) is running and accessible."- error_type = "connection_error"-- # Raise with improved error message- raise Exception(f"{error_message} (Error type: {error_type})")-- # Generate output based on mode- if mode == "quick":- # Quick Summary- if results.get("findings") or results.get("formatted_findings"):-- raw_formatted_findings = results["formatted_findings"]- logger.info(- f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"- )-- try:- clean_markdown = raw_formatted_findings- # ADDED CODE: Convert debug output to clean markdown- # clean_markdown = convert_debug_to_markdown(raw_formatted_findings, query)- print(- f"Successfully converted to clean markdown of length: {len(clean_markdown)}"- )-- # First send a progress update for generating the summary- progress_callback(- "Generating clean summary from research data...",- 90,- {"phase": "output_generation"},- )-- # 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"- )-- # Send progress update for writing to file- progress_callback(- "Writing research report to file...",- 95,- {"phase": "report_complete"},- )-- print(f"Writing report to: {report_path}")- 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(- clean_markdown- ) # Use clean markdown instead of raw findings- 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()-- print(f"Updating database for research_id: {research_id}")- # 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()- print(- f"Database updated successfully for research_id: {research_id}"- )-- # Send the final completion message- progress_callback(- "Research completed successfully",- 100,- {"phase": "complete", "report_path": report_path},- )-- # Clean up resources- print(f"Cleaning up resources for research_id: {research_id}")- cleanup_research_resources(research_id)- print(f"Resources cleaned up for research_id: {research_id}")- except Exception as inner_e:- print(f"Error during quick summary generation: {str(inner_e)}")- print(traceback.format_exc())- raise Exception(f"Error generating quick summary: {str(inner_e)}")- else:- raise Exception(- "No research findings were generated. Please try again."- )- else:- # Full Report- progress_callback(- "Generating detailed report...", 85, {"phase": "report_generation"}- )- report_generator = IntegratedReportGenerator()- final_report = report_generator.generate_report(results, 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 - moved to a separate function for reuse- cleanup_research_resources(research_id)-- except Exception as e:- # Handle error- error_message = f"Research failed: {str(e)}"- print(f"Research error: {error_message}")- try:- # Check for common Ollama error patterns in the exception and provide more user-friendly errors- user_friendly_error = str(e)- error_context = {}-- if "Error type: ollama_unavailable" in user_friendly_error:- user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."- error_context = {- "solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."- }- elif "Error type: model_not_found" in user_friendly_error:- user_friendly_error = (- "Required Ollama model not found. Please pull the model first."- )- error_context = {- "solution": "Run 'ollama pull mistral' to download the required model."- }- elif "Error type: connection_error" in user_friendly_error:- user_friendly_error = "Connection error with LLM service. Please check that your AI service is running."- error_context = {- "solution": "Ensure Ollama or your API service is running and accessible."- }- elif "Error type: api_error" in user_friendly_error:- # Keep the original error message as it's already improved- error_context = {"solution": "Check API configuration and credentials."}-- # Update metadata with more context about the error- metadata = {"phase": "error", "error": user_friendly_error}- if error_context:- metadata.update(error_context)-- progress_callback(user_friendly_error, None, metadata)-- 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 user_friendly_error- )-- # 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(metadata),- 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 - moved to a separate function for reuse- cleanup_research_resources(research_id)---@research_bp.route("/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()- termination_message = "Research termination requested by user"- current_progress = active_research[research_id]["progress"]-- # Create log entry- log_entry = {- "time": timestamp,- "message": termination_message,- "progress": current_progress,- "metadata": {"phase": "termination"},- }-- # Add to in-memory log- active_research[research_id]["log"].append(log_entry)-- # Add to database log- add_log_to_db(- research_id,- termination_message,- log_type="milestone",- progress=current_progress,- metadata={"phase": "termination"},- )-- # Update the log in the database (old way for backward compatibility)- cursor.execute(- "SELECT progress_log FROM research_history WHERE id = ?", (research_id,)- )- log_result = cursor.fetchone()- if log_result:- try:- current_log = json.loads(log_result[0])- except Exception:- current_log = []- current_log.append(log_entry)- cursor.execute(- "UPDATE research_history SET progress_log = ? WHERE id = ?",- (json.dumps(current_log), research_id),- )-- # IMMEDIATELY update the status to 'suspended' to avoid race conditions- cursor.execute(- "UPDATE research_history SET status = ? WHERE id = ?",- ("suspended", research_id),- )- conn.commit()- conn.close()-- # Emit a socket event for the termination request- try:- event_data = {- "status": "suspended", # Changed from 'terminating' to 'suspended'- "message": "Research was suspended by user request",- }-- 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"})---@research_bp.route("/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"})---@research_bp.route("/settings", methods=["GET"])-def settings_page():- """Main settings dashboard with links to specialized config pages"""- return render_template("settings_dashboard.html")---@research_bp.route("/settings/main", methods=["GET"])-def main_config_page():- """Edit main configuration with search parameters"""- return render_template("main_config.html", main_file_path=MAIN_CONFIG_FILE)--@research_bp.route("/settings/collections", methods=["GET"])-def collections_config_page():- """Edit local collections configuration using raw file editor"""- return render_template(- "collections_config.html", collections_file_path=LOCAL_COLLECTIONS_FILE- )---@research_bp.route("/settings/api_keys", methods=["GET"])-def api_keys_config_page():- """Edit API keys configuration"""- # Get the secrets file path- secrets_file = CONFIG_DIR / ".secrets.toml"-- return render_template("api_keys_config.html", secrets_file_path=secrets_file)---# Add a new route for search engines configuration page-@research_bp.route("/settings/search_engines", methods=["GET"])-def search_engines_config_page():- """Edit search engines configuration using raw file editor"""- # Read the current config file- raw_config = ""- try:- with open(SEARCH_ENGINES_FILE, "r") as f:- raw_config = f.read()- except Exception as e:- flash(f"Error reading search engines configuration: {str(e)}", "error")- raw_config = "# Error reading configuration file"-- # Get list of engine names for display- engine_names = []- try:- from ..web_search_engines.search_engines_config import SEARCH_ENGINES-- engine_names = list(SEARCH_ENGINES.keys())- engine_names.sort() # Alphabetical order- except Exception as e:- logger.error(f"Error getting engine names: {e}")-- return render_template(- "search_engines_config.html",- search_engines_file_path=SEARCH_ENGINES_FILE,- raw_config=raw_config,- engine_names=engine_names,- )---# Add a route to save search engines configuration-@research_bp.route("/api/save_search_engines_config", methods=["POST"])-def save_search_engines_config():- try:- data = request.get_json()- raw_config = data.get("raw_config", "")-- # Validate TOML syntax- try:- toml.loads(raw_config)- except toml.TomlDecodeError as e:- return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})-- # Ensure directory exists- os.makedirs(os.path.dirname(SEARCH_ENGINES_FILE), exist_ok=True)-- # Create a backup first- backup_path = f"{SEARCH_ENGINES_FILE}.bak"- if os.path.exists(SEARCH_ENGINES_FILE):- import shutil-- shutil.copy2(SEARCH_ENGINES_FILE, backup_path)-- # Write new config- with open(SEARCH_ENGINES_FILE, "w") as f:- f.write(raw_config)-- return jsonify({"success": True})- except Exception as e:- return jsonify({"success": False, "error": str(e)})---# API endpoint to save raw collections config-@research_bp.route("/api/save_collections_config", methods=["POST"])-def save_collections_config():- try:- data = request.get_json()- raw_config = data.get("raw_config", "")-- # Validate TOML syntax- try:- toml.loads(raw_config)- except toml.TomlDecodeError as e:- return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})-- # Ensure directory exists- os.makedirs(os.path.dirname(LOCAL_COLLECTIONS_FILE), exist_ok=True)-- # Create a backup first- backup_path = f"{LOCAL_COLLECTIONS_FILE}.bak"- if os.path.exists(LOCAL_COLLECTIONS_FILE):- import shutil-- shutil.copy2(LOCAL_COLLECTIONS_FILE, backup_path)-- # Write new config- with open(LOCAL_COLLECTIONS_FILE, "w") as f:- f.write(raw_config)-- # Also trigger a reload in the collections system- try:- # TODO (djpetti) Fix collection reloading.- load_local_collections(reload=True) # noqa: F821- except Exception as reload_error:- return jsonify(- {- "success": True,- "warning": f"Config saved, but error reloading: {str(reload_error)}",- }- )-- return jsonify({"success": True})- except Exception as e:- return jsonify({"success": False, "error": str(e)})---# API endpoint to save raw main config-@research_bp.route("/api/save_main_config", methods=["POST"])-def save_raw_main_config():- try:- data = request.get_json()- raw_config = data.get("raw_config", "")-- # Validate TOML syntax- try:- toml.loads(raw_config)- except toml.TomlDecodeError as e:- return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})-- # Ensure directory exists- os.makedirs(os.path.dirname(MAIN_CONFIG_FILE), exist_ok=True)-- # Create a backup first- backup_path = f"{MAIN_CONFIG_FILE}.bak"- if os.path.exists(MAIN_CONFIG_FILE):- import shutil-- shutil.copy2(MAIN_CONFIG_FILE, backup_path)-- # Write new config- with open(MAIN_CONFIG_FILE, "w") as f:- f.write(raw_config)-- return jsonify({"success": True})- except Exception as e:- return jsonify({"success": False, "error": str(e)})---@research_bp.route("/raw_config")-def get_raw_config():- """Return the raw configuration file content"""- try:- # Determine which config file to load based on a query parameter- config_type = request.args.get("type", "main")-- if config_type == "main":- config_path = os.path.join(app.config["CONFIG_DIR"], "config.toml")- with open(config_path, "r") as f:- return f.read()- elif config_type == "llm":- config_path = os.path.join(app.config["CONFIG_DIR"], "llm_config.py")- with open(config_path, "r") as f:- return f.read()- elif config_type == "collections":- config_path = os.path.join(app.config["CONFIG_DIR"], "collections.toml")- with open(config_path, "r") as f:- return f.read()- else:- return "Unknown configuration type", 400- except Exception as e:- return str(e), 500---@research_bp.route("/open_file_location", methods=["POST"])-def open_file_location():- file_path = request.form.get("file_path")-- if not file_path:- flash("No file path provided", "error")- return redirect(url_for("research.settings_page"))-- # Get the directory containing the file- dir_path = os.path.dirname(os.path.abspath(file_path))-- # Open the directory in the file explorer- try:- if platform.system() == "Windows":- subprocess.Popen(f'explorer "{dir_path}"')- elif platform.system() == "Darwin": # macOS- subprocess.Popen(["open", dir_path])- else: # Linux- subprocess.Popen(["xdg-open", dir_path])-- flash(f"Opening folder: {dir_path}", "success")- except Exception as e:- flash(f"Error opening folder: {str(e)}", "error")-- # Redirect back to the settings page- if "llm" in file_path:- return redirect(url_for("research.llm_config_page"))- elif "collections" in file_path:- return redirect(url_for("research.collections_config_page"))- else:- return redirect(url_for("research.main_config_page"))---@research_bp.route("/api/research/<int:research_id>/logs")-def get_research_logs(research_id):- """Get logs for a specific research ID"""- # First check if the research exists- conn = sqlite3.connect(DB_PATH)- conn.row_factory = sqlite3.Row- cursor = conn.cursor()- cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))- result = cursor.fetchone()- conn.close()-- if not result:- return jsonify({"status": "error", "message": "Research not found"}), 404-- # Retrieve logs from the database- logs = get_logs_for_research(research_id)-- # Add any current logs from memory if this is an active research- if research_id in active_research and active_research[research_id].get("log"):- # Use the logs from memory temporarily until they're saved to the database- memory_logs = active_research[research_id]["log"]-- # Filter out logs that are already in the database- # We'll compare timestamps to avoid duplicates- db_timestamps = {log["time"] for log in logs}- unique_memory_logs = [- log for log in memory_logs if log["time"] not in db_timestamps- ]-- # Add unique memory logs to our return list- logs.extend(unique_memory_logs)-- # Sort logs by timestamp- logs.sort(key=lambda x: x["time"])-- return jsonify({"status": "success", "logs": logs})---# Register the blueprint-app.register_blueprint(research_bp)---# Also add the static route at the app level for compatibility[email protected]("/static/<path:path>")-def app_serve_static(path):- return send_from_directory(app.static_folder, path)---# Add favicon route to prevent 404 errors[email protected]("/favicon.ico")-def favicon():- return send_from_directory(- app.static_folder, "favicon.ico", mimetype="image/x-icon"- )---# Add this function to app.py-def convert_debug_to_markdown(raw_text, query):- """- Convert the debug-formatted text to clean markdown.-- Args:- raw_text: The raw formatted findings with debug symbols- query: Original research query-- Returns:- Clean markdown formatted text- """- try:- print(f"Starting markdown conversion for query: {query}")- print(f"Raw text type: {type(raw_text)}")-- # Handle None or empty input- if not raw_text:- print("WARNING: raw_text is empty or None")- return f"No detailed findings available for '{query}'."-- # If there's a "DETAILED FINDINGS:" section, extract everything after it- if "DETAILED FINDINGS:" in raw_text:- print("Found DETAILED FINDINGS section")- detailed_index = raw_text.index("DETAILED FINDINGS:")- content = raw_text[detailed_index + len("DETAILED FINDINGS:") :].strip()- else:- print("No DETAILED FINDINGS section found, using full text")- content = raw_text-- # Remove divider lines with === symbols- lines_before = len(content.split("\n"))- content = "\n".join(- [- line- for line in content.split("\n")- if not line.strip().startswith("===") and not line.strip() == "=" * 80- ]- )- lines_after = len(content.split("\n"))- print(f"Removed {lines_before - lines_after} divider lines")-- # Remove SEARCH QUESTIONS BY ITERATION section- if "SEARCH QUESTIONS BY ITERATION:" in content:- print("Found SEARCH QUESTIONS BY ITERATION section")- search_index = content.index("SEARCH QUESTIONS BY ITERATION:")- next_major_section = -1- for marker in ["DETAILED FINDINGS:", "COMPLETE RESEARCH:"]:- if marker in content[search_index:]:- marker_pos = content.index(marker, search_index)- if next_major_section == -1 or marker_pos < next_major_section:- next_major_section = marker_pos-- if next_major_section != -1:- print(- f"Removing section from index {search_index} to {next_major_section}"- )- content = content[:search_index] + content[next_major_section:]- else:- # If no later section, just remove everything from SEARCH QUESTIONS onwards- print(f"Removing everything after index {search_index}")- content = content[:search_index].strip()-- print(f"Final markdown length: {len(content.strip())}")- return content.strip()- except Exception as e:- print(f"Error in convert_debug_to_markdown: {str(e)}")- print(traceback.format_exc())- # Return a basic message with the original query as fallback- return f"# Research on {query}\n\nThere was an error formatting the research results."-+# Create the Flask app and SocketIO instance+app, socketio = create_app()def main():"""Entry point for the web application when run as a command.This function is needed for the package's entry point to work properly."""- # Import settings here to avoid circular imports- from ..config import settings-# Get web server settings with defaultsport = settings.web.porthost = settings.web.host@@ -1957,18 +31,18 @@ def main():import openaiopenai.api_key = api_key- print("OpenAI integration is available")+ logger.info("OpenAI integration is available")except ImportError:- print("OpenAI package not installed, integration disabled")+ logger.info("OpenAI package not installed, integration disabled")else:- print(+ logger.info("OPENAI_API_KEY not found in environment variables, OpenAI integration disabled")except Exception as e:- print(f"Error checking OpenAI availability: {e}")+ logger.error(f"Error checking OpenAI availability: {e}")+ logger.info(f"Starting web server on {host}:{port} (debug: {debug})")socketio.run(app, debug=debug, host=host, port=port, allow_unsafe_werkzeug=True)-if __name__ == "__main__":- main()+ main()\ No newline at end of filediff --git a/src/local_deep_research/web/app.py.old b/src/local_deep_research/web/app.py.oldnew file mode 100644index 0000000000..e926ca410d--- /dev/null+++ b/src/local_deep_research/web/app.py.old@@ -0,0 +1,1974 @@+import json+import logging+import os+import platform+import sqlite3+import subprocess+import threading+import traceback+from datetime import datetime++from importlib import resources as importlib_resources+import toml++# Move this import up to ensure it's available globally+from dateutil import parser+from flask import (+ Blueprint,+ Flask,+ flash,+ jsonify,+ make_response,+ redirect,+ render_template,+ request,+ send_from_directory,+ url_for,+)+from flask_socketio import SocketIO, emit++# Import the new configuration manager+from ..config import SEARCH_ENGINES_FILE, get_config_dir+from ..report_generator import IntegratedReportGenerator+from ..search_system import AdvancedSearchSystem++logger = logging.getLogger(__name__)++CONFIG_DIR = get_config_dir() / "config"+MAIN_CONFIG_FILE = CONFIG_DIR / "settings.toml"+LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"++# Set flag for tracking OpenAI availability - we'll check it only when needed+OPENAI_AVAILABLE = False++# Initialize Flask app+try:+ from ..utilties.setup_utils import setup_user_directories++ # Configure logging+ logging.basicConfig(level=logging.INFO)+ logger = logging.getLogger(__name__)++ # Explicitly run setup+ logger.info("Initializing configuration...")+ setup_user_directories()++ # Get directories based on package installation+ PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"+ with importlib_resources.as_file(PACKAGE_DIR) as package_dir:+ STATIC_DIR = (package_dir / "static").as_posix()+ TEMPLATE_DIR = (package_dir / "templates").as_posix()++ # Setup logging+ logging.basicConfig(level=logging.INFO)++ # Create directories and default configs if needed+ setup_user_directories()++ # Initialize Flask app with package directories+ app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)+ print(f"Using package static path: {STATIC_DIR}")+ print(f"Using package template path: {TEMPLATE_DIR}")+except Exception as e:+ # Fallback for development+ print(f"Package directories not found, using fallback paths: {str(e)}")+ app = Flask(+ __name__,+ static_folder=os.path.abspath("static"),+ template_folder=os.path.abspath("templates"),+ )+app.config["SECRET_KEY"] = "deep-research-secret-key"++# Create a Blueprint for the research application+research_bp = Blueprint("research", __name__, url_prefix="/research")++# Add improved Socket.IO configuration with better error handling+socketio = SocketIO(+ app,+ cors_allowed_origins="*",+ async_mode="threading",+ path="/research/socket.io",+ logger=True,+ engineio_logger=True,+ ping_timeout=20,+ ping_interval=5,+)++# Active research processes and socket subscriptions+active_research = {}+socket_subscriptions = {}++# Add termination flags dictionary+termination_flags = {}++# Database setup+DB_PATH = "research_history.db"++# Output directory for research results+OUTPUT_DIR = "research_outputs"+++# 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+++# Add a middleware layer to handle abrupt disconnections[email protected]_request+def handle_websocket_requests():+ if request.path.startswith("/research/socket.io"):+ try:+ if not request.environ.get("werkzeug.socket"):+ return+ except Exception as e:+ print(f"WebSocket preprocessing error: {e}")+ # Return empty response to prevent further processing+ return "", 200+++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,+ progress INTEGER+ )+ """+ )++ # Create a dedicated table for research logs+ cursor.execute(+ """+ CREATE TABLE IF NOT EXISTS research_logs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ research_id INTEGER NOT NULL,+ timestamp TEXT NOT NULL,+ message TEXT NOT NULL,+ log_type TEXT NOT NULL,+ progress INTEGER,+ metadata TEXT,+ FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE+ )+ """+ )++ # 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"+ )++ # Check if the progress column exists, add it if missing+ if "progress" not in columns:+ print("Adding missing 'progress' column to research_history table")+ cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")++ # Enable foreign key support+ cursor.execute("PRAGMA foreign_keys = ON")++ conn.commit()+ conn.close()+++# Helper function to calculate duration between created_at and completed_at 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 Exception:+ print(+ f"Fallback duration calculation also failed for timestamp: {created_at_str}"+ )++ return duration_seconds+++# Add these helper functions after the calculate_duration function+++def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):+ """+ Store a log entry in the database++ Args:+ research_id: ID of the research+ message: Log message text+ log_type: Type of log (info, error, milestone)+ progress: Progress percentage (0-100)+ metadata: Additional metadata as dictionary (will be stored as JSON)+ """+ try:+ timestamp = datetime.utcnow().isoformat()+ metadata_json = json.dumps(metadata) if metadata else None++ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ "INSERT INTO research_logs (research_id, timestamp, message, log_type, progress, metadata) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (research_id, timestamp, message, log_type, progress, metadata_json),+ )+ conn.commit()+ conn.close()+ return True+ except Exception as e:+ print(f"Error adding log to database: {str(e)}")+ print(traceback.format_exc())+ return False+++def get_logs_for_research(research_id):+ """+ Retrieve all logs for a specific research ID++ Args:+ research_id: ID of the research++ Returns:+ List of log entries as dictionaries+ """+ try:+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute(+ "SELECT * FROM research_logs WHERE research_id = ? ORDER BY timestamp ASC",+ (research_id,),+ )+ results = cursor.fetchall()+ conn.close()++ logs = []+ for result in results:+ log_entry = dict(result)+ # Parse metadata JSON if it exists+ if log_entry.get("metadata"):+ try:+ log_entry["metadata"] = json.loads(log_entry["metadata"])+ except Exception:+ log_entry["metadata"] = {}+ else:+ log_entry["metadata"] = {}++ # Convert entry for frontend consumption+ formatted_entry = {+ "time": log_entry["timestamp"],+ "message": log_entry["message"],+ "progress": log_entry["progress"],+ "metadata": log_entry["metadata"],+ "type": log_entry["log_type"],+ }+ logs.append(formatted_entry)++ return logs+ except Exception as e:+ print(f"Error retrieving logs from database: {str(e)}")+ print(traceback.format_exc())+ return []+++# Initialize the database on startup+def initialize():+ init_db()+++# Call initialize immediately when app is created+initialize()+++# Route for index page - keep this at root level for easy access[email protected]("/")+def root_index():+ return redirect(url_for("research.index"))+++# Update all routes with the research prefix+@research_bp.route("/")+def index():+ return render_template("index.html")+++@research_bp.route("/static/<path:path>")+def serve_static(path):+ try:+ print(f"Serving static file: {path}")+ print(f"Static folder path: {app.static_folder}")+ return send_from_directory(app.static_folder, path)+ except Exception as e:+ print(f"Error serving static file {path}: {str(e)}")+ return f"Error serving file: {str(e)}", 404+++@research_bp.route("/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 Exception:+ 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 Exception:+ 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+++@research_bp.route("/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 that's actually still running+ if active_research:+ # Verify each active research is still valid+ stale_research_ids = []+ for research_id, research_data in list(active_research.items()):+ # Check database status+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ conn.close()++ # If the research doesn't exist in DB or is not in_progress, it's stale+ if not result or result[0] != "in_progress":+ stale_research_ids.append(research_id)+ # Also check if thread is still alive+ elif (+ not research_data.get("thread")+ or not research_data.get("thread").is_alive()+ ):+ stale_research_ids.append(research_id)++ # Clean up any stale research processes+ for stale_id in stale_research_ids:+ print(f"Cleaning up stale research process: {stale_id}")+ if stale_id in active_research:+ del active_research[stale_id]+ if stale_id in termination_flags:+ del termination_flags[stale_id]++ # After cleanup, check if there's still active research+ if active_research:+ return (+ jsonify(+ {+ "status": "error",+ "message": "Another research is already in progress. Please wait for it to complete.",+ }+ ),+ 409,+ )++ # 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})+++@research_bp.route("/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 Exception:+ result["log"] = []+ else:+ result["progress"] = 0+ try:+ result["log"] = json.loads(result.get("progress_log", "[]"))+ except Exception:+ result["log"] = []++ return jsonify(result)+++@research_bp.route("/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++ # Get logs from the dedicated log database+ logs = get_logs_for_research(research_id)++ # If this is an active research, merge with any in-memory logs+ if research_id in active_research:+ # Use the logs from memory temporarily until they're saved to the database+ memory_logs = active_research[research_id]["log"]++ # Filter out logs that are already in the database by timestamp+ db_timestamps = {log["time"] for log in logs}+ unique_memory_logs = [+ log for log in memory_logs if log["time"] not in db_timestamps+ ]++ # Add unique memory logs to our return list+ logs.extend(unique_memory_logs)++ # Sort logs by timestamp+ logs.sort(key=lambda x: x["time"])++ return jsonify(+ {+ "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": logs,+ }+ )+++@research_bp.route("/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+++@research_bp.route("/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():+ try:+ 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)+ print(f"Removed empty subscription for research {research_id}")+ except Exception as e:+ print(f"Error handling disconnect: {e}")++[email protected]("subscribe_to_research")+def handle_subscribe(data):+ research_id = data.get("research_id")+ if research_id:+ # First check if this research is still active+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ conn.close()++ # Only allow subscription to valid research+ if result:+ status = result[0]++ # Initialize subscription set if needed+ if research_id not in socket_subscriptions:+ socket_subscriptions[research_id] = set()++ # Add this client to the subscribers+ 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,+ },+ )+ elif status in ["completed", "failed", "suspended"]:+ # Send final status for completed research+ emit(+ f"research_progress_{research_id}",+ {+ "progress": 100 if status == "completed" else 0,+ "message": (+ "Research completed successfully"+ if status == "completed"+ else (+ "Research failed"+ if status == "failed"+ else "Research was suspended"+ )+ ),+ "status": status,+ "log_entry": {+ "time": datetime.utcnow().isoformat(),+ "message": f"Research is {status}",+ "progress": 100 if status == "completed" else 0,+ "metadata": {+ "phase": (+ "complete" if status == "completed" else "error"+ )+ },+ },+ },+ )+ else:+ # Research not found+ emit("error", {"message": f"Research ID {research_id} not found"})++[email protected]_error+def handle_socket_error(e):+ print(f"Socket.IO error: {str(e)}")+ # Don't propagate exceptions to avoid crashing the server+ return False++[email protected]_error_default+def handle_default_error(e):+ print(f"Unhandled Socket.IO error: {str(e)}")+ # Don't propagate exceptions to avoid crashing the server+ return False+++# Function to clean up resources for a completed research+def cleanup_research_resources(research_id):+ """Clean up resources for a completed research"""+ print(f"Cleaning up resources for research {research_id}")++ # Get the current status from the database to determine the final status message+ current_status = "completed" # Default+ try:+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ if result and result[0]:+ current_status = result[0]+ conn.close()+ except Exception as e:+ print(f"Error retrieving research status during cleanup: {e}")++ # Remove from active research+ if research_id in active_research:+ del active_research[research_id]++ # Remove from termination flags+ if research_id in termination_flags:+ del termination_flags[research_id]++ # Send a final message to any remaining subscribers with explicit status+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ # Use the proper status message based on database status+ if current_status == "suspended" or current_status == "failed":+ final_message = {+ "status": current_status,+ "message": f"Research was {current_status}",+ "progress": 0, # For suspended research, show 0% not 100%+ }+ else:+ final_message = {+ "status": "completed",+ "message": "Research process has ended and resources have been cleaned up",+ "progress": 100,+ }++ try:+ print(+ f"Sending final {current_status} socket message for research {research_id}"+ )+ # Use emit to all, not just subscribers+ socketio.emit(f"research_progress_{research_id}", final_message)++ # Also emit to specific subscribers+ for sid in socket_subscriptions[research_id]:+ try:+ socketio.emit(+ f"research_progress_{research_id}", final_message, room=sid+ )+ except Exception as sub_err:+ print(f"Error emitting to subscriber {sid}: {str(sub_err)}")+ except Exception as e:+ print(f"Error sending final cleanup message: {e}")++ # Don't immediately remove subscriptions - let clients disconnect naturally+++def run_research_process(research_id, query, mode):+ """Run the research process in the background for a given research ID"""+ try:+ # Check if this research has been terminated before we even start+ if research_id in termination_flags and termination_flags[research_id]:+ print(f"Research {research_id} was terminated before starting")+ cleanup_research_resources(research_id)+ return++ print(f"Starting research process for ID {research_id}, query: {query}")++ # Set up the AI Context Manager+ output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")+ os.makedirs(output_dir, exist_ok=True)++ # Set up progress callback+ def progress_callback(message, progress_percent, metadata):+ # FREQUENT TERMINATION CHECK: Check for termination at each callback+ if research_id in termination_flags and termination_flags[research_id]:+ # Explicitly set the status to suspended in the database+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ # Calculate duration up to termination point - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ cursor.execute(+ "SELECT created_at FROM research_history WHERE id = ?",+ (research_id,),+ )+ result = cursor.fetchone()++ # Calculate the duration+ duration_seconds = (+ calculate_duration(result[0]) if result and result[0] else None+ )++ # Update the database with suspended status+ cursor.execute(+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",+ ("suspended", completed_at, duration_seconds, research_id),+ )+ conn.commit()+ conn.close()++ # Clean up resources+ cleanup_research_resources(research_id)++ # Raise exception to exit the process+ raise Exception("Research was terminated by user")++ timestamp = datetime.utcnow().isoformat()++ # Adjust progress based on research mode+ adjusted_progress = progress_percent+ if mode == "detailed" and metadata.get("phase") == "output_generation":+ # For detailed mode, we need to adjust the progress range+ # because detailed reports take longer after the search phase+ adjusted_progress = min(80, progress_percent)+ elif mode == "detailed" and metadata.get("phase") == "report_generation":+ # Scale the progress from 80% to 95% for the report generation phase+ # Map progress_percent values (0-100%) to the (80-95%) range+ if progress_percent is not None:+ normalized = progress_percent / 100+ adjusted_progress = 80 + (normalized * 15)+ elif mode == "quick" and metadata.get("phase") == "output_generation":+ # For quick mode, ensure we're at least at 85% during output generation+ adjusted_progress = max(85, progress_percent)+ # Map any further progress within output_generation to 85-95% range+ if progress_percent is not None and progress_percent > 0:+ normalized = progress_percent / 100+ adjusted_progress = 85 + (normalized * 10)++ # Don't let progress go backwards+ if research_id in active_research and adjusted_progress is not None:+ current_progress = active_research[research_id].get("progress", 0)+ adjusted_progress = max(current_progress, adjusted_progress)++ log_entry = {+ "time": timestamp,+ "message": message,+ "progress": adjusted_progress,+ "metadata": metadata,+ }++ # Check if termination was requested+ if research_id in termination_flags and termination_flags[research_id]:+ # Explicitly set the status to suspended in the database+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ # Calculate duration up to termination point - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ cursor.execute(+ "SELECT created_at FROM research_history WHERE id = ?",+ (research_id,),+ )+ result = cursor.fetchone()++ # Calculate the duration+ duration_seconds = (+ calculate_duration(result[0]) if result and result[0] else None+ )++ # Update the database with suspended status+ cursor.execute(+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",+ ("suspended", completed_at, duration_seconds, research_id),+ )+ conn.commit()+ conn.close()++ # Clean up resources+ cleanup_research_resources(research_id)++ # Raise exception to exit the process+ 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 adjusted_progress is not None:+ active_research[research_id]["progress"] = adjusted_progress++ # Determine log type for database storage+ log_type = "info"+ if metadata and metadata.get("phase"):+ phase = metadata.get("phase")+ if phase in ["complete", "iteration_complete"]:+ log_type = "milestone"+ elif phase == "error" or "error" in message.lower():+ log_type = "error"++ # Always save logs to the new research_logs table+ add_log_to_db(+ research_id,+ message,+ log_type=log_type,+ progress=adjusted_progress,+ metadata=metadata,+ )++ # Update progress in the research_history table (for backward compatibility)+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()++ # Update the progress and log separately to avoid race conditions with reading/writing the log+ if adjusted_progress is not None:+ cursor.execute(+ "UPDATE research_history SET progress = ? WHERE id = ?",+ (adjusted_progress, research_id),+ )++ # Add the log entry to the progress_log+ cursor.execute(+ "SELECT progress_log FROM research_history WHERE id = ?",+ (research_id,),+ )+ log_result = cursor.fetchone()++ if log_result:+ try:+ current_log = json.loads(log_result[0])+ except Exception:+ current_log = []++ current_log.append(log_entry)+ cursor.execute(+ "UPDATE research_history SET progress_log = ? WHERE id = ?",+ (json.dumps(current_log), research_id),+ )++ conn.commit()+ conn.close()++ # Emit a socket event+ try:+ # Basic event data+ event_data = {"message": message, "progress": adjusted_progress}++ # Add log entry in full format for detailed logging on client+ if metadata:+ event_data["log_entry"] = log_entry++ # Send to all subscribers and broadcast channel+ socketio.emit(f"research_progress_{research_id}", event_data)++ if research_id in socket_subscriptions:+ 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 e:+ print(f"Socket emit error (non-critical): {str(e)}")++ # FUNCTION TO CHECK TERMINATION DURING LONG-RUNNING OPERATIONS+ def check_termination():+ if research_id in termination_flags and termination_flags[research_id]:+ # Explicitly set the status to suspended in the database+ conn = sqlite3.connect(DB_PATH)+ cursor = conn.cursor()+ now = datetime.utcnow()+ completed_at = now.isoformat()++ cursor.execute(+ "SELECT created_at FROM research_history WHERE id = ?",+ (research_id,),+ )+ result = cursor.fetchone()+ duration_seconds = (+ calculate_duration(result[0]) if result and result[0] else None+ )++ cursor.execute(+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",+ ("suspended", completed_at, duration_seconds, research_id),+ )+ conn.commit()+ conn.close()++ # Clean up resources+ cleanup_research_resources(research_id)++ # Raise exception to exit the process+ raise Exception(+ "Research was terminated by user during long-running operation"+ )+ return False # Not terminated++ # Set the progress callback in the system+ system = AdvancedSearchSystem()+ system.set_progress_callback(progress_callback)++ # Run the search+ progress_callback("Starting research process", 5, {"phase": "init"})++ try:+ results = system.analyze_topic(query)+ if mode == "quick":+ progress_callback(+ "Search complete, preparing to generate summary...",+ 85,+ {"phase": "output_generation"},+ )+ else:+ progress_callback(+ "Search complete, generating output",+ 80,+ {"phase": "output_generation"},+ )+ except Exception as search_error:+ # Better handling of specific search errors+ error_message = str(search_error)+ error_type = "unknown"++ # Extract error details for common issues+ if "status code: 503" in error_message:+ error_message = "Ollama AI service is unavailable (HTTP 503). Please check that Ollama is running properly on your system."+ error_type = "ollama_unavailable"+ elif "status code: 404" in error_message:+ error_message = "Ollama model not found (HTTP 404). Please check that you have pulled the required model."+ error_type = "model_not_found"+ elif "status code:" in error_message:+ # Extract the status code for other HTTP errors+ status_code = error_message.split("status code:")[1].strip()+ error_message = f"API request failed with status code {status_code}. Please check your configuration."+ error_type = "api_error"+ elif "connection" in error_message.lower():+ error_message = "Connection error. Please check that your LLM service (Ollama/API) is running and accessible."+ error_type = "connection_error"++ # Raise with improved error message+ raise Exception(f"{error_message} (Error type: {error_type})")++ # Generate output based on mode+ if mode == "quick":+ # Quick Summary+ if results.get("findings") or results.get("formatted_findings"):++ raw_formatted_findings = results["formatted_findings"]+ logger.info(+ f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"+ )++ try:+ clean_markdown = raw_formatted_findings+ # ADDED CODE: Convert debug output to clean markdown+ # clean_markdown = convert_debug_to_markdown(raw_formatted_findings, query)+ print(+ f"Successfully converted to clean markdown of length: {len(clean_markdown)}"+ )++ # First send a progress update for generating the summary+ progress_callback(+ "Generating clean summary from research data...",+ 90,+ {"phase": "output_generation"},+ )++ # 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"+ )++ # Send progress update for writing to file+ progress_callback(+ "Writing research report to file...",+ 95,+ {"phase": "report_complete"},+ )++ print(f"Writing report to: {report_path}")+ 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(+ clean_markdown+ ) # Use clean markdown instead of raw findings+ 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()++ print(f"Updating database for research_id: {research_id}")+ # 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()+ print(+ f"Database updated successfully for research_id: {research_id}"+ )++ # Send the final completion message+ progress_callback(+ "Research completed successfully",+ 100,+ {"phase": "complete", "report_path": report_path},+ )++ # Clean up resources+ print(f"Cleaning up resources for research_id: {research_id}")+ cleanup_research_resources(research_id)+ print(f"Resources cleaned up for research_id: {research_id}")+ except Exception as inner_e:+ print(f"Error during quick summary generation: {str(inner_e)}")+ print(traceback.format_exc())+ raise Exception(f"Error generating quick summary: {str(inner_e)}")+ else:+ raise Exception(+ "No research findings were generated. Please try again."+ )+ else:+ # Full Report+ progress_callback(+ "Generating detailed report...", 85, {"phase": "report_generation"}+ )+ report_generator = IntegratedReportGenerator()+ final_report = report_generator.generate_report(results, 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 - moved to a separate function for reuse+ cleanup_research_resources(research_id)++ except Exception as e:+ # Handle error+ error_message = f"Research failed: {str(e)}"+ print(f"Research error: {error_message}")+ try:+ # Check for common Ollama error patterns in the exception and provide more user-friendly errors+ user_friendly_error = str(e)+ error_context = {}++ if "Error type: ollama_unavailable" in user_friendly_error:+ user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."+ error_context = {+ "solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."+ }+ elif "Error type: model_not_found" in user_friendly_error:+ user_friendly_error = (+ "Required Ollama model not found. Please pull the model first."+ )+ error_context = {+ "solution": "Run 'ollama pull mistral' to download the required model."+ }+ elif "Error type: connection_error" in user_friendly_error:+ user_friendly_error = "Connection error with LLM service. Please check that your AI service is running."+ error_context = {+ "solution": "Ensure Ollama or your API service is running and accessible."+ }+ elif "Error type: api_error" in user_friendly_error:+ # Keep the original error message as it's already improved+ error_context = {"solution": "Check API configuration and credentials."}++ # Update metadata with more context about the error+ metadata = {"phase": "error", "error": user_friendly_error}+ if error_context:+ metadata.update(error_context)++ progress_callback(user_friendly_error, None, metadata)++ 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 user_friendly_error+ )++ # 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(metadata),+ 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 - moved to a separate function for reuse+ cleanup_research_resources(research_id)+++@research_bp.route("/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()+ termination_message = "Research termination requested by user"+ current_progress = active_research[research_id]["progress"]++ # Create log entry+ log_entry = {+ "time": timestamp,+ "message": termination_message,+ "progress": current_progress,+ "metadata": {"phase": "termination"},+ }++ # Add to in-memory log+ active_research[research_id]["log"].append(log_entry)++ # Add to database log+ add_log_to_db(+ research_id,+ termination_message,+ log_type="milestone",+ progress=current_progress,+ metadata={"phase": "termination"},+ )++ # Update the log in the database (old way for backward compatibility)+ cursor.execute(+ "SELECT progress_log FROM research_history WHERE id = ?", (research_id,)+ )+ log_result = cursor.fetchone()+ if log_result:+ try:+ current_log = json.loads(log_result[0])+ except Exception:+ current_log = []+ current_log.append(log_entry)+ cursor.execute(+ "UPDATE research_history SET progress_log = ? WHERE id = ?",+ (json.dumps(current_log), research_id),+ )++ # IMMEDIATELY update the status to 'suspended' to avoid race conditions+ cursor.execute(+ "UPDATE research_history SET status = ? WHERE id = ?",+ ("suspended", research_id),+ )+ conn.commit()+ conn.close()++ # Emit a socket event for the termination request+ try:+ event_data = {+ "status": "suspended", # Changed from 'terminating' to 'suspended'+ "message": "Research was suspended by user request",+ }++ 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"})+++@research_bp.route("/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"})+++@research_bp.route("/settings", methods=["GET"])+def settings_page():+ """Main settings dashboard with links to specialized config pages"""+ return render_template("settings_dashboard.html")+++@research_bp.route("/settings/main", methods=["GET"])+def main_config_page():+ """Edit main configuration with search parameters"""+ return render_template("main_config.html", main_file_path=MAIN_CONFIG_FILE)++@research_bp.route("/settings/collections", methods=["GET"])+def collections_config_page():+ """Edit local collections configuration using raw file editor"""+ return render_template(+ "collections_config.html", collections_file_path=LOCAL_COLLECTIONS_FILE+ )+++@research_bp.route("/settings/api_keys", methods=["GET"])+def api_keys_config_page():+ """Edit API keys configuration"""+ # Get the secrets file path+ secrets_file = CONFIG_DIR / ".secrets.toml"++ return render_template("api_keys_config.html", secrets_file_path=secrets_file)+++# Add a new route for search engines configuration page+@research_bp.route("/settings/search_engines", methods=["GET"])+def search_engines_config_page():+ """Edit search engines configuration using raw file editor"""+ # Read the current config file+ raw_config = ""+ try:+ with open(SEARCH_ENGINES_FILE, "r") as f:+ raw_config = f.read()+ except Exception as e:+ flash(f"Error reading search engines configuration: {str(e)}", "error")+ raw_config = "# Error reading configuration file"++ # Get list of engine names for display+ engine_names = []+ try:+ from ..web_search_engines.search_engines_config import SEARCH_ENGINES++ engine_names = list(SEARCH_ENGINES.keys())+ engine_names.sort() # Alphabetical order+ except Exception as e:+ logger.error(f"Error getting engine names: {e}")++ return render_template(+ "search_engines_config.html",+ search_engines_file_path=SEARCH_ENGINES_FILE,+ raw_config=raw_config,+ engine_names=engine_names,+ )+++# Add a route to save search engines configuration+@research_bp.route("/api/save_search_engines_config", methods=["POST"])+def save_search_engines_config():+ try:+ data = request.get_json()+ raw_config = data.get("raw_config", "")++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})++ # Ensure directory exists+ os.makedirs(os.path.dirname(SEARCH_ENGINES_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{SEARCH_ENGINES_FILE}.bak"+ if os.path.exists(SEARCH_ENGINES_FILE):+ import shutil++ shutil.copy2(SEARCH_ENGINES_FILE, backup_path)++ # Write new config+ with open(SEARCH_ENGINES_FILE, "w") as f:+ f.write(raw_config)++ return jsonify({"success": True})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)})+++# API endpoint to save raw collections config+@research_bp.route("/api/save_collections_config", methods=["POST"])+def save_collections_config():+ try:+ data = request.get_json()+ raw_config = data.get("raw_config", "")++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})++ # Ensure directory exists+ os.makedirs(os.path.dirname(LOCAL_COLLECTIONS_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{LOCAL_COLLECTIONS_FILE}.bak"+ if os.path.exists(LOCAL_COLLECTIONS_FILE):+ import shutil++ shutil.copy2(LOCAL_COLLECTIONS_FILE, backup_path)++ # Write new config+ with open(LOCAL_COLLECTIONS_FILE, "w") as f:+ f.write(raw_config)++ # Also trigger a reload in the collections system+ try:+ # TODO (djpetti) Fix collection reloading.+ load_local_collections(reload=True) # noqa: F821+ except Exception as reload_error:+ return jsonify(+ {+ "success": True,+ "warning": f"Config saved, but error reloading: {str(reload_error)}",+ }+ )++ return jsonify({"success": True})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)})+++# API endpoint to save raw main config+@research_bp.route("/api/save_main_config", methods=["POST"])+def save_raw_main_config():+ try:+ data = request.get_json()+ raw_config = data.get("raw_config", "")++ # Validate TOML syntax+ try:+ toml.loads(raw_config)+ except toml.TomlDecodeError as e:+ return jsonify({"success": False, "error": f"TOML syntax error: {str(e)}"})++ # Ensure directory exists+ os.makedirs(os.path.dirname(MAIN_CONFIG_FILE), exist_ok=True)++ # Create a backup first+ backup_path = f"{MAIN_CONFIG_FILE}.bak"+ if os.path.exists(MAIN_CONFIG_FILE):+ import shutil++ shutil.copy2(MAIN_CONFIG_FILE, backup_path)++ # Write new config+ with open(MAIN_CONFIG_FILE, "w") as f:+ f.write(raw_config)++ return jsonify({"success": True})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)})+++@research_bp.route("/raw_config")+def get_raw_config():+ """Return the raw configuration file content"""+ try:+ # Determine which config file to load based on a query parameter+ config_type = request.args.get("type", "main")++ if config_type == "main":+ config_path = os.path.join(app.config["CONFIG_DIR"], "config.toml")+ with open(config_path, "r") as f:+ return f.read()+ elif config_type == "llm":+ config_path = os.path.join(app.config["CONFIG_DIR"], "llm_config.py")+ with open(config_path, "r") as f:+ return f.read()+ elif config_type == "collections":+ config_path = os.path.join(app.config["CONFIG_DIR"], "collections.toml")+ with open(config_path, "r") as f:+ return f.read()+ else:+ return "Unknown configuration type", 400+ except Exception as e:+ return str(e), 500+++@research_bp.route("/open_file_location", methods=["POST"])+def open_file_location():+ file_path = request.form.get("file_path")++ if not file_path:+ flash("No file path provided", "error")+ return redirect(url_for("research.settings_page"))++ # Get the directory containing the file+ dir_path = os.path.dirname(os.path.abspath(file_path))++ # Open the directory in the file explorer+ try:+ if platform.system() == "Windows":+ subprocess.Popen(f'explorer "{dir_path}"')+ elif platform.system() == "Darwin": # macOS+ subprocess.Popen(["open", dir_path])+ else: # Linux+ subprocess.Popen(["xdg-open", dir_path])++ flash(f"Opening folder: {dir_path}", "success")+ except Exception as e:+ flash(f"Error opening folder: {str(e)}", "error")++ # Redirect back to the settings page+ if "llm" in file_path:+ return redirect(url_for("research.llm_config_page"))+ elif "collections" in file_path:+ return redirect(url_for("research.collections_config_page"))+ else:+ return redirect(url_for("research.main_config_page"))+++@research_bp.route("/api/research/<int:research_id>/logs")+def get_research_logs(research_id):+ """Get logs for a specific research ID"""+ # First check if the research exists+ conn = sqlite3.connect(DB_PATH)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))+ result = cursor.fetchone()+ conn.close()++ if not result:+ return jsonify({"status": "error", "message": "Research not found"}), 404++ # Retrieve logs from the database+ logs = get_logs_for_research(research_id)++ # Add any current logs from memory if this is an active research+ if research_id in active_research and active_research[research_id].get("log"):+ # Use the logs from memory temporarily until they're saved to the database+ memory_logs = active_research[research_id]["log"]++ # Filter out logs that are already in the database+ # We'll compare timestamps to avoid duplicates+ db_timestamps = {log["time"] for log in logs}+ unique_memory_logs = [+ log for log in memory_logs if log["time"] not in db_timestamps+ ]++ # Add unique memory logs to our return list+ logs.extend(unique_memory_logs)++ # Sort logs by timestamp+ logs.sort(key=lambda x: x["time"])++ return jsonify({"status": "success", "logs": logs})+++# Register the blueprint+app.register_blueprint(research_bp)+++# Also add the static route at the app level for compatibility[email protected]("/static/<path:path>")+def app_serve_static(path):+ return send_from_directory(app.static_folder, path)+++# Add favicon route to prevent 404 errors[email protected]("/favicon.ico")+def favicon():+ return send_from_directory(+ app.static_folder, "favicon.ico", mimetype="image/x-icon"+ )+++# Add this function to app.py+def convert_debug_to_markdown(raw_text, query):+ """+ Convert the debug-formatted text to clean markdown.++ Args:+ raw_text: The raw formatted findings with debug symbols+ query: Original research query++ Returns:+ Clean markdown formatted text+ """+ try:+ print(f"Starting markdown conversion for query: {query}")+ print(f"Raw text type: {type(raw_text)}")++ # Handle None or empty input+ if not raw_text:+ print("WARNING: raw_text is empty or None")+ return f"No detailed findings available for '{query}'."++ # If there's a "DETAILED FINDINGS:" section, extract everything after it+ if "DETAILED FINDINGS:" in raw_text:+ print("Found DETAILED FINDINGS section")+ detailed_index = raw_text.index("DETAILED FINDINGS:")+ content = raw_text[detailed_index + len("DETAILED FINDINGS:") :].strip()+ else:+ print("No DETAILED FINDINGS section found, using full text")+ content = raw_text++ # Remove divider lines with === symbols+ lines_before = len(content.split("\n"))+ content = "\n".join(+ [+ line+ for line in content.split("\n")+ if not line.strip().startswith("===") and not line.strip() == "=" * 80+ ]+ )+ lines_after = len(content.split("\n"))+ print(f"Removed {lines_before - lines_after} divider lines")++ # Remove SEARCH QUESTIONS BY ITERATION section+ if "SEARCH QUESTIONS BY ITERATION:" in content:+ print("Found SEARCH QUESTIONS BY ITERATION section")+ search_index = content.index("SEARCH QUESTIONS BY ITERATION:")+ next_major_section = -1+ for marker in ["DETAILED FINDINGS:", "COMPLETE RESEARCH:"]:+ if marker in content[search_index:]:+ marker_pos = content.index(marker, search_index)+ if next_major_section == -1 or marker_pos < next_major_section:+ next_major_section = marker_pos++ if next_major_section != -1:+ print(+ f"Removing section from index {search_index} to {next_major_section}"+ )+ content = content[:search_index] + content[next_major_section:]+ else:+ # If no later section, just remove everything from SEARCH QUESTIONS onwards+ print(f"Removing everything after index {search_index}")+ content = content[:search_index].strip()++ print(f"Final markdown length: {len(content.strip())}")+ return content.strip()+ except Exception as e:+ print(f"Error in convert_debug_to_markdown: {str(e)}")+ print(traceback.format_exc())+ # Return a basic message with the original query as fallback+ return f"# Research on {query}\n\nThere was an error formatting the research results."+++def main():+ """+ Entry point for the web application when run as a command.+ This function is needed for the package's entry point to work properly.+ """+ # Import settings here to avoid circular imports+ from ..config import settings++ # Get web server settings with defaults+ port = settings.web.port+ host = settings.web.host+ debug = settings.web.debug++ # Check for OpenAI availability but don't import it unless necessary+ try:+ import os++ api_key = os.environ.get("OPENAI_API_KEY")+ if api_key:+ try:+ # Only try to import if we have an API key+ import openai++ openai.api_key = api_key+ print("OpenAI integration is available")+ except ImportError:+ print("OpenAI package not installed, integration disabled")+ else:+ print(+ "OPENAI_API_KEY not found in environment variables, OpenAI integration disabled"+ )+ except Exception as e:+ print(f"Error checking OpenAI availability: {e}")++ socketio.run(app, debug=debug, host=host, port=port, allow_unsafe_werkzeug=True)+++if __name__ == "__main__":+ main()diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pynew file mode 100644index 0000000000..9263b8f35f--- /dev/null+++ b/src/local_deep_research/web/app_factory.py@@ -0,0 +1,282 @@+from importlib import resources as importlib_resources+import logging+import os+import platform+import traceback++from flask import Blueprint, Flask, jsonify, make_response, send_from_directory, request, redirect, url_for+from flask_socketio import SocketIO++# Initialize logger+logger = logging.getLogger(__name__)++def create_app():+ """+ Create and configure the Flask application.++ Returns:+ tuple: (app, socketio) - The configured Flask app and SocketIO instance+ """+ # Configure logging+ logging.basicConfig(level=logging.INFO)++ try:+ # Get directories based on package installation+ PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"+ with importlib_resources.as_file(PACKAGE_DIR) as package_dir:+ STATIC_DIR = (package_dir / "static").as_posix()+ TEMPLATE_DIR = (package_dir / "templates").as_posix()++ # Initialize Flask app with package directories+ app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)+ print(f"Using package static path: {STATIC_DIR}")+ print(f"Using package template path: {TEMPLATE_DIR}")+ except Exception as e:+ # Fallback for development+ print(f"Package directories not found, using fallback paths: {str(e)}")+ app = Flask(+ __name__,+ static_folder=os.path.abspath("static"),+ template_folder=os.path.abspath("templates"),+ )++ # App configuration+ app.config["SECRET_KEY"] = "deep-research-secret-key"++ # Initialize extensions+ socketio = SocketIO(+ app,+ cors_allowed_origins="*",+ async_mode="threading",+ path="/research/socket.io",+ logger=True,+ engineio_logger=True,+ ping_timeout=20,+ ping_interval=5,+ )++ # Initialize database+ from .models.database import init_db+ init_db()++ # Register socket service+ from .services.socket_service import set_socketio+ set_socketio(socketio)++ # Register socket event handlers+ register_socket_events(socketio)++ # Apply middleware+ apply_middleware(app)++ # Register blueprints+ register_blueprints(app)++ # Register error handlers+ register_error_handlers(app)++ return app, socketio++def apply_middleware(app):+ """Apply middleware to the Flask app."""++ # Add Content Security Policy headers to allow Socket.IO to function+ @app.after_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++ # Add a middleware layer to handle abrupt disconnections+ @app.before_request+ def handle_websocket_requests():+ if request.path.startswith("/research/socket.io"):+ try:+ if not request.environ.get("werkzeug.socket"):+ return+ except Exception as e:+ print(f"WebSocket preprocessing error: {e}")+ # Return empty response to prevent further processing+ return "", 200++def register_blueprints(app):+ """Register blueprints with the Flask app."""++ # Import blueprints+ from .routes.research_routes import research_bp+ from .routes.history_routes import history_bp++ # Register blueprints+ app.register_blueprint(research_bp)+ app.register_blueprint(history_bp)++ # Add root route redirect+ @app.route("/")+ def root_index():+ return redirect(url_for("research.index"))++ # Add favicon route+ @app.route("/favicon.ico")+ def favicon():+ return send_from_directory(+ app.static_folder, "favicon.ico", mimetype="image/x-icon"+ )++ # Add static route at the app level for compatibility+ @app.route("/static/<path:path>")+ def app_serve_static(path):+ return send_from_directory(app.static_folder, path)++def register_error_handlers(app):+ """Register error handlers with the Flask app."""++ @app.errorhandler(404)+ def not_found(error):+ return make_response(jsonify({"error": "Not found"}), 404)++ @app.errorhandler(500)+ def server_error(error):+ return make_response(jsonify({"error": "Server error"}), 500)++def register_socket_events(socketio):+ """Register Socket.IO event handlers."""++ @socketio.on("connect")+ def handle_connect():+ print(f"Client connected: {request.sid}")++ @socketio.on("disconnect")+ def handle_disconnect():+ try:+ print(f"Client disconnected: {request.sid}")+ # Import to avoid circular imports+ from .routes.research_routes import get_globals+ globals_dict = get_globals()+ socket_subscriptions = globals_dict['socket_subscriptions']++ # 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)+ print(f"Removed empty subscription for research {research_id}")+ except Exception as e:+ print(f"Error handling disconnect: {e}")++ @socketio.on("subscribe_to_research")+ def handle_subscribe(data):+ from .routes.research_routes import get_globals+ globals_dict = get_globals()+ active_research = globals_dict['active_research']+ socket_subscriptions = globals_dict['socket_subscriptions']++ research_id = data.get("research_id")+ if research_id:+ # First check if this research is still active+ from .models.database import get_db_connection+ conn = get_db_connection()+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ conn.close()++ # Only allow subscription to valid research+ if result:+ status = result[0]++ # Initialize subscription set if needed+ if research_id not in socket_subscriptions:+ socket_subscriptions[research_id] = set()++ # Add this client to the subscribers+ 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:+ socketio.emit(+ f"research_progress_{research_id}",+ {+ "progress": progress,+ "message": latest_log.get("message", "Processing..."),+ "status": "in_progress",+ "log_entry": latest_log,+ },+ room=request.sid+ )+ elif status in ["completed", "failed", "suspended"]:+ # Send final status for completed research+ socketio.emit(+ f"research_progress_{research_id}",+ {+ "progress": 100 if status == "completed" else 0,+ "message": (+ "Research completed successfully"+ if status == "completed"+ else (+ "Research failed"+ if status == "failed"+ else "Research was suspended"+ )+ ),+ "status": status,+ "log_entry": {+ "time": datetime.utcnow().isoformat(),+ "message": f"Research is {status}",+ "progress": 100 if status == "completed" else 0,+ "metadata": {+ "phase": (+ "complete" if status == "completed" else "error"+ )+ },+ },+ },+ room=request.sid+ )+ else:+ # Research not found+ socketio.emit("error", {"message": f"Research ID {research_id} not found"}, room=request.sid)++ @socketio.on_error+ def handle_socket_error(e):+ print(f"Socket.IO error: {str(e)}")+ print(traceback.format_exc())+ # Don't propagate exceptions to avoid crashing the server+ return False++ @socketio.on_error_default+ def handle_default_error(e):+ print(f"Unhandled Socket.IO error: {str(e)}")+ print(traceback.format_exc())+ # Don't propagate exceptions to avoid crashing the server+ return False\ No newline at end of filediff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.pynew file mode 100644index 0000000000..f0291ee827--- /dev/null+++ b/src/local_deep_research/web/models/database.py@@ -0,0 +1,204 @@+import json+import logging+import sqlite3+import traceback+from datetime import datetime+import os++# Initialize logger+logger = logging.getLogger(__name__)++# Database path+DB_PATH = "research_history.db"++def get_db_connection():+ """+ Get a connection to the SQLite database.+ Allows for custom row factory if needed.+ """+ conn = sqlite3.connect(DB_PATH)+ return conn++def init_db():+ """Initialize the database with necessary tables."""+ conn = get_db_connection()+ 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,+ progress INTEGER+ )+ """+ )++ # Create a dedicated table for research logs+ cursor.execute(+ """+ CREATE TABLE IF NOT EXISTS research_logs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ research_id INTEGER NOT NULL,+ timestamp TEXT NOT NULL,+ message TEXT NOT NULL,+ log_type TEXT NOT NULL,+ progress INTEGER,+ metadata TEXT,+ FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE+ )+ """+ )++ # 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"+ )++ # Check if the progress column exists, add it if missing+ if "progress" not in columns:+ print("Adding missing 'progress' column to research_history table")+ cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")++ # Enable foreign key support+ cursor.execute("PRAGMA foreign_keys = ON")++ conn.commit()+ conn.close()++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:+ from dateutil import parser+ start_time_fallback = parser.parse(created_at_str)+ duration_seconds = int((now - start_time_fallback).total_seconds())+ except Exception:+ print(+ f"Fallback duration calculation also failed for timestamp: {created_at_str}"+ )++ return duration_seconds++def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):+ """+ Store a log entry in the database++ Args:+ research_id: ID of the research+ message: Log message text+ log_type: Type of log (info, error, milestone)+ progress: Progress percentage (0-100)+ metadata: Additional metadata as dictionary (will be stored as JSON)+ """+ try:+ timestamp = datetime.utcnow().isoformat()+ metadata_json = json.dumps(metadata) if metadata else None++ conn = get_db_connection()+ cursor = conn.cursor()+ cursor.execute(+ "INSERT INTO research_logs (research_id, timestamp, message, log_type, progress, metadata) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (research_id, timestamp, message, log_type, progress, metadata_json),+ )+ conn.commit()+ conn.close()+ return True+ except Exception as e:+ print(f"Error adding log to database: {str(e)}")+ print(traceback.format_exc())+ return False++def get_logs_for_research(research_id):+ """+ Retrieve all logs for a specific research ID++ Args:+ research_id: ID of the research++ Returns:+ List of log entries as dictionaries+ """+ try:+ conn = get_db_connection()+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()+ cursor.execute(+ "SELECT * FROM research_logs WHERE research_id = ? ORDER BY timestamp ASC",+ (research_id,),+ )+ results = cursor.fetchall()+ conn.close()++ logs = []+ for result in results:+ log_entry = dict(result)+ # Parse metadata JSON if it exists+ if log_entry.get("metadata"):+ try:+ log_entry["metadata"] = json.loads(log_entry["metadata"])+ except Exception:+ log_entry["metadata"] = {}+ else:+ log_entry["metadata"] = {}++ # Convert entry for frontend consumption+ formatted_entry = {+ "time": log_entry["timestamp"],+ "message": log_entry["message"],+ "progress": log_entry["progress"],+ "metadata": log_entry["metadata"],+ "type": log_entry["log_type"],+ }+ logs.append(formatted_entry)++ return logs+ except Exception as e:+ print(f"Error retrieving logs from database: {str(e)}")+ print(traceback.format_exc())+ return []\ No newline at end of filediff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pynew file mode 100644index 0000000000..f09e289eae--- /dev/null+++ b/src/local_deep_research/web/routes/history_routes.py@@ -0,0 +1,279 @@+import json+import logging+import traceback+from flask import Blueprint, jsonify, make_response, request++from ..models.database import get_db_connection, get_logs_for_research++# Initialize logger+logger = logging.getLogger(__name__)++# Create a Blueprint for the history routes+history_bp = Blueprint("history", __name__, url_prefix="/api")++@history_bp.route("/history", methods=["GET"])+def get_history():+ """Get the research history"""+ try:+ conn = get_db_connection()+ conn.row_factory = lambda cursor, row: {+ column[0]: row[idx] for idx, column in enumerate(cursor.description)+ }+ 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+ from dateutil import parser+ dt = parser.parse(item["created_at"])+ item["created_at"] = dt.isoformat()+ except Exception:+ pass++ if item["completed_at"] and "T" not in item["completed_at"]:+ try:+ # Convert to ISO format if it's not already+ from dateutil import parser+ dt = parser.parse(item["completed_at"])+ item["completed_at"] = dt.isoformat()+ except Exception:+ 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:+ from dateutil import parser+ 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++@history_bp.route("/research/<int:research_id>")+def get_research_status(research_id):+ conn = get_db_connection()+ conn.row_factory = lambda cursor, row: {+ column[0]: row[idx] for idx, column in enumerate(cursor.description)+ }+ cursor = conn.cursor()+ cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))+ result = cursor.fetchone()+ conn.close()++ if not result:+ return jsonify({"status": "error", "message": "Research not found"}), 404++ # Import globals from research routes+ from .research_routes import get_globals+ globals_dict = get_globals()+ active_research = globals_dict['active_research']++ # 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 Exception:+ result["log"] = []+ else:+ result["progress"] = 0+ try:+ result["log"] = json.loads(result.get("progress_log", "[]"))+ except Exception:+ result["log"] = []++ return jsonify(result)++@history_bp.route("/research/<int:research_id>/details")+def get_research_details(research_id):+ """Get detailed progress log for a specific research"""+ conn = get_db_connection()+ conn.row_factory = lambda cursor, row: {+ column[0]: row[idx] for idx, column in enumerate(cursor.description)+ }+ cursor = conn.cursor()+ cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))+ result = cursor.fetchone()+ conn.close()++ if not result:+ return jsonify({"status": "error", "message": "Research not found"}), 404++ # Get logs from the dedicated log database+ logs = get_logs_for_research(research_id)++ # Import globals from research routes+ from .research_routes import get_globals+ globals_dict = get_globals()+ active_research = globals_dict['active_research']++ # If this is an active research, merge with any in-memory logs+ if research_id in active_research:+ # Use the logs from memory temporarily until they're saved to the database+ memory_logs = active_research[research_id]["log"]++ # Filter out logs that are already in the database by timestamp+ db_timestamps = {log["time"] for log in logs}+ unique_memory_logs = [+ log for log in memory_logs if log["time"] not in db_timestamps+ ]++ # Add unique memory logs to our return list+ logs.extend(unique_memory_logs)++ # Sort logs by timestamp+ logs.sort(key=lambda x: x["time"])++ return jsonify(+ {+ "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": logs,+ }+ )++@history_bp.route("/report/<int:research_id>")+def get_report(research_id):+ conn = get_db_connection()+ conn.row_factory = lambda cursor, row: {+ column[0]: row[idx] for idx, column in enumerate(cursor.description)+ }+ cursor = conn.cursor()+ cursor.execute("SELECT * FROM research_history WHERE id = ?", (research_id,))+ result = cursor.fetchone()+ 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++@history_bp.route("/research/<int:research_id>/logs")+def get_research_logs(research_id):+ """Get logs for a specific research ID"""+ # First check if the research exists+ conn = get_db_connection()+ conn.row_factory = lambda cursor, row: {+ column[0]: row[idx] for idx, column in enumerate(cursor.description)+ }+ cursor = conn.cursor()+ cursor.execute("SELECT id FROM research_history WHERE id = ?", (research_id,))+ result = cursor.fetchone()+ conn.close()++ if not result:+ return jsonify({"status": "error", "message": "Research not found"}), 404++ # Retrieve logs from the database+ logs = get_logs_for_research(research_id)++ # Import globals from research routes+ from .research_routes import get_globals+ globals_dict = get_globals()+ active_research = globals_dict['active_research']++ # Add any current logs from memory if this is an active research+ if research_id in active_research and active_research[research_id].get("log"):+ # Use the logs from memory temporarily until they're saved to the database+ memory_logs = active_research[research_id]["log"]++ # Filter out logs that are already in the database+ # We'll compare timestamps to avoid duplicates+ db_timestamps = {log["time"] for log in logs}+ unique_memory_logs = [+ log for log in memory_logs if log["time"] not in db_timestamps+ ]++ # Add unique memory logs to our return list+ logs.extend(unique_memory_logs)++ # Sort logs by timestamp+ logs.sort(key=lambda x: x["time"])++ return jsonify({"status": "success", "logs": logs})\ No newline at end of filediff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pynew file mode 100644index 0000000000..3f57fc5e72--- /dev/null+++ b/src/local_deep_research/web/routes/research_routes.py@@ -0,0 +1,290 @@+import logging+import traceback+from datetime import datetime+import json+import os++from flask import Blueprint, render_template, request, jsonify, make_response, redirect, url_for+from flask_socketio import emit++from ..models.database import init_db, add_log_to_db, get_logs_for_research, calculate_duration+from ..services.research_service import start_research_process, run_research_process, cleanup_research_resources++# Initialize logger+logger = logging.getLogger(__name__)++# Create a Blueprint for the research application+research_bp = Blueprint("research", __name__, url_prefix="/research")++# Active research processes and socket subscriptions+active_research = {}+socket_subscriptions = {}++# Add termination flags dictionary+termination_flags = {}++# Output directory for research results+OUTPUT_DIR = "research_outputs"++# Return reference to globals for other modules to access+def get_globals():+ return {+ 'active_research': active_research,+ 'socket_subscriptions': socket_subscriptions,+ 'termination_flags': termination_flags+ }++# Route for index page - redirection+@research_bp.route("/")+def index():+ return render_template("pages/research.html")++@research_bp.route("/progress/<int:research_id>")+def progress_page(research_id):+ """Render the research progress page"""+ return render_template("pages/progress.html")++@research_bp.route("/details/<int:research_id>")+def research_details_page(research_id):+ """Render the research details page"""+ return render_template("pages/details.html")++@research_bp.route("/results/<int:research_id>")+def results_page(research_id):+ """Render the research results page"""+ return render_template("pages/results.html")++@research_bp.route("/history")+def history_page():+ """Render the history page"""+ return render_template("pages/history.html")++@research_bp.route("/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 that's actually still running+ if active_research:+ # Verify each active research is still valid+ stale_research_ids = []+ for research_id, research_data in list(active_research.items()):+ # Check database status+ from ..models.database import get_db_connection+ conn = get_db_connection()+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ conn.close()++ # If the research doesn't exist in DB or is not in_progress, it's stale+ if not result or result[0] != "in_progress":+ stale_research_ids.append(research_id)+ # Also check if thread is still alive+ elif (+ not research_data.get("thread")+ or not research_data.get("thread").is_alive()+ ):+ stale_research_ids.append(research_id)++ # Clean up any stale research processes+ for stale_id in stale_research_ids:+ print(f"Cleaning up stale research process: {stale_id}")+ if stale_id in active_research:+ del active_research[stale_id]+ if stale_id in termination_flags:+ del termination_flags[stale_id]++ # After cleanup, check if there's still active research+ if active_research:+ return (+ jsonify(+ {+ "status": "error",+ "message": "Another research is already in progress. Please wait for it to complete.",+ }+ ),+ 409,+ )++ # Create a record in the database with explicit UTC timestamp+ created_at = datetime.utcnow().isoformat()+ from ..models.database import get_db_connection+ conn = get_db_connection()+ 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 the research process+ research_thread = start_research_process(research_id, query, mode,+ active_research, termination_flags, run_research_process)++ return jsonify({"status": "success", "research_id": research_id})++@research_bp.route("/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+ from ..models.database import get_db_connection+ conn = get_db_connection()+ 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()+ termination_message = "Research termination requested by user"+ current_progress = active_research[research_id]["progress"]++ # Create log entry+ log_entry = {+ "time": timestamp,+ "message": termination_message,+ "progress": current_progress,+ "metadata": {"phase": "termination"},+ }++ # Add to in-memory log+ active_research[research_id]["log"].append(log_entry)++ # Add to database log+ add_log_to_db(+ research_id,+ termination_message,+ log_type="milestone",+ progress=current_progress,+ metadata={"phase": "termination"},+ )++ # Update the log in the database (old way for backward compatibility)+ cursor.execute(+ "SELECT progress_log FROM research_history WHERE id = ?", (research_id,)+ )+ log_result = cursor.fetchone()+ if log_result:+ try:+ current_log = json.loads(log_result[0])+ except Exception:+ current_log = []+ current_log.append(log_entry)+ cursor.execute(+ "UPDATE research_history SET progress_log = ? WHERE id = ?",+ (json.dumps(current_log), research_id),+ )++ # IMMEDIATELY update the status to 'suspended' to avoid race conditions+ cursor.execute(+ "UPDATE research_history SET status = ? WHERE id = ?",+ ("suspended", research_id),+ )+ conn.commit()+ conn.close()++ # Emit a socket event for the termination request+ try:+ event_data = {+ "status": "suspended", # Changed from 'terminating' to 'suspended'+ "message": "Research was suspended by user request",+ }++ from ..services.socket_service import emit_socket_event+ emit_socket_event(f"research_progress_{research_id}", event_data)++ except Exception as socket_error:+ print(f"Socket emit error (non-critical): {str(socket_error)}")++ return jsonify({"status": "success", "message": "Research termination requested"})++@research_bp.route("/api/research/<int:research_id>/delete", methods=["DELETE"])+def delete_research(research_id):+ """Delete a research record"""+ from ..models.database import get_db_connection+ conn = get_db_connection()+ 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"})\ No newline at end of filediff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pynew file mode 100644index 0000000000..fd65dec8a3--- /dev/null+++ b/src/local_deep_research/web/services/research_service.py@@ -0,0 +1,601 @@+import json+import logging+import os+import threading+import traceback+from datetime import datetime++from flask_socketio import emit++from ..models.database import get_db_connection, add_log_to_db, calculate_duration++# Initialize logger+logger = logging.getLogger(__name__)++# Output directory for research results+OUTPUT_DIR = "research_outputs"++def start_research_process(research_id, query, mode, active_research, termination_flags, run_research_callback):+ """+ Start a research process in a background thread.++ Args:+ research_id: The ID of the research+ query: The research query+ mode: The research mode (quick/detailed)+ active_research: Dictionary of active research processes+ termination_flags: Dictionary of termination flags+ run_research_callback: The callback function to run the research++ Returns:+ threading.Thread: The thread running the research+ """+ # Start research process in a background thread+ thread = threading.Thread(+ target=run_research_callback,+ args=(research_id, query, mode, active_research, termination_flags)+ )+ thread.daemon = True+ thread.start()++ active_research[research_id] = {+ "thread": thread,+ "progress": 0,+ "status": "in_progress",+ "log": [{"time": datetime.utcnow().isoformat(), "message": "Research started", "progress": 0}],+ }++ return thread++def run_research_process(research_id, query, mode, active_research, termination_flags):+ """+ Run the research process in the background for a given research ID.++ Args:+ research_id: The ID of the research+ query: The research query+ mode: The research mode (quick/detailed)+ active_research: Dictionary of active research processes+ termination_flags: Dictionary of termination flags+ """+ try:+ # Check if this research has been terminated before we even start+ if research_id in termination_flags and termination_flags[research_id]:+ logger.info(f"Research {research_id} was terminated before starting")+ cleanup_research_resources(research_id, active_research, termination_flags)+ return++ logger.info(f"Starting research process for ID {research_id}, query: {query}")++ # Set up the AI Context Manager+ output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")+ os.makedirs(output_dir, exist_ok=True)++ # Set up progress callback+ def progress_callback(message, progress_percent, metadata):+ # Frequent termination check+ if research_id in termination_flags and termination_flags[research_id]:+ handle_termination(research_id, active_research, termination_flags)+ raise Exception("Research was terminated by user")++ timestamp = datetime.utcnow().isoformat()++ # Adjust progress based on research mode+ adjusted_progress = progress_percent+ if mode == "detailed" and metadata.get("phase") == "output_generation":+ # For detailed mode, adjust the progress range for output generation+ adjusted_progress = min(80, progress_percent)+ elif mode == "detailed" and metadata.get("phase") == "report_generation":+ # Scale the progress from 80% to 95% for the report generation phase+ if progress_percent is not None:+ normalized = progress_percent / 100+ adjusted_progress = 80 + (normalized * 15)+ elif mode == "quick" and metadata.get("phase") == "output_generation":+ # For quick mode, ensure we're at least at 85% during output generation+ adjusted_progress = max(85, progress_percent)+ # Map any further progress within output_generation to 85-95% range+ if progress_percent is not None and progress_percent > 0:+ normalized = progress_percent / 100+ adjusted_progress = 85 + (normalized * 10)++ # Don't let progress go backwards+ if research_id in active_research and adjusted_progress is not None:+ current_progress = active_research[research_id].get("progress", 0)+ adjusted_progress = max(current_progress, adjusted_progress)++ log_entry = {+ "time": timestamp,+ "message": message,+ "progress": adjusted_progress,+ "metadata": metadata,+ }++ # Update active research record+ if research_id in active_research:+ active_research[research_id]["log"].append(log_entry)+ if adjusted_progress is not None:+ active_research[research_id]["progress"] = adjusted_progress++ # Determine log type for database storage+ log_type = "info"+ if metadata and metadata.get("phase"):+ phase = metadata.get("phase")+ if phase in ["complete", "iteration_complete"]:+ log_type = "milestone"+ elif phase == "error" or "error" in message.lower():+ log_type = "error"++ # Save logs to the database+ add_log_to_db(+ research_id,+ message,+ log_type=log_type,+ progress=adjusted_progress,+ metadata=metadata,+ )++ # Update progress in the research_history table (for backward compatibility)+ conn = get_db_connection()+ cursor = conn.cursor()++ # Update the progress and log separately to avoid race conditions+ if adjusted_progress is not None:+ cursor.execute(+ "UPDATE research_history SET progress = ? WHERE id = ?",+ (adjusted_progress, research_id),+ )++ # Add the log entry to the progress_log+ cursor.execute(+ "SELECT progress_log FROM research_history WHERE id = ?",+ (research_id,),+ )+ log_result = cursor.fetchone()++ if log_result:+ try:+ current_log = json.loads(log_result[0])+ except Exception:+ current_log = []++ current_log.append(log_entry)+ cursor.execute(+ "UPDATE research_history SET progress_log = ? WHERE id = ?",+ (json.dumps(current_log), research_id),+ )++ conn.commit()+ conn.close()++ # Emit a socket event+ try:+ # Basic event data+ event_data = {"message": message, "progress": adjusted_progress}++ # Add log entry in full format for detailed logging on client+ if metadata:+ event_data["log_entry"] = log_entry++ from ..services.socket_service import emit_to_subscribers+ emit_to_subscribers("research_progress", research_id, event_data)+ except Exception as e:+ logger.error(f"Socket emit error (non-critical): {str(e)}")++ # Function to check termination during long-running operations+ def check_termination():+ if research_id in termination_flags and termination_flags[research_id]:+ handle_termination(research_id, active_research, termination_flags)+ raise Exception("Research was terminated by user during long-running operation")+ return False # Not terminated++ # Set the progress callback in the system+ from ...search_system import AdvancedSearchSystem+ system = AdvancedSearchSystem()+ system.set_progress_callback(progress_callback)++ # Run the search+ progress_callback("Starting research process", 5, {"phase": "init"})++ try:+ results = system.analyze_topic(query)+ if mode == "quick":+ progress_callback(+ "Search complete, preparing to generate summary...",+ 85,+ {"phase": "output_generation"},+ )+ else:+ progress_callback(+ "Search complete, generating output",+ 80,+ {"phase": "output_generation"},+ )+ except Exception as search_error:+ # Better handling of specific search errors+ error_message = str(search_error)+ error_type = "unknown"++ # Extract error details for common issues+ if "status code: 503" in error_message:+ error_message = "Ollama AI service is unavailable (HTTP 503). Please check that Ollama is running properly on your system."+ error_type = "ollama_unavailable"+ elif "status code: 404" in error_message:+ error_message = "Ollama model not found (HTTP 404). Please check that you have pulled the required model."+ error_type = "model_not_found"+ elif "status code:" in error_message:+ # Extract the status code for other HTTP errors+ status_code = error_message.split("status code:")[1].strip()+ error_message = f"API request failed with status code {status_code}. Please check your configuration."+ error_type = "api_error"+ elif "connection" in error_message.lower():+ error_message = "Connection error. Please check that your LLM service (Ollama/API) is running and accessible."+ error_type = "connection_error"++ # Raise with improved error message+ raise Exception(f"{error_message} (Error type: {error_type})")++ # Generate output based on mode+ if mode == "quick":+ # Quick Summary+ if results.get("findings") or results.get("formatted_findings"):+ raw_formatted_findings = results["formatted_findings"]+ logger.info(f"Found formatted_findings of length: {len(str(raw_formatted_findings))}")++ try:+ clean_markdown = raw_formatted_findings+ logger.info(f"Successfully converted to clean markdown of length: {len(clean_markdown)}")++ # First send a progress update for generating the summary+ progress_callback(+ "Generating clean summary from research data...",+ 90,+ {"phase": "output_generation"},+ )++ # Save as markdown file+ 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")++ # Send progress update for writing to file+ progress_callback(+ "Writing research report to file...",+ 95,+ {"phase": "report_complete"},+ )++ logger.info(f"Writing report to: {report_path}")+ 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(clean_markdown)+ 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()++ logger.info(f"Updating database for research_id: {research_id}")+ # Get the start time from the database+ conn = get_db_connection()+ 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()+ logger.info(f"Database updated successfully for research_id: {research_id}")++ # Send the final completion message+ progress_callback(+ "Research completed successfully",+ 100,+ {"phase": "complete", "report_path": report_path},+ )++ # Clean up resources+ logger.info(f"Cleaning up resources for research_id: {research_id}")+ cleanup_research_resources(research_id, active_research, termination_flags)+ logger.info(f"Resources cleaned up for research_id: {research_id}")++ except Exception as inner_e:+ logger.error(f"Error during quick summary generation: {str(inner_e)}")+ logger.error(traceback.format_exc())+ raise Exception(f"Error generating quick summary: {str(inner_e)}")+ else:+ raise Exception("No research findings were generated. Please try again.")+ else:+ # Full Report+ progress_callback(+ "Generating detailed report...", 85, {"phase": "report_generation"}+ )++ from ...report_generator import IntegratedReportGenerator+ report_generator = IntegratedReportGenerator()+ final_report = report_generator.generate_report(results, query)++ progress_callback(+ "Report generation complete", 95, {"phase": "report_complete"}+ )++ # Save as markdown file+ 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 = get_db_connection()+ 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 resources+ cleanup_research_resources(research_id, active_research, termination_flags)++ except Exception as e:+ # Handle error+ error_message = f"Research failed: {str(e)}"+ logger.error(error_message)+ try:+ # Check for common Ollama error patterns in the exception and provide more user-friendly errors+ user_friendly_error = str(e)+ error_context = {}++ if "Error type: ollama_unavailable" in user_friendly_error:+ user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."+ error_context = {+ "solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."+ }+ elif "Error type: model_not_found" in user_friendly_error:+ user_friendly_error = "Required Ollama model not found. Please pull the model first."+ error_context = {+ "solution": "Run 'ollama pull mistral' to download the required model."+ }+ elif "Error type: connection_error" in user_friendly_error:+ user_friendly_error = "Connection error with LLM service. Please check that your AI service is running."+ error_context = {+ "solution": "Ensure Ollama or your API service is running and accessible."+ }+ elif "Error type: api_error" in user_friendly_error:+ # Keep the original error message as it's already improved+ error_context = {"solution": "Check API configuration and credentials."}++ # Update metadata with more context about the error+ metadata = {"phase": "error", "error": user_friendly_error}+ if error_context:+ metadata.update(error_context)++ # If we still have an active research record, update its log+ if research_id in active_research:+ progress_callback(user_friendly_error, None, metadata)++ conn = get_db_connection()+ 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 user_friendly_error+ )++ # 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(metadata),+ research_id,+ ),+ )+ conn.commit()+ conn.close()++ try:+ from ..services.socket_service import emit_to_subscribers+ emit_to_subscribers("research_progress", research_id, {"status": status, "error": message})+ except Exception as socket_error:+ logger.error(f"Failed to emit error via socket: {str(socket_error)}")++ except Exception as inner_e:+ logger.error(f"Error in error handler: {str(inner_e)}")+ logger.error(traceback.format_exc())++ # Clean up resources+ cleanup_research_resources(research_id, active_research, termination_flags)++def cleanup_research_resources(research_id, active_research, termination_flags):+ """+ Clean up resources for a completed research.++ Args:+ research_id: The ID of the research+ active_research: Dictionary of active research processes+ termination_flags: Dictionary of termination flags+ """+ logger.info(f"Cleaning up resources for research {research_id}")++ # Get the current status from the database to determine the final status message+ current_status = "completed" # Default+ try:+ conn = get_db_connection()+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ if result and result[0]:+ current_status = result[0]+ conn.close()+ except Exception as e:+ logger.error(f"Error retrieving research status during cleanup: {e}")++ # Remove from active research+ if research_id in active_research:+ del active_research[research_id]++ # Remove from termination flags+ if research_id in termination_flags:+ del termination_flags[research_id]++ # Send a final message to subscribers+ try:+ # Import here to avoid circular imports+ from ..routes.research_routes import get_globals+ globals_dict = get_globals()+ socket_subscriptions = globals_dict.get('socket_subscriptions', {})++ # Send a final message to any remaining subscribers with explicit status+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ # Use the proper status message based on database status+ if current_status == "suspended" or current_status == "failed":+ final_message = {+ "status": current_status,+ "message": f"Research was {current_status}",+ "progress": 0, # For suspended research, show 0% not 100%+ }+ else:+ final_message = {+ "status": "completed",+ "message": "Research process has ended and resources have been cleaned up",+ "progress": 100,+ }++ logger.info(f"Sending final {current_status} socket message for research {research_id}")++ from ..services.socket_service import emit_to_subscribers+ emit_to_subscribers("research_progress", research_id, final_message)++ except Exception as e:+ logger.error(f"Error sending final cleanup message: {e}")++def handle_termination(research_id, active_research, termination_flags):+ """+ Handle the termination of a research process.++ Args:+ research_id: The ID of the research+ active_research: Dictionary of active research processes+ termination_flags: Dictionary of termination flags+ """+ # Explicitly set the status to suspended in the database+ conn = get_db_connection()+ cursor = conn.cursor()++ # Calculate duration up to termination point - using UTC consistently+ now = datetime.utcnow()+ completed_at = now.isoformat()++ # Get the start time from the database+ cursor.execute(+ "SELECT created_at FROM research_history WHERE id = ?",+ (research_id,),+ )+ result = cursor.fetchone()++ # Calculate the duration+ duration_seconds = calculate_duration(result[0]) if result and result[0] else None++ # Update the database with suspended status+ cursor.execute(+ "UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ? WHERE id = ?",+ ("suspended", completed_at, duration_seconds, research_id),+ )+ conn.commit()+ conn.close()++ # Clean up resources+ cleanup_research_resources(research_id, active_research, termination_flags)\ No newline at end of filediff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pynew file mode 100644index 0000000000..96e931b159--- /dev/null+++ b/src/local_deep_research/web/services/socket_service.py@@ -0,0 +1,86 @@+import logging++# Initialize logger+logger = logging.getLogger(__name__)++# Make this a module variable to be set by the Flask app on initialization+socketio = None++def set_socketio(socket_instance):+ """Set the Socket.IO instance for the service."""+ global socketio+ socketio = socket_instance+ logger.info("Socket.IO instance attached to socket service")++def emit_socket_event(event, data, room=None):+ """+ Emit a socket event to clients.++ Args:+ event: The event name to emit+ data: The data to send with the event+ room: Optional room ID to send to specific client++ Returns:+ bool: True if emission was successful, False otherwise+ """+ global socketio++ if not socketio:+ logger.error("Socket.IO not initialized when attempting to emit event")+ return False++ try:+ # If room is specified, only emit to that room+ if room:+ socketio.emit(event, data, room=room)+ else:+ # Otherwise broadcast to all+ socketio.emit(event, data)+ return True+ except Exception as e:+ logger.error(f"Error emitting socket event {event}: {str(e)}")+ return False++def emit_to_subscribers(event_base, research_id, data):+ """+ Emit an event to all subscribers of a specific research.++ Args:+ event_base: Base event name (will be formatted with research_id)+ research_id: ID of the research+ data: The data to send with the event++ Returns:+ bool: True if emission was successful, False otherwise+ """+ global socketio++ if not socketio:+ logger.error("Socket.IO not initialized when attempting to emit to subscribers")+ return False++ try:+ # Import locally to avoid circular imports+ from ..routes.research_routes import get_globals++ # Get socket subscription data+ globals_dict = get_globals()+ socket_subscriptions = globals_dict.get('socket_subscriptions', {})++ # Emit to the general channel for the research+ full_event = f"{event_base}_{research_id}"+ socketio.emit(full_event, data)++ # Emit to specific subscribers+ if research_id in socket_subscriptions and socket_subscriptions[research_id]:+ for sid in socket_subscriptions[research_id]:+ try:+ socketio.emit(full_event, data, room=sid)+ except Exception as sub_err:+ logger.error(f"Error emitting to subscriber {sid}: {str(sub_err)}")++ return True+ except Exception as e:+ logger.error(f"Error emitting to subscribers for research {research_id}: {str(e)}")+ return False\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/detail.js b/src/local_deep_research/web/static/js/components/detail.jsnew file mode 100644index 0000000000..f2d5def7c8--- /dev/null+++ b/src/local_deep_research/web/static/js/components/detail.js@@ -0,0 +1,336 @@+/**+ * Detail Component+ * Manages the display of detailed information for a specific research topic+ */+(function() {+ // DOM Elements+ let detailContainer = null;+ let sourcesList = null;+ let tabsContainer = null;++ // Component state+ let currentResearchId = null;+ let currentTopicId = null;+ let detailData = null;++ /**+ * Initialize the detail component+ */+ function initializeDetail() {+ // Get IDs from URL+ const ids = getIdsFromUrl();+ currentResearchId = ids.researchId;+ currentTopicId = ids.topicId;++ if (!currentResearchId || !currentTopicId) {+ console.error('No research or topic ID found');+ window.ui.showError('Invalid research or topic. Please return to the results page.');+ return;+ }++ // Get DOM elements+ detailContainer = document.getElementById('detail-content');+ sourcesList = document.getElementById('sources-list');+ tabsContainer = document.getElementById('detail-tabs');++ if (!detailContainer) {+ console.error('Required DOM elements not found for detail component');+ return;+ }++ // Set up event listeners+ setupEventListeners();++ // Load topic detail+ loadTopicDetail();++ console.log('Detail component initialized for research:', currentResearchId, 'topic:', currentTopicId);+ }++ /**+ * Extract research and topic IDs from URL+ * @returns {Object} Object with researchId and topicId+ */+ function getIdsFromUrl() {+ const pathParts = window.location.pathname.split('/');+ const detailIndex = pathParts.indexOf('detail');++ if (detailIndex > 0 && detailIndex + 2 < pathParts.length) {+ return {+ researchId: pathParts[detailIndex + 1],+ topicId: pathParts[detailIndex + 2]+ };+ }++ return { researchId: null, topicId: null };+ }++ /**+ * Set up event listeners+ */+ function setupEventListeners() {+ // Tab click events+ if (tabsContainer) {+ tabsContainer.addEventListener('click', function(e) {+ if (e.target && e.target.matches('.tab-item')) {+ const tabId = e.target.dataset.tab;+ switchTab(tabId);+ }+ });+ }++ // Source highlight and citation copy+ if (sourcesList) {+ sourcesList.addEventListener('click', function(e) {+ // Handle citation copy+ if (e.target && e.target.matches('.copy-citation-btn')) {+ const sourceId = e.target.closest('.source-item').dataset.id;+ handleCopyCitation(sourceId);+ }++ // Handle source highlighting+ if (e.target && e.target.closest('.source-item')) {+ const sourceItem = e.target.closest('.source-item');+ if (!e.target.matches('.copy-citation-btn')) {+ toggleSourceHighlight(sourceItem);+ }+ }+ });+ }+ }++ /**+ * Load topic detail from API+ */+ async function loadTopicDetail() {+ // Show loading state+ window.ui.showSpinner(detailContainer, 'Loading topic details...');++ try {+ // Get topic detail+ detailData = await window.api.getTopicDetail(currentResearchId, currentTopicId);++ if (!detailData) {+ throw new Error('No topic details found');+ }++ // Render detail+ renderDetail(detailData);+ } catch (error) {+ console.error('Error loading topic detail:', error);+ window.ui.hideSpinner(detailContainer);+ window.ui.showError('Error loading topic detail: ' + error.message);+ }+ }++ /**+ * Render topic detail+ * @param {Object} data - The topic detail data+ */+ function renderDetail(data) {+ // Hide spinner+ window.ui.hideSpinner(detailContainer);++ // Set page title+ document.title = `${data.title || 'Topic Detail'} - Local Deep Research`;++ // Update page header+ const pageTitle = document.querySelector('h1.page-title');+ if (pageTitle && data.title) {+ pageTitle.textContent = data.title;+ }++ // Render content+ if (data.content) {+ // Render markdown+ const renderedHtml = window.ui.renderMarkdown(data.content);+ detailContainer.innerHTML = renderedHtml;++ // Add syntax highlighting+ highlightCodeBlocks();+ } else {+ detailContainer.innerHTML = '<p class="text-error">No content available for this topic.</p>';+ }++ // Render sources+ if (sourcesList && data.sources && data.sources.length > 0) {+ renderSources(data.sources);+ }++ // Set sources count+ const sourcesCountEl = document.getElementById('sources-count');+ if (sourcesCountEl && data.sources) {+ sourcesCountEl.textContent = `${data.sources.length} source${data.sources.length !== 1 ? 's' : ''}`;+ }++ // Show first tab+ if (tabsContainer) {+ const firstTab = tabsContainer.querySelector('.tab-item');+ if (firstTab) {+ switchTab(firstTab.dataset.tab);+ }+ }+ }++ /**+ * Render sources list+ * @param {Array} sources - Array of source objects+ */+ function renderSources(sources) {+ sourcesList.innerHTML = '';++ sources.forEach((source, index) => {+ const sourceEl = document.createElement('div');+ sourceEl.className = 'source-item';+ sourceEl.dataset.id = index;++ const title = source.title || source.url || `Source ${index + 1}`;+ const url = source.url || '';+ const author = source.author || '';+ const date = source.date || '';++ sourceEl.innerHTML = `+ <div class="source-header">+ <h4 class="source-title">${title}</h4>+ <button class="copy-citation-btn" title="Copy citation">+ <i class="fas fa-clipboard"></i>+ </button>+ </div>+ ${url ? `<div class="source-url"><a href="${url}" target="_blank">${url}</a></div>` : ''}+ <div class="source-metadata">+ ${author ? `<span><i class="fas fa-user"></i> ${author}</span>` : ''}+ ${date ? `<span><i class="far fa-calendar"></i> ${date}</span>` : ''}+ </div>+ ${source.relevance ? `<div class="source-relevance">Relevance: ${source.relevance}</div>` : ''}+ `;++ sourcesList.appendChild(sourceEl);+ });+ }++ /**+ * Switch between tabs+ * @param {string} tabId - The tab ID to switch to+ */+ function switchTab(tabId) {+ // Update active tab+ const tabs = document.querySelectorAll('.tab-item');+ tabs.forEach(tab => {+ tab.classList.toggle('active', tab.dataset.tab === tabId);+ });++ // Update visible content+ const tabContents = document.querySelectorAll('.tab-content');+ tabContents.forEach(content => {+ content.style.display = content.dataset.tab === tabId ? 'block' : 'none';+ });+ }++ /**+ * Toggle source highlight+ * @param {HTMLElement} sourceEl - The source element to highlight+ */+ function toggleSourceHighlight(sourceEl) {+ // Remove highlight from all sources+ const allSources = document.querySelectorAll('.source-item');+ allSources.forEach(s => s.classList.remove('highlighted'));++ // Add highlight to clicked source+ sourceEl.classList.add('highlighted');++ // Get source index+ const sourceIndex = parseInt(sourceEl.dataset.id);++ // Highlight content with this source+ highlightContentFromSource(sourceIndex);+ }++ /**+ * Highlight content sections from a specific source+ * @param {number} sourceIndex - The source index to highlight+ */+ function highlightContentFromSource(sourceIndex) {+ // Remove all existing highlights+ const allCitations = document.querySelectorAll('.citation-highlight');+ allCitations.forEach(el => {+ el.classList.remove('citation-highlight');+ });++ // Add highlight to citations from this source+ const citations = document.querySelectorAll(`.citation[data-source="${sourceIndex}"]`);+ citations.forEach(citation => {+ citation.classList.add('citation-highlight');++ // Scroll to first citation+ if (citations.length > 0) {+ citations[0].scrollIntoView({ behavior: 'smooth', block: 'center' });+ }+ });+ }++ /**+ * Handle copying citation+ * @param {number} sourceIndex - The source index to copy+ */+ async function handleCopyCitation(sourceIndex) {+ if (!detailData || !detailData.sources || !detailData.sources[sourceIndex]) {+ return;+ }++ const source = detailData.sources[sourceIndex];++ // Format citation+ let citation = '';++ if (source.author) {+ citation += source.author;+ if (source.date) {+ citation += ` (${source.date})`;+ }+ citation += '. ';+ }++ if (source.title) {+ citation += `"${source.title}". `;+ }++ if (source.url) {+ citation += `Retrieved from ${source.url}`;+ }++ // Copy to clipboard+ try {+ await navigator.clipboard.writeText(citation);++ // Show tooltip+ const btn = document.querySelector(`.source-item[data-id="${sourceIndex}"] .copy-citation-btn`);+ if (btn) {+ const originalHTML = btn.innerHTML;+ btn.innerHTML = '<i class="fas fa-check"></i>';++ setTimeout(() => {+ btn.innerHTML = originalHTML;+ }, 2000);+ }+ } catch (error) {+ console.error('Failed to copy citation:', error);+ }+ }++ /**+ * Apply syntax highlighting to code blocks+ */+ function highlightCodeBlocks() {+ // Check if Prism is available+ if (typeof Prism !== 'undefined') {+ Prism.highlightAllUnder(detailContainer);+ }+ }++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeDetail);+ } else {+ initializeDetail();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.jsnew file mode 100644index 0000000000..76aa71768f--- /dev/null+++ b/src/local_deep_research/web/static/js/components/history.js@@ -0,0 +1,277 @@+/**+ * History Component+ * Manages the display and interaction with research history+ */+(function() {+ // DOM Elements+ let historyContainer = null;+ let searchInput = null;+ let clearHistoryBtn = null;+ let historyEmptyMessage = null;++ // Component state+ let historyItems = [];+ let filteredItems = [];++ /**+ * Initialize the history component+ */+ function initializeHistory() {+ // Get DOM elements+ historyContainer = document.getElementById('history-items');+ searchInput = document.getElementById('history-search');+ clearHistoryBtn = document.getElementById('clear-history-btn');+ historyEmptyMessage = document.getElementById('history-empty-message');++ if (!historyContainer) {+ console.error('Required DOM elements not found for history component');+ return;+ }++ // Set up event listeners+ setupEventListeners();++ // Load history data+ loadHistoryData();++ console.log('History component initialized');+ }++ /**+ * Set up event listeners+ */+ function setupEventListeners() {+ // Search input+ if (searchInput) {+ searchInput.addEventListener('input', handleSearchInput);+ }++ // Clear history button+ if (clearHistoryBtn) {+ clearHistoryBtn.addEventListener('click', handleClearHistory);+ }++ // Delegation for history item clicks+ if (historyContainer) {+ historyContainer.addEventListener('click', function(e) {+ // Handle delete button click+ if (e.target && e.target.closest('.delete-item-btn')) {+ const itemId = e.target.closest('.history-item').dataset.id;+ handleDeleteItem(itemId);+ }+ });+ }+ }++ /**+ * Load history data from API+ */+ async function loadHistoryData() {+ // Show loading state+ window.ui.showSpinner(historyContainer, 'Loading research history...');++ try {+ // Get history items+ const response = await window.api.getResearchHistory();++ if (response && Array.isArray(response.items)) {+ historyItems = response.items;+ filteredItems = [...historyItems];++ // Render history items+ renderHistoryItems();+ } else {+ throw new Error('Invalid response format');+ }+ } catch (error) {+ console.error('Error loading history:', error);+ window.ui.hideSpinner(historyContainer);+ window.ui.showError('Error loading history: ' + error.message);+ }+ }++ /**+ * Render history items+ */+ function renderHistoryItems() {+ // Hide spinner+ window.ui.hideSpinner(historyContainer);++ // Clear container+ historyContainer.innerHTML = '';++ // Show empty message if no items+ if (filteredItems.length === 0) {+ if (historyEmptyMessage) {+ historyEmptyMessage.style.display = 'block';+ } else {+ historyContainer.innerHTML = `+ <div class="empty-state">+ <i class="fas fa-history empty-icon"></i>+ <p>No research history found.</p>+ ${searchInput && searchInput.value ? '<p>Try adjusting your search query.</p>' : ''}+ </div>+ `;+ }++ if (clearHistoryBtn) {+ clearHistoryBtn.style.display = 'none';+ }+ return;+ }++ // Hide empty message+ if (historyEmptyMessage) {+ historyEmptyMessage.style.display = 'none';+ }++ // Show clear button+ if (clearHistoryBtn) {+ clearHistoryBtn.style.display = 'inline-block';+ }++ // Create items+ filteredItems.forEach(item => {+ const itemElement = createHistoryItemElement(item);+ historyContainer.appendChild(itemElement);+ });+ }++ /**+ * Create a history item element+ * @param {Object} item - The history item data+ * @returns {HTMLElement} The history item element+ */+ function createHistoryItemElement(item) {+ const itemEl = document.createElement('div');+ itemEl.className = 'history-item';+ itemEl.dataset.id = item.id;++ // Status class+ if (item.status) {+ itemEl.classList.add(`status-${item.status}`);+ }++ // Format date+ const formattedDate = window.formatting.formatDate(item.created_at);++ // Create result link if completed+ const resultLink = item.status === 'completed'+ ? `<a href="/research/results/${item.id}" class="view-results-btn">+ <i class="fas fa-eye"></i> View Results+ </a>`+ : '';++ // Create status badge+ const statusBadge = `<span class="status-badge status-${item.status}">+ ${window.formatting.formatStatus(item.status)}+ </span>`;++ // Set item content+ itemEl.innerHTML = `+ <div class="item-header">+ <h3 class="item-title">${item.title || 'Untitled Research'}</h3>+ ${statusBadge}+ </div>+ <div class="item-query">${item.query || ''}</div>+ <div class="item-metadata">+ <span><i class="far fa-clock"></i> ${formattedDate}</span>+ <span><i class="fas fa-tag"></i> ${window.formatting.formatMode(item.mode)}</span>+ ${item.duration_seconds ? `<span><i class="fas fa-hourglass-end"></i> ${Math.floor(item.duration_seconds / 60)}m ${item.duration_seconds % 60}s</span>` : ''}+ </div>+ <div class="item-actions">+ ${resultLink}+ <button class="delete-item-btn" aria-label="Delete research">+ <i class="fas fa-trash-alt"></i>+ </button>+ </div>+ `;++ return itemEl;+ }++ /**+ * Handle search input+ */+ function handleSearchInput() {+ const searchTerm = searchInput.value.trim().toLowerCase();++ if (!searchTerm) {+ // Reset to show all items+ filteredItems = [...historyItems];+ } else {+ // Filter items based on search term+ filteredItems = historyItems.filter(item => {+ return (+ (item.title && item.title.toLowerCase().includes(searchTerm)) ||+ (item.query && item.query.toLowerCase().includes(searchTerm))+ );+ });+ }++ // Render filtered items+ renderHistoryItems();+ }++ /**+ * Handle delete item+ * @param {string} itemId - The item ID to delete+ */+ async function handleDeleteItem(itemId) {+ if (!confirm('Are you sure you want to delete this research? This action cannot be undone.')) {+ return;+ }++ try {+ // Delete item via API+ await window.api.deleteResearch(itemId);++ // Remove from arrays+ historyItems = historyItems.filter(item => item.id != itemId);+ filteredItems = filteredItems.filter(item => item.id != itemId);++ // Show success message+ window.ui.showMessage('Research deleted successfully');++ // Re-render history items+ renderHistoryItems();+ } catch (error) {+ console.error('Error deleting research:', error);+ window.ui.showError('Error deleting research: ' + error.message);+ }+ }++ /**+ * Handle clear history+ */+ async function handleClearHistory() {+ if (!confirm('Are you sure you want to clear all research history? This action cannot be undone.')) {+ return;+ }++ try {+ // Clear history via API+ await window.api.clearResearchHistory();++ // Clear arrays+ historyItems = [];+ filteredItems = [];++ // Show success message+ window.ui.showMessage('Research history cleared successfully');++ // Re-render history items+ renderHistoryItems();+ } catch (error) {+ console.error('Error clearing history:', error);+ window.ui.showError('Error clearing history: ' + error.message);+ }+ }++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeHistory);+ } else {+ initializeHistory();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.jsnew file mode 100644index 0000000000..e3ba501461--- /dev/null+++ b/src/local_deep_research/web/static/js/components/progress.js@@ -0,0 +1,295 @@+/**+ * Progress Component+ * Manages research progress display and updates via Socket.IO+ */+(function() {+ // Component state+ let currentResearchId = null;+ let pollInterval = null;+ let isCompleted = false;++ // DOM Elements+ let progressBar = null;+ let statusText = null;+ let currentTaskText = null;+ let cancelButton = null;+ let viewResultsButton = null;++ /**+ * Initialize the progress component+ */+ function initializeProgress() {+ // Get research ID from URL or localStorage+ currentResearchId = getResearchIdFromUrl() || localStorage.getItem('currentResearchId');++ if (!currentResearchId) {+ console.error('No research ID found');+ window.ui.showError('No active research found. Please start a new research.');+ setTimeout(() => {+ window.location.href = '/';+ }, 3000);+ return;+ }++ // Get DOM elements+ progressBar = document.getElementById('progress-bar');+ statusText = document.getElementById('status-text');+ currentTaskText = document.getElementById('current-task');+ cancelButton = document.getElementById('cancel-research-btn');+ viewResultsButton = document.getElementById('view-results-btn');++ if (!progressBar || !statusText || !currentTaskText) {+ console.error('Required DOM elements not found for progress component');+ return;+ }++ // Set up event listeners+ if (cancelButton) {+ cancelButton.addEventListener('click', handleCancelResearch);+ }++ // Initialize socket connection+ initializeSocket();++ // Initial progress check+ checkProgress();++ console.log('Progress component initialized for research ID:', currentResearchId);+ }++ /**+ * Extract research ID from URL+ * @returns {string|null} The research ID or null if not found+ */+ function getResearchIdFromUrl() {+ const pathParts = window.location.pathname.split('/');+ const idIndex = pathParts.indexOf('progress') + 1;++ if (idIndex > 0 && idIndex < pathParts.length) {+ return pathParts[idIndex];+ }++ return null;+ }++ /**+ * Initialize Socket.IO connection and listeners+ */+ function initializeSocket() {+ // Subscribe to research events+ window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);++ // Handle socket reconnection+ window.socket.onReconnect(() => {+ console.log('Socket reconnected, resubscribing to research events');+ window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);+ });+ }++ /**+ * Handle progress updates from Socket.IO+ * @param {Object} data - The progress data+ */+ function handleProgressUpdate(data) {+ console.log('Received progress update:', data);++ if (!data) return;++ // Update progress UI+ updateProgressUI(data);++ // Check if research is completed+ if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ handleResearchCompletion(data);+ }+ }++ /**+ * Check research progress via API+ */+ async function checkProgress() {+ try {+ const data = await window.api.getResearchStatus(currentResearchId);++ if (data) {+ // Update progress UI+ updateProgressUI(data);++ // Check if research is completed+ if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ handleResearchCompletion(data);+ } else {+ // Set up polling for status updates as backup for socket+ if (!pollInterval) {+ pollInterval = setInterval(checkProgress, 5000);+ }+ }+ }+ } catch (error) {+ console.error('Error checking research progress:', error);+ statusText.textContent = 'Error checking research status';+ }+ }++ /**+ * Update the progress UI with data+ * @param {Object} data - The progress data+ */+ function updateProgressUI(data) {+ // Update progress bar+ if (data.progress !== undefined) {+ window.ui.updateProgressBar(progressBar, data.progress);+ }++ // Update status text+ if (data.status) {+ statusText.textContent = window.formatting.formatStatus(data.status);++ // Add status class for styling+ document.querySelectorAll('.status-indicator').forEach(el => {+ el.className = 'status-indicator';+ el.classList.add(`status-${data.status}`);+ });+ }++ // Update current task+ if (data.current_task) {+ currentTaskText.textContent = data.current_task;+ }++ // Update page title with progress+ if (data.progress !== undefined) {+ document.title = `Research (${Math.floor(data.progress)}%) - Local Deep Research`;+ }++ // Update favicon based on status+ window.ui.updateFavicon(data.status);++ // Show notification if enabled+ if (data.status === 'completed' && localStorage.getItem('notificationsEnabled') === 'true') {+ showNotification('Research Completed', 'Your research has been completed successfully.');+ }+ }++ /**+ * Handle research completion+ * @param {Object} data - The completion data+ */+ function handleResearchCompletion(data) {+ if (isCompleted) return;+ isCompleted = true;++ // Clear polling interval+ if (pollInterval) {+ clearInterval(pollInterval);+ pollInterval = null;+ }++ // Update UI for completion+ if (data.status === 'completed') {+ // Show view results button+ if (viewResultsButton) {+ viewResultsButton.style.display = 'inline-block';+ viewResultsButton.href = `/research/results/${currentResearchId}`;+ }++ // Hide cancel button+ if (cancelButton) {+ cancelButton.style.display = 'none';+ }+ } else if (data.status === 'failed' || data.status === 'cancelled') {+ // Show error message+ window.ui.showError(data.error || 'Research was unsuccessful');++ // Update button to go back to home+ if (viewResultsButton) {+ viewResultsButton.textContent = 'Start New Research';+ viewResultsButton.href = '/';+ viewResultsButton.style.display = 'inline-block';+ }++ // Hide cancel button+ if (cancelButton) {+ cancelButton.style.display = 'none';+ }+ }+ }++ /**+ * Handle research cancellation+ */+ async function handleCancelResearch() {+ if (!confirm('Are you sure you want to cancel this research?')) {+ return;+ }++ // Disable cancel button+ if (cancelButton) {+ cancelButton.disabled = true;+ cancelButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cancelling...';+ }++ try {+ await window.api.cancelResearch(currentResearchId);++ // Update status manually (in case socket fails)+ statusText.textContent = 'Cancelled';+ document.querySelectorAll('.status-indicator').forEach(el => {+ el.className = 'status-indicator status-cancelled';+ });++ // Show message+ window.ui.showMessage('Research has been cancelled.');++ // Update cancel button+ if (cancelButton) {+ cancelButton.style.display = 'none';+ }++ // Show go home button+ if (viewResultsButton) {+ viewResultsButton.textContent = 'Start New Research';+ viewResultsButton.href = '/';+ viewResultsButton.style.display = 'inline-block';+ }+ } catch (error) {+ console.error('Error cancelling research:', error);+ window.ui.showError('Error cancelling research: ' + error.message);++ // Re-enable cancel button+ if (cancelButton) {+ cancelButton.disabled = false;+ cancelButton.innerHTML = '<i class="fas fa-times"></i> Cancel Research';+ }+ }+ }++ /**+ * Show browser notification+ * @param {string} title - Notification title+ * @param {string} body - Notification body+ */+ function showNotification(title, body) {+ if (!("Notification" in window)) {+ console.log("Browser does not support notifications");+ return;+ }++ if (Notification.permission === "granted") {+ new Notification(title, { body, icon: '/static/favicon.ico' });+ } else if (Notification.permission !== "denied") {+ Notification.requestPermission().then(permission => {+ if (permission === "granted") {+ new Notification(title, { body, icon: '/static/favicon.ico' });+ }+ });+ }+ }++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeProgress);+ } else {+ initializeProgress();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsnew file mode 100644index 0000000000..a7bf931f3c--- /dev/null+++ b/src/local_deep_research/web/static/js/components/research.js@@ -0,0 +1,169 @@+/**+ * Research Component+ * Manages the research form and handles submissions+ */+(function() {+ // DOM Elements+ let form = null;+ let queryInput = null;+ let modeOptions = null;+ let notificationToggle = null;+ let startBtn = null;++ /**+ * Initialize the research component+ */+ function initializeResearch() {+ // Get DOM elements+ form = document.getElementById('research-form');+ queryInput = document.getElementById('query');+ modeOptions = document.querySelectorAll('.mode-option');+ notificationToggle = document.getElementById('notification-toggle');+ startBtn = document.getElementById('start-research-btn');++ if (!form || !queryInput || !modeOptions.length || !startBtn) {+ console.error('Required DOM elements not found for research component');+ return;+ }++ // Set up event listeners+ setupEventListeners();++ console.log('Research component initialized');+ }++ /**+ * Set up event listeners for the research form+ */+ function setupEventListeners() {+ // Mode selection toggle+ modeOptions.forEach(option => {+ option.addEventListener('click', function() {+ // Remove active class from all options+ modeOptions.forEach(opt => opt.classList.remove('active'));++ // Add active class to clicked option+ this.classList.add('active');+ });+ });++ // Form submission+ form.addEventListener('submit', handleResearchSubmit);+ }++ /**+ * Handle research form submission+ * @param {Event} e - The form submit event+ */+ async function handleResearchSubmit(e) {+ e.preventDefault();++ // Get form values+ const query = queryInput.value.trim();+ const activeMode = document.querySelector('.mode-option.active');+ const mode = activeMode ? activeMode.dataset.mode : 'quick';+ const enableNotifications = notificationToggle ? notificationToggle.checked : true;++ // Validate input+ if (!query) {+ showFormError('Please enter a research query');+ return;+ }++ // Disable form+ setFormSubmitting(true);++ try {+ // Start research process+ const response = await window.api.startResearch(query, mode);++ if (response && response.status === 'success' && response.research_id) {+ // Store research settings+ window.localStorage.setItem('notificationsEnabled', enableNotifications);++ // Navigate to progress page+ navigateToResearchProgress(response.research_id, query, mode);+ } else {+ throw new Error('Invalid response from server');+ }+ } catch (error) {+ console.error('Error starting research:', error);++ // Handle common errors+ if (error.message.includes('409')) {+ showFormError('Another research is already in progress. Please wait for it to complete.');+ } else {+ showFormError(`Error starting research: ${error.message}`);+ }++ // Re-enable the form+ setFormSubmitting(false);+ }+ }++ /**+ * Show an error message on the form+ * @param {string} message - The error message to display+ */+ function showFormError(message) {+ // Check if error element already exists+ let errorEl = form.querySelector('.form-error');++ if (!errorEl) {+ // Create error element+ errorEl = document.createElement('div');+ errorEl.className = 'form-error';+ form.insertBefore(errorEl, form.querySelector('.form-actions'));+ }++ // Set error message+ errorEl.textContent = message;+ errorEl.style.display = 'block';++ // Hide error after 5 seconds+ setTimeout(() => {+ errorEl.style.display = 'none';+ }, 5000);+ }++ /**+ * Set the form to submitting state+ * @param {boolean} isSubmitting - Whether the form is submitting+ */+ function setFormSubmitting(isSubmitting) {+ startBtn.disabled = isSubmitting;+ queryInput.disabled = isSubmitting;++ modeOptions.forEach(option => {+ option.style.pointerEvents = isSubmitting ? 'none' : 'auto';+ option.style.opacity = isSubmitting ? '0.7' : '1';+ });++ startBtn.innerHTML = isSubmitting ?+ '<i class="fas fa-spinner fa-spin"></i> Starting...' :+ '<i class="fas fa-rocket"></i> Start Research';+ }++ /**+ * Navigate to the research progress page+ * @param {number} researchId - The research ID+ * @param {string} query - The research query+ * @param {string} mode - The research mode+ */+ function navigateToResearchProgress(researchId, query, mode) {+ // Store current research info in local storage+ window.localStorage.setItem('currentResearchId', researchId);+ window.localStorage.setItem('currentQuery', query);+ window.localStorage.setItem('currentMode', mode);++ // Navigate to progress page+ window.location.href = `/research/progress/${researchId}`;+ }++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeResearch);+ } else {+ initializeResearch();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.jsnew file mode 100644index 0000000000..c2702fa9d5--- /dev/null+++ b/src/local_deep_research/web/static/js/components/results.js@@ -0,0 +1,343 @@+/**+ * Results Component+ * Manages the display and interaction with research results+ */+(function() {+ // Component state+ let currentResearchId = null;+ let researchData = null;++ // DOM Elements+ let resultsContainer = null;+ let metadataContainer = null;+ let exportPdfBtn = null;+ let exportMarkdownBtn = null;+ let backToHomeBtn = null;++ /**+ * Initialize the results component+ */+ function initializeResults() {+ // Get research ID from URL+ currentResearchId = getResearchIdFromUrl();++ if (!currentResearchId) {+ console.error('No research ID found');+ window.ui.showError('No research results found. Please start a new research.');+ setTimeout(() => {+ window.location.href = '/';+ }, 3000);+ return;+ }++ // Get DOM elements+ resultsContainer = document.getElementById('results-content');+ metadataContainer = document.getElementById('research-metadata');+ exportPdfBtn = document.getElementById('export-pdf-btn');+ exportMarkdownBtn = document.getElementById('export-markdown-btn');+ backToHomeBtn = document.getElementById('back-home-btn');++ if (!resultsContainer) {+ console.error('Required DOM elements not found for results component');+ return;+ }++ // Set up event listeners+ setupEventListeners();++ // Load research results+ loadResearchResults();++ console.log('Results component initialized for research ID:', currentResearchId);+ }++ /**+ * Extract research ID from URL+ * @returns {string|null} The research ID or null if not found+ */+ function getResearchIdFromUrl() {+ const pathParts = window.location.pathname.split('/');+ const idIndex = pathParts.indexOf('results') + 1;++ if (idIndex > 0 && idIndex < pathParts.length) {+ return pathParts[idIndex];+ }++ return null;+ }++ /**+ * Set up event listeners+ */+ function setupEventListeners() {+ if (exportPdfBtn) {+ exportPdfBtn.addEventListener('click', handleExportPdf);+ }++ if (exportMarkdownBtn) {+ exportMarkdownBtn.addEventListener('click', handleExportMarkdown);+ }++ // Set up table of contents click events+ document.addEventListener('click', function(e) {+ if (e.target && e.target.matches('.toc-link')) {+ e.preventDefault();+ const targetId = e.target.getAttribute('href').substring(1);+ const targetElement = document.getElementById(targetId);++ if (targetElement) {+ // Smooth scroll to section+ targetElement.scrollIntoView({ behavior: 'smooth' });+ }+ }+ });+ }++ /**+ * Load research results from API+ */+ async function loadResearchResults() {+ // Show loading state+ window.ui.showSpinner(resultsContainer, 'Loading research results...');++ try {+ // Get research results+ researchData = await window.api.getResearchResults(currentResearchId);++ if (!researchData || !researchData.content) {+ throw new Error('No research results found');+ }++ // Render results+ renderResults(researchData);+ } catch (error) {+ console.error('Error loading research results:', error);+ window.ui.hideSpinner(resultsContainer);+ window.ui.showError('Error loading research results: ' + error.message);+ }+ }++ /**+ * Render research results+ * @param {Object} data - The research data+ */+ function renderResults(data) {+ // Hide spinner+ window.ui.hideSpinner(resultsContainer);++ // Set page title+ document.title = `${data.title || 'Research Results'} - Local Deep Research`;++ // Render metadata+ if (metadataContainer) {+ renderMetadata(data);+ }++ // Render content+ if (data.content) {+ // Render markdown+ const renderedHtml = window.ui.renderMarkdown(data.content);+ resultsContainer.innerHTML = renderedHtml;++ // Generate table of contents+ generateTableOfContents();++ // Add syntax highlighting+ highlightCodeBlocks();+ } else {+ resultsContainer.innerHTML = '<p class="text-error">No research content available.</p>';+ }++ // Enable export buttons+ if (exportPdfBtn) exportPdfBtn.disabled = false;+ if (exportMarkdownBtn) exportMarkdownBtn.disabled = false;+ }++ /**+ * Render research metadata+ * @param {Object} data - The research data+ */+ function renderMetadata(data) {+ const metadata = [];++ // Research title+ if (data.title) {+ document.querySelector('h1.page-title').textContent = data.title;+ }++ // Query+ if (data.query) {+ metadata.push(`<div class="metadata-item"><span>Query:</span> ${data.query}</div>`);+ }++ // Mode+ if (data.mode) {+ metadata.push(`<div class="metadata-item"><span>Mode:</span> ${window.formatting.formatMode(data.mode)}</div>`);+ }++ // Completed date+ if (data.completed_at) {+ metadata.push(`<div class="metadata-item"><span>Completed:</span> ${window.formatting.formatDate(data.completed_at)}</div>`);+ }++ // Duration+ if (data.duration_seconds) {+ const minutes = Math.floor(data.duration_seconds / 60);+ const seconds = data.duration_seconds % 60;+ metadata.push(`<div class="metadata-item"><span>Duration:</span> ${minutes}m ${seconds}s</div>`);+ }++ // Sources count+ if (data.sources_count) {+ metadata.push(`<div class="metadata-item"><span>Sources:</span> ${data.sources_count}</div>`);+ }++ // Render metadata+ metadataContainer.innerHTML = metadata.join('');+ }++ /**+ * Generate table of contents from headings+ */+ function generateTableOfContents() {+ const tocContainer = document.getElementById('table-of-contents');+ if (!tocContainer) return;++ const headings = resultsContainer.querySelectorAll('h2, h3, h4');+ if (headings.length === 0) {+ tocContainer.closest('.toc-container').style.display = 'none';+ return;+ }++ const tocItems = [];++ // Process each heading+ headings.forEach((heading, index) => {+ // Add ID if not present+ if (!heading.id) {+ heading.id = `heading-${index}`;+ }++ const level = parseInt(heading.tagName.substring(1)) - 2;+ const indentation = ' '.repeat(level);++ tocItems.push(`${indentation}<li><a href="#${heading.id}" class="toc-link">${heading.textContent}</a></li>`);+ });++ // Render table of contents+ tocContainer.innerHTML = `<ul>${tocItems.join('')}</ul>`;+ }++ /**+ * Apply syntax highlighting to code blocks+ */+ function highlightCodeBlocks() {+ // Check if Prism is available+ if (typeof Prism !== 'undefined') {+ Prism.highlightAllUnder(resultsContainer);+ }+ }++ /**+ * Handle PDF export+ */+ function handleExportPdf() {+ if (!researchData) return;++ // Disable button+ if (exportPdfBtn) {+ exportPdfBtn.disabled = true;+ exportPdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';+ }++ try {+ // Generate and download PDF+ window.pdf.downloadPdf(+ researchData.title || 'Research Results',+ researchData.content,+ {+ query: researchData.query,+ mode: window.formatting.formatMode(researchData.mode),+ completed: window.formatting.formatDate(researchData.completed_at),+ sources: researchData.sources_count+ }+ );++ // Reset button state after delay+ setTimeout(() => {+ if (exportPdfBtn) {+ exportPdfBtn.disabled = false;+ exportPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';+ }+ }, 1000);+ } catch (error) {+ console.error('Error generating PDF:', error);+ window.ui.showError('Error generating PDF: ' + error.message);++ // Reset button state+ if (exportPdfBtn) {+ exportPdfBtn.disabled = false;+ exportPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Export as PDF';+ }+ }+ }++ /**+ * Handle Markdown export+ */+ async function handleExportMarkdown() {+ if (!researchData || !researchData.content) return;++ // Disable button+ if (exportMarkdownBtn) {+ exportMarkdownBtn.disabled = true;+ exportMarkdownBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating Markdown...';+ }++ try {+ // Get raw markdown content+ const response = await window.api.getMarkdownExport(currentResearchId);++ if (!response || !response.content) {+ throw new Error('Failed to get markdown content');+ }++ // Create blob and download link+ const blob = new Blob([response.content], { type: 'text/markdown' });+ const url = URL.createObjectURL(blob);++ const a = document.createElement('a');+ a.href = url;+ a.download = `${researchData.title || 'research-results'}.md`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);++ // Show success message+ window.ui.showMessage('Markdown file downloaded successfully');++ // Reset button state+ if (exportMarkdownBtn) {+ exportMarkdownBtn.disabled = false;+ exportMarkdownBtn.innerHTML = '<i class="fas fa-file-alt"></i> Export as Markdown';+ }+ } catch (error) {+ console.error('Error generating Markdown:', error);+ window.ui.showError('Error generating Markdown: ' + error.message);++ // Reset button state+ if (exportMarkdownBtn) {+ exportMarkdownBtn.disabled = false;+ exportMarkdownBtn.innerHTML = '<i class="fas fa-file-alt"></i> Export as Markdown';+ }+ }+ }++ // Initialize on DOM content loaded+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeResults);+ } else {+ initializeResults();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/main.js b/src/local_deep_research/web/static/js/main.jsnew file mode 100644index 0000000000..5ca0de6ec2--- /dev/null+++ b/src/local_deep_research/web/static/js/main.js@@ -0,0 +1,175 @@+/**+ * Main JavaScript Entry Point+ * Loads appropriate components based on the current page+ */+(function() {+ // Map of page identifiers to component scripts+ const pageComponents = {+ 'page-home': ['research.js'],+ 'page-progress': ['progress.js'],+ 'page-results': ['results.js'],+ 'page-detail': ['detail.js'],+ 'page-history': ['history.js']+ };++ // Core services to always load+ const coreServices = [+ 'formatting.js',+ 'ui.js',+ 'api.js',+ 'socket.js'+ ];++ // Optional services to load when needed+ const optionalServices = {+ 'page-results': ['pdf.js'],+ 'page-detail': ['pdf.js']+ };++ /**+ * Initialize the application+ */+ function initializeApp() {+ // Detect current page+ const currentPage = detectCurrentPage();++ if (!currentPage) {+ console.error('Cannot detect current page type');+ return;+ }++ console.log('Current page detected:', currentPage);++ // Load core services+ loadScripts('services', coreServices);++ // Load optional services for this page+ if (optionalServices[currentPage]) {+ loadScripts('services', optionalServices[currentPage]);+ }++ // Load components for this page+ if (pageComponents[currentPage]) {+ loadScripts('components', pageComponents[currentPage]);+ }++ // Initialize tooltips and other global UI elements+ initializeGlobalUI();+ }++ /**+ * Detect the current page based on body class+ * @returns {string|null} The page identifier or null if not found+ */+ function detectCurrentPage() {+ const bodyClasses = document.body.classList;++ for (const pageId in pageComponents) {+ if (bodyClasses.contains(pageId)) {+ return pageId;+ }+ }++ // Check URL patterns as fallback+ const path = window.location.pathname;++ if (path === '/' || path === '/index' || path === '/home') {+ return 'page-home';+ } else if (path.includes('/research/progress')) {+ return 'page-progress';+ } else if (path.includes('/research/results')) {+ return 'page-results';+ } else if (path.includes('/research/detail')) {+ return 'page-detail';+ } else if (path.includes('/research/history')) {+ return 'page-history';+ }++ return null;+ }++ /**+ * Load scripts dynamically+ * @param {string} folder - The folder containing the scripts+ * @param {Array} scripts - Array of script filenames to load+ */+ function loadScripts(folder, scripts) {+ if (!scripts || !scripts.length) return;++ scripts.forEach(script => {+ const scriptElement = document.createElement('script');+ scriptElement.src = `/static/js/${folder}/${script}`;+ scriptElement.async = false; // Load in sequence+ document.body.appendChild(scriptElement);+ });+ }++ /**+ * Initialize global UI elements+ */+ function initializeGlobalUI() {+ // Initialize notifications if browser supports it+ if ("Notification" in window && Notification.permission === "default") {+ // Only ask for permission when user interacts with the page+ document.addEventListener('click', requestNotificationPermission, { once: true });+ }++ // Initialize theme toggle+ const themeToggle = document.getElementById('theme-toggle');+ if (themeToggle) {+ // Check for saved theme preference or use system preference+ const savedTheme = localStorage.getItem('theme');+ const systemDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;+ const isDarkMode = savedTheme === 'dark' || (savedTheme === null && systemDarkMode);++ // Set initial theme+ document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');+ themeToggle.innerHTML = isDarkMode ?+ '<i class="fas fa-sun"></i>' :+ '<i class="fas fa-moon"></i>';++ // Listen for theme toggle click+ themeToggle.addEventListener('click', function() {+ const currentTheme = document.documentElement.getAttribute('data-theme');+ const newTheme = currentTheme === 'dark' ? 'light' : 'dark';++ document.documentElement.setAttribute('data-theme', newTheme);+ localStorage.setItem('theme', newTheme);++ themeToggle.innerHTML = newTheme === 'dark' ?+ '<i class="fas fa-sun"></i>' :+ '<i class="fas fa-moon"></i>';+ });+ }++ // Initialize mobile menu toggle+ const mobileMenuToggle = document.getElementById('mobile-menu-toggle');+ const navMenu = document.getElementById('main-nav');++ if (mobileMenuToggle && navMenu) {+ mobileMenuToggle.addEventListener('click', function() {+ navMenu.classList.toggle('open');+ mobileMenuToggle.setAttribute(+ 'aria-expanded',+ navMenu.classList.contains('open') ? 'true' : 'false'+ );+ });+ }+ }++ /**+ * Request notification permission+ */+ function requestNotificationPermission() {+ if ("Notification" in window && Notification.permission === "default") {+ Notification.requestPermission();+ }+ }++ // Initialize when DOM is ready+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initializeApp);+ } else {+ initializeApp();+ }+})();\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.jsnew file mode 100644index 0000000000..acd32121eb--- /dev/null+++ b/src/local_deep_research/web/static/js/services/api.js@@ -0,0 +1,138 @@+/**+ * API Service+ * Handles all communication with the server API endpoints+ */++// Base URL for API+const API_BASE_URL = '/api';++/**+ * Get the full URL for an API endpoint+ * @param {string} path - The API path (without leading slash)+ * @returns {string} The full API URL+ */+function getApiUrl(path) {+ return `${API_BASE_URL}/${path}`;+}++/**+ * Generic fetch with error handling+ * @param {string} url - The URL to fetch+ * @param {Object} options - Fetch options+ * @returns {Promise<any>} The parsed response data+ */+async function fetchWithErrorHandling(url, options = {}) {+ try {+ const response = await fetch(url, {+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...(options.headers || {})+ }+ });++ // Handle non-200 responses+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.message || `API Error: ${response.status} ${response.statusText}`);+ }++ // Parse the response+ return await response.json();+ } catch (error) {+ console.error('API Error:', error);+ throw error;+ }+}++/**+ * Start a new research+ * @param {string} query - The research query+ * @param {string} mode - The research mode (quick/detailed)+ * @returns {Promise<Object>} The research response with ID+ */+async function startResearch(query, mode) {+ return fetchWithErrorHandling(getApiUrl('research/api/start_research'), {+ method: 'POST',+ body: JSON.stringify({ query, mode })+ });+}++/**+ * Get a research status by ID+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The research status+ */+async function getResearchStatus(researchId) {+ return fetchWithErrorHandling(getApiUrl(`research/${researchId}`));+}++/**+ * Get research details+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The research details+ */+async function getResearchDetails(researchId) {+ return fetchWithErrorHandling(getApiUrl(`research/${researchId}/details`));+}++/**+ * Get research logs+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The research logs+ */+async function getResearchLogs(researchId) {+ return fetchWithErrorHandling(getApiUrl(`research/${researchId}/logs`));+}++/**+ * Get research history+ * @returns {Promise<Array>} The research history+ */+async function getResearchHistory() {+ return fetchWithErrorHandling(getApiUrl('history'));+}++/**+ * Get research report+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The research report+ */+async function getReport(researchId) {+ return fetchWithErrorHandling(getApiUrl(`report/${researchId}`));+}++/**+ * Terminate a research+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The termination response+ */+async function terminateResearch(researchId) {+ return fetchWithErrorHandling(getApiUrl(`research/${researchId}/terminate`), {+ method: 'POST'+ });+}++/**+ * Delete a research+ * @param {number} researchId - The research ID+ * @returns {Promise<Object>} The deletion response+ */+async function deleteResearch(researchId) {+ return fetchWithErrorHandling(getApiUrl(`research/${researchId}/delete`), {+ method: 'DELETE'+ });+}++// Export the API functions+window.api = {+ startResearch,+ getResearchStatus,+ getResearchDetails,+ getResearchLogs,+ getResearchHistory,+ getReport,+ terminateResearch,+ deleteResearch,+ getApiUrl+};\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsnew file mode 100644index 0000000000..7daa24fa39--- /dev/null+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -0,0 +1,261 @@+/**+ * PDF Service+ * Handles generation of PDFs from research results+ */++/**+ * Generate a PDF from the research content+ * @param {string} title - The research title/query+ * @param {string} content - The markdown content of the research+ * @param {Object} metadata - Additional metadata for the PDF+ * @returns {Promise<Blob>} A promise resolving to the generated PDF blob+ */+async function generatePdf(title, content, metadata = {}) {+ // Check if necessary libraries are loaded+ if (typeof jspdf === 'undefined' || typeof html2canvas === 'undefined') {+ throw new Error('PDF generation libraries not loaded');+ }++ // Create a temporary container to render the markdown+ const tempContainer = document.createElement('div');+ tempContainer.style.position = 'absolute';+ tempContainer.style.left = '-9999px';+ tempContainer.style.top = '-9999px';+ tempContainer.style.width = '8.5in'; // US Letter width+ tempContainer.className = 'pdf-content';++ // Add PDF-specific styles+ tempContainer.innerHTML = `+ <style>+ .pdf-content {+ font-family: Arial, sans-serif;+ color: #333;+ line-height: 1.5;+ padding: 20px;+ }+ .pdf-content h1 {+ font-size: 24px;+ color: #000;+ margin-bottom: 12px;+ }+ .pdf-content h2 {+ font-size: 20px;+ color: #000;+ margin-top: 20px;+ margin-bottom: 10px;+ }+ .pdf-content h3 {+ font-size: 16px;+ color: #000;+ margin-top: 16px;+ margin-bottom: 8px;+ }+ .pdf-content p {+ margin-bottom: 10px;+ }+ .pdf-content ul, .pdf-content ol {+ margin-left: 20px;+ margin-bottom: 10px;+ }+ .pdf-content li {+ margin-bottom: 5px;+ }+ .pdf-content pre {+ background-color: #f5f5f5;+ padding: 10px;+ border-radius: 4px;+ overflow-x: auto;+ font-family: monospace;+ font-size: 12px;+ margin-bottom: 10px;+ }+ .pdf-content code {+ font-family: monospace;+ background-color: #f5f5f5;+ padding: 2px 4px;+ border-radius: 2px;+ font-size: 12px;+ }+ .pdf-content blockquote {+ border-left: 4px solid #ddd;+ padding-left: 15px;+ margin-left: 0;+ color: #666;+ }+ .pdf-content table {+ border-collapse: collapse;+ width: 100%;+ margin-bottom: 15px;+ }+ .pdf-content table, .pdf-content th, .pdf-content td {+ border: 1px solid #ddd;+ }+ .pdf-content th, .pdf-content td {+ padding: 8px;+ text-align: left;+ }+ .pdf-content th {+ background-color: #f5f5f5;+ }+ .pdf-metadata {+ color: #666;+ font-size: 12px;+ margin-bottom: 20px;+ border-bottom: 1px solid #ddd;+ padding-bottom: 10px;+ }+ .pdf-header {+ text-align: center;+ border-bottom: 2px solid #333;+ padding-bottom: 10px;+ margin-bottom: 20px;+ }+ .pdf-footer {+ border-top: 1px solid #ddd;+ padding-top: 10px;+ margin-top: 20px;+ font-size: 12px;+ color: #666;+ }+ </style>+ <div class="pdf-header">+ <h1>${title}</h1>+ </div>+ <div class="pdf-metadata">+ <p>Generated: ${new Date().toLocaleString()}</p>+ ${metadata.mode ? `<p>Mode: ${metadata.mode}</p>` : ''}+ ${metadata.iterations ? `<p>Search iterations: ${metadata.iterations}</p>` : ''}+ </div>+ <div class="pdf-body">+ ${window.marked ? window.marked.parse(content) : content}+ </div>+ <div class="pdf-footer">+ <p>Generated by Deep Research System</p>+ </div>+ `;++ // Add to the document body temporarily+ document.body.appendChild(tempContainer);++ try {+ // Create a new PDF document+ const pdf = new jspdf.jsPDF({+ orientation: 'portrait',+ unit: 'pt',+ format: 'letter'+ });++ // Function to add page with header+ const addPageWithHeader = (pageNum, totalPages) => {+ pdf.setFont('helvetica', 'normal');+ pdf.setFontSize(8);+ pdf.setTextColor(100, 100, 100);+ pdf.text(`Page ${pageNum} of ${totalPages || '?'}`, 40, 20);+ pdf.text(`Generated: ${new Date().toLocaleString()}`, 450, 20, { align: 'right' });+ };++ // Convert each page to image and add to PDF+ // Get the computed width and height+ const width = tempContainer.offsetWidth;+ const height = tempContainer.offsetHeight;++ // Calculate how many pages we need+ const pdfWidth = pdf.internal.pageSize.getWidth();+ const pdfHeight = pdf.internal.pageSize.getHeight() - 40; // Account for margins+ const totalPages = Math.ceil(height / pdfHeight);++ // Convert to canvas in chunks for each page+ for (let i = 0; i < totalPages; i++) {+ // If not the first page, add a new page+ if (i > 0) {+ pdf.addPage();+ }++ // Add header to each page+ addPageWithHeader(i + 1, totalPages);++ // Setup the page+ const yPosition = i * pdfHeight;++ // Create canvas with the specific part of the content+ const canvas = await html2canvas(tempContainer, {+ y: yPosition,+ height: Math.min(pdfHeight, height - yPosition),+ windowHeight: Math.min(pdfHeight, height - yPosition) + 100,+ scale: 1.5 // Higher quality+ });++ // Add to PDF+ const imgData = canvas.toDataURL('image/png');+ pdf.addImage(imgData, 'PNG', 30, 30, pdfWidth - 60, 0);+ }++ // Generate the PDF blob+ const blob = pdf.output('blob');+ return blob;+ } finally {+ // Clean up+ document.body.removeChild(tempContainer);+ }+}++/**+ * Generate and download a PDF from research content+ * @param {string} title - The research title/query+ * @param {string} content - The markdown content of the research+ * @param {Object} metadata - Additional metadata for the PDF+ * @returns {Promise<void>} A promise that resolves when the PDF has been downloaded+ */+async function downloadPdf(title, content, metadata = {}) {+ try {+ // Show loading indicator+ const loadingIndicator = document.createElement('div');+ loadingIndicator.className = 'loading-indicator';+ loadingIndicator.innerHTML = '<div class="spinner"></div><div>Generating PDF...</div>';+ loadingIndicator.style.position = 'fixed';+ loadingIndicator.style.top = '50%';+ loadingIndicator.style.left = '50%';+ loadingIndicator.style.transform = 'translate(-50%, -50%)';+ loadingIndicator.style.zIndex = '9999';+ loadingIndicator.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';+ loadingIndicator.style.color = 'white';+ loadingIndicator.style.padding = '20px';+ loadingIndicator.style.borderRadius = '5px';+ document.body.appendChild(loadingIndicator);++ // Generate the PDF+ const blob = await generatePdf(title, content, metadata);++ // Create a download link+ const url = URL.createObjectURL(blob);+ const downloadLink = document.createElement('a');+ downloadLink.href = url;++ // Generate a filename based on the title+ const safeTitle = title.replace(/[^a-z0-9]/gi, '_').toLowerCase();+ downloadLink.download = `${safeTitle}_research.pdf`;++ // Trigger the download+ document.body.appendChild(downloadLink);+ downloadLink.click();++ // Clean up+ document.body.removeChild(downloadLink);+ URL.revokeObjectURL(url);+ } catch (error) {+ console.error('Error generating PDF:', error);+ alert('Error generating PDF: ' + error.message);+ } finally {+ // Remove loading indicator+ const loadingIndicator = document.querySelector('.loading-indicator');+ if (loadingIndicator) {+ document.body.removeChild(loadingIndicator);+ }+ }+}++// Export PDF functions+window.pdfService = {+ generatePdf,+ downloadPdf+};\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsnew file mode 100644index 0000000000..73d0c30855--- /dev/null+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -0,0 +1,177 @@+/**+ * Socket Service+ * Manages WebSocket communication using Socket.IO+ */++// Socket.IO instance+let socket = null;++// Map of event handlers for each research ID+const researchEventHandlers = new Map();++/**+ * Initialize the Socket.IO connection+ * @returns {Object} The socket instance+ */+function initializeSocket() {+ // Check if Socket.IO library is available+ if (typeof io === 'undefined') {+ console.error('Socket.IO library not loaded');+ return null;+ }++ // Initialize Socket.IO with the research namespace+ try {+ socket = io({+ path: '/research/socket.io'+ });++ // Setup core socket event handlers+ setupSocketEvents();++ console.log('Socket.IO initialized');+ return socket;+ } catch (err) {+ console.error('Error initializing Socket.IO:', err);+ return null;+ }+}++/**+ * Setup core Socket.IO event handlers+ */+function setupSocketEvents() {+ if (!socket) return;++ socket.on('connect', () => {+ console.log('Socket connected, ID:', socket.id);++ // Reconnect any active research subscriptions+ researchEventHandlers.forEach((handlers, researchId) => {+ subscribeToResearch(researchId);+ });+ });++ socket.on('disconnect', (reason) => {+ console.log('Socket disconnected:', reason);+ });++ socket.on('error', (error) => {+ console.error('Socket error:', error);+ });++ socket.on('connect_error', (error) => {+ console.error('Socket connection error:', error);+ });+}++/**+ * Subscribe to events for a specific research ID+ * @param {number} researchId - The research ID to subscribe to+ */+function subscribeToResearch(researchId) {+ if (!socket) {+ initializeSocket();+ }++ if (!socket || !researchId) return;++ // Create a unique event name for this research+ const eventName = `research_progress_${researchId}`;++ // Subscribe to this research on the server+ socket.emit('subscribe_to_research', { research_id: researchId });++ console.log(`Subscribed to research ${researchId}`);+}++/**+ * Add an event handler for a specific research+ * @param {number} researchId - The research ID+ * @param {Function} callback - The event handler function+ */+function addResearchEventHandler(researchId, callback) {+ if (!socket) {+ initializeSocket();+ }++ if (!socket || !researchId || !callback) return;++ // Create a unique event name for this research+ const eventName = `research_progress_${researchId}`;++ // Remove any existing handler+ removeResearchEventHandler(researchId);++ // Add the handler+ socket.on(eventName, callback);++ // Store the handler reference+ if (!researchEventHandlers.has(researchId)) {+ researchEventHandlers.set(researchId, new Set());+ }+ researchEventHandlers.get(researchId).add(callback);++ // Subscribe to the research+ subscribeToResearch(researchId);+}++/**+ * Remove an event handler for a specific research+ * @param {number} researchId - The research ID+ * @param {Function} callback - Optional specific callback to remove+ */+function removeResearchEventHandler(researchId, callback) {+ if (!socket || !researchId) return;++ // Create a unique event name for this research+ const eventName = `research_progress_${researchId}`;++ if (callback) {+ // Remove specific callback+ socket.off(eventName, callback);++ // Remove from our registry+ const handlers = researchEventHandlers.get(researchId);+ if (handlers) {+ handlers.delete(callback);+ if (handlers.size === 0) {+ researchEventHandlers.delete(researchId);+ }+ }+ } else {+ // Remove all callbacks for this research+ socket.off(eventName);++ // Remove from our registry+ researchEventHandlers.delete(researchId);+ }+}++/**+ * Disconnect and cleanup all socket events+ */+function disconnectSocket() {+ if (!socket) return;++ // Remove all event handlers+ researchEventHandlers.forEach((handlers, researchId) => {+ removeResearchEventHandler(researchId);+ });++ // Disconnect the socket+ socket.disconnect();+ socket = null;++ console.log('Socket disconnected and cleaned up');+}++// Export the socket service functions+window.socketService = {+ initializeSocket,+ subscribeToResearch,+ addResearchEventHandler,+ removeResearchEventHandler,+ disconnectSocket,+ getSocket: () => socket+};\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/utils/formatting.js b/src/local_deep_research/web/static/js/utils/formatting.jsnew file mode 100644index 0000000000..7f27fea49f--- /dev/null+++ b/src/local_deep_research/web/static/js/utils/formatting.js@@ -0,0 +1,87 @@+/**+ * Utility functions for formatting data+ */++/**+ * Format a status string to be more user-friendly+ * @param {string} status - The status string+ * @returns {string} The formatted status string+ */+function formatStatus(status) {+ switch(status) {+ case 'in_progress': return 'In Progress';+ case 'completed': return 'Completed';+ case 'failed': return 'Failed';+ case 'suspended': return 'Suspended';+ default: return status.charAt(0).toUpperCase() + status.slice(1);+ }+}++/**+ * Format a research mode string to be more user-friendly+ * @param {string} mode - The mode string+ * @returns {string} The formatted mode string+ */+function formatMode(mode) {+ switch(mode) {+ case 'quick': return 'Quick Summary';+ case 'detailed': return 'Detailed Report';+ default: return mode.charAt(0).toUpperCase() + mode.slice(1);+ }+}++/**+ * Format a date string with optional duration+ * @param {string} date - The date string in ISO format+ * @param {number|null} duration - Optional duration in seconds+ * @returns {string} The formatted date string+ */+function formatDate(date, duration = null) {+ if (!date) return 'Unknown';++ try {+ const dateObj = new Date(date);+ const options = {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit'+ };++ let formattedDate = dateObj.toLocaleDateString('en-US', options);++ if (duration) {+ // Format the duration+ const minutes = Math.floor(duration / 60);+ const seconds = duration % 60;++ if (minutes > 0) {+ formattedDate += ` (${minutes}m ${seconds}s)`;+ } else {+ formattedDate += ` (${seconds}s)`;+ }+ }++ return formattedDate;+ } catch (e) {+ console.error('Error formatting date:', e);+ return date; // Return the original date if there's an error+ }+}++/**+ * Capitalize the first letter of a string+ * @param {string} string - The string to capitalize+ * @returns {string} The capitalized string+ */+function capitalizeFirstLetter(string) {+ if (!string) return '';+ return string.charAt(0).toUpperCase() + string.slice(1);+}++// Export the functions to make them available to other modules+window.formatStatus = formatStatus;+window.formatMode = formatMode;+window.formatDate = formatDate;+window.capitalizeFirstLetter = capitalizeFirstLetter;\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/utils/ui.js b/src/local_deep_research/web/static/js/utils/ui.jsnew file mode 100644index 0000000000..74007e5098--- /dev/null+++ b/src/local_deep_research/web/static/js/utils/ui.js@@ -0,0 +1,153 @@+/**+ * UI utility functions+ */++/**+ * Update a progress bar UI element+ * @param {string} fillElementId - The ID of the element to fill+ * @param {string} percentageElementId - The ID of the element to show percentage+ * @param {number} percentage - The percentage to set+ */+function updateProgressBar(fillElementId, percentageElementId, percentage) {+ const progressFill = document.getElementById(fillElementId);+ const progressPercentage = document.getElementById(percentageElementId);++ if (progressFill && progressPercentage) {+ // Convert any value to a percentage between 0-100+ const safePercentage = Math.min(100, Math.max(0, percentage || 0));++ // Update the width of the fill element+ progressFill.style.width = `${safePercentage}%`;++ // Update the percentage text+ progressPercentage.textContent = `${Math.round(safePercentage)}%`;++ // Add classes for visual feedback+ if (safePercentage >= 100) {+ progressFill.classList.add('complete');+ } else {+ progressFill.classList.remove('complete');+ }+ }+}++/**+ * Show a loading spinner+ * @param {string} containerId - The ID of the container to add the spinner to+ * @param {string} message - Optional message to show with the spinner+ */+function showSpinner(containerId, message = 'Loading...') {+ const container = document.getElementById(containerId);+ if (container) {+ container.innerHTML = '';++ const spinnerHTML = `+ <div class="loading-spinner centered">+ <div class="spinner"></div>+ ${message ? `<div class="spinner-message">${message}</div>` : ''}+ </div>+ `;++ container.innerHTML = spinnerHTML;+ }+}++/**+ * Hide a loading spinner+ * @param {string} containerId - The ID of the container with the spinner+ */+function hideSpinner(containerId) {+ const container = document.getElementById(containerId);+ if (container) {+ const spinner = container.querySelector('.loading-spinner');+ if (spinner) {+ spinner.remove();+ }+ }+}++/**+ * Show an error message+ * @param {string} containerId - The ID of the container to add the error to+ * @param {string} message - The error message+ */+function showError(containerId, message) {+ const container = document.getElementById(containerId);+ if (container) {+ const errorHTML = `+ <div class="error-message">+ <i class="fas fa-exclamation-circle"></i>+ <span>${message}</span>+ </div>+ `;++ container.innerHTML = errorHTML;+ }+}++/**+ * Format and render Markdown content+ * @param {string} containerId - The ID of the container to render markdown into+ * @param {string} markdown - The markdown content+ */+function renderMarkdown(containerId, markdown) {+ const container = document.getElementById(containerId);+ if (container && window.marked) {+ // Add a wrapper for proper styling+ container.innerHTML = `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;++ // Highlight code blocks if highlight.js is available+ if (window.hljs) {+ container.querySelectorAll('pre code').forEach((block) => {+ window.hljs.highlightBlock(block);+ });+ }+ }+}++/**+ * Create a dynamic favicon+ * @param {string} emoji - The emoji to use for the favicon+ */+function createDynamicFavicon(emoji = '⚡') {+ // Create a canvas element+ const canvas = document.createElement('canvas');+ canvas.width = 64;+ canvas.height = 64;++ // Get the 2D drawing context+ const ctx = canvas.getContext('2d');++ // Clear the canvas+ ctx.clearRect(0, 0, canvas.width, canvas.height);++ // Set font+ ctx.font = '48px Arial';+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';++ // Draw the emoji+ ctx.fillText(emoji, 32, 32);++ // Convert to data URL+ const dataUrl = canvas.toDataURL('image/png');++ // Create or update the favicon link+ let link = document.querySelector('link[rel="icon"]');+ if (!link) {+ link = document.createElement('link');+ link.rel = 'icon';+ document.head.appendChild(link);+ }++ // Set the new favicon+ link.href = dataUrl;+}++// Export the functions to make them available to other modules+window.updateProgressBar = updateProgressBar;+window.showSpinner = showSpinner;+window.hideSpinner = hideSpinner;+window.showError = showError;+window.renderMarkdown = renderMarkdown;+window.createDynamicFavicon = createDynamicFavicon;\ No newline at end of filediff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlnew file mode 100644index 0000000000..9c12f2b859--- /dev/null+++ b/src/local_deep_research/web/templates/base.html@@ -0,0 +1,67 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>{% block title %}Deep Research System{% endblock %}</title>+ <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">+ {% block extra_head %}{% endblock %}+</head>+<body>+ <div class="app-container">+ <!-- Sidebar -->+ {% include 'components/sidebar.html' %}++ <!-- Main Content -->+ <main class="main-content">+ {% block content %}{% endblock %}++ <!-- Collapsible Log Panel -->+ {% include 'components/log_panel.html' %}+ </main>+ </div>++ <!-- Mobile Tab Bar -->+ {% include 'components/mobile_nav.html' %}++ <!-- Common Templates -->+ {% block templates %}{% endblock %}++ <!-- Scripts -->+ <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>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>+ <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>++ <!-- Core JS -->+ <script src="{{ url_for('research.serve_static', path='js/utils/formatting.js') }}"></script>+ <script src="{{ url_for('research.serve_static', path='js/utils/ui.js') }}"></script>+ <script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script>+ <script src="{{ url_for('research.serve_static', path='js/services/socket.js') }}"></script>++ <!-- Component JS -->+ {% block component_scripts %}{% endblock %}++ <!-- Page-specific JS -->+ {% block page_scripts %}{% endblock %}++ <script>+ // 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') {+ window.html2canvas_noSandbox = true;+ }+ </script>+</body>+</html>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/components/log_panel.html b/src/local_deep_research/web/templates/components/log_panel.htmlnew file mode 100644index 0000000000..4495597116--- /dev/null+++ b/src/local_deep_research/web/templates/components/log_panel.html@@ -0,0 +1,32 @@+<div class="collapsible-log-panel">+ <div class="log-panel-header" id="log-panel-toggle">+ <i class="fas fa-chevron-down toggle-icon"></i>+ <span>Research Logs</span>+ <span class="log-indicator" id="log-indicator">0</span>+ </div>+ <div class="log-panel-content" id="log-panel-content">+ <div class="log-controls">+ <div class="log-filter">+ <div class="filter-buttons">+ <button class="small-btn selected" onclick="window.filterLogsByType('all')">All</button>+ <button class="small-btn" onclick="window.filterLogsByType('milestone')">Milestones</button>+ <button class="small-btn" onclick="window.filterLogsByType('info')">Info</button>+ <button class="small-btn" onclick="window.filterLogsByType('error')">Errors</button>+ </div>+ </div>+ </div>+ <div class="console-log" id="console-log-container">+ <!-- Logs will be added here dynamically -->+ <div class="empty-log-message">No logs yet. Research logs will appear here as they occur.</div>+ </div>+ </div>+</div>++<!-- Template for console log entries -->+<template id="console-log-entry-template">+ <div class="console-log-entry">+ <span class="log-timestamp"></span>+ <span class="log-badge"></span>+ <span class="log-message"></span>+ </div>+</template>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/components/mobile_nav.html b/src/local_deep_research/web/templates/components/mobile_nav.htmlnew file mode 100644index 0000000000..1f219f3abd--- /dev/null+++ b/src/local_deep_research/web/templates/components/mobile_nav.html@@ -0,0 +1,18 @@+<nav class="mobile-tab-bar">+ <ul>+ <li {% if active_page == 'new-research' %}class="active"{% endif %} data-page="new-research">+ <i class="fas fa-search"></i>+ <span>Research</span>+ </li>+ <li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">+ <i class="fas fa-history"></i>+ <span>History</span>+ </li>+ <li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">+ <a href="{{ url_for('research.settings_page') }}">+ <i class="fas fa-cog"></i>+ <span>Settings</span>+ </a>+ </li>+ </ul>+</nav>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.htmlnew file mode 100644index 0000000000..690fb06517--- /dev/null+++ b/src/local_deep_research/web/templates/components/sidebar.html@@ -0,0 +1,21 @@+<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 {% if active_page == 'new-research' %}class="active"{% endif %} data-page="new-research">+ <i class="fas fa-search"></i> New Research+ </li>+ <li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">+ <i class="fas fa-history"></i> History+ </li>+ <li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">+ <i class="fas fa-cog"></i> <a href="{{ url_for('research.settings_page') }}">Settings</a>+ </li>+ </ul>+ </nav>+ <div class="sidebar-footer">+ <p>v0.1.0 | <i class="fas fa-brain"></i></p>+ </div>+</aside>\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/details.html b/src/local_deep_research/web/templates/pages/details.htmlnew file mode 100644index 0000000000..a53fc9e838--- /dev/null+++ b/src/local_deep_research/web/templates/pages/details.html@@ -0,0 +1,73 @@+{% extends "base.html" %}++{% block title %}Research Details - Deep Research System{% endblock %}++{% block content %}+<div class="page active" 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>+{% endblock %}++{% block templates %}+<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>+{% endblock %}++{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/details.js') }}"></script>+{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.htmlnew file mode 100644index 0000000000..bdd23a2524--- /dev/null+++ b/src/local_deep_research/web/templates/pages/history.html@@ -0,0 +1,47 @@+{% extends "base.html" %}++{% set active_page = 'history' %}++{% block title %}Research History - Deep Research System{% endblock %}++{% block content %}+<div class="page active" 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>+{% endblock %}++{% block 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>+{% endblock %}++{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/history.js') }}"></script>+{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/progress.html b/src/local_deep_research/web/templates/pages/progress.htmlnew file mode 100644index 0000000000..0eb4f4281c--- /dev/null+++ b/src/local_deep_research/web/templates/pages/progress.html@@ -0,0 +1,59 @@+{% extends "base.html" %}++{% block title %}Research in Progress - Deep Research System{% endblock %}++{% block content %}+<div class="page active" 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 id="error-message" class="error-message" style="display: none;"></div>+ <button id="try-again-btn" class="btn btn-primary" style="display: none; margin-top: 15px;">+ <i class="fas fa-redo"></i> Try Again+ </button>+ </div>+ </div>+ </div>+ </div>+</div>+{% endblock %}++{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/progress.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');+ }+ });+ }+ });+</script>+{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlnew file mode 100644index 0000000000..41171fd868--- /dev/null+++ b/src/local_deep_research/web/templates/pages/research.html@@ -0,0 +1,57 @@+{% extends "base.html" %}++{% set active_page = 'new-research' %}++{% block title %}New Research - Deep Research System{% endblock %}++{% block content %}+<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-options">+ <div class="form-option">+ <label for="notification-toggle" class="checkbox-label">+ <input type="checkbox" id="notification-toggle" checked>+ <span class="checkbox-text">Sound notifications when complete</span>+ </label>+ </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>+{% endblock %}++{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/components/research.js') }}"></script>+{% endblock %}\ No newline at end of filediff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.htmlnew file mode 100644index 0000000000..fe99e95082--- /dev/null+++ b/src/local_deep_research/web/templates/pages/results.html@@ -0,0 +1,46 @@+{% extends "base.html" %}++{% block title %}Research Results - Deep Research System{% endblock %}++{% block content %}+<div class="page active" 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>+{% endblock %}++{% block page_scripts %}+<script src="{{ url_for('research.serve_static', path='js/services/pdf.js') }}"></script>+<script src="{{ url_for('research.serve_static', path='js/components/results.js') }}"></script>+{% endblock %}\ No newline at end of file