Skip to content

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

Merge branch 'main' of https://github.com/HashedViking/local-deep-research

hashedviking9d84a60e07ea
diff --cc app.py
index d7a9aa7f61,d7a9aa7f61..61f911145e
--- a/app.py
+++ b/app.py
@@@ -275,12 -275,12 +275,39 @@@ def start_research()
if not query:
return jsonify({'status': 'error', 'message': 'Query is required'}), 400
-- # Check if there's any active research
++ # Check if there's any active research that's actually still running
if active_research:
-- return jsonify({
-- 'status': 'error',
-- 'message': 'Another research is already in progress. Please wait for it to complete.'
-- }), 409
++ # 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()
@@@ -422,6 -422,6 +449,7 @@@ def handle_disconnect()
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}")
@@@ -429,23 -429,23 +457,54 @@@
def handle_subscribe(data):
research_id = data.get('research_id')
if research_id:
-- if research_id not in socket_subscriptions:
-- socket_subscriptions[research_id] = set()
-- socket_subscriptions[research_id].add(request.sid)
-- print(f"Client {request.sid} subscribed to research {research_id}")
++ # 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()
-- # 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
++ # Only allow subscription to valid research
++ if result:
++ status = result[0]
-- if latest_log:
++ # 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': progress,
-- 'message': latest_log.get('message', 'Processing...'),
-- 'status': 'in_progress',
-- 'log_entry': latest_log
++ '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'})
@socketio.on_error
def handle_socket_error(e):
@@@ -459,6 -459,6 +518,47 @@@ def handle_default_error(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}")
++
++ # 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 completed status
++ if research_id in socket_subscriptions and socket_subscriptions[research_id]:
++ final_message = {
++ 'status': 'completed',
++ 'message': 'Research process has ended and resources have been cleaned up',
++ 'progress': 100,
++ }
++
++ try:
++ print(f"Sending final completion 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):
try:
system = AdvancedSearchSystem()
@@@ -466,10 -466,10 +566,36 @@@
# Set up progress callback
def progress_callback(message, progress_percent, metadata):
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": progress_percent,
++ "progress": adjusted_progress,
"metadata": metadata
}
@@@ -481,11 -481,11 +607,11 @@@
# Update active research record
if research_id in active_research:
active_research[research_id]['log'].append(log_entry)
-- if progress_percent is not None:
-- active_research[research_id]['progress'] = progress_percent
++ if adjusted_progress is not None:
++ active_research[research_id]['progress'] = adjusted_progress
# Save to database (but not too frequently)
-- if progress_percent is None or progress_percent % 10 == 0 or metadata.get('phase') in ['complete', 'iteration_complete']:
++ if adjusted_progress is None or adjusted_progress % 10 == 0 or metadata.get('phase') in ['complete', 'iteration_complete', 'output_generation', 'report_generation', 'report_complete']:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
@@@ -509,7 -509,7 +635,7 @@@
# Emit socket event with try/except block to handle connection issues
try:
event_data = {
-- 'progress': progress_percent,
++ 'progress': adjusted_progress,
'message': message,
'status': 'in_progress',
'log_entry': log_entry
@@@ -533,14 -533,14 +659,44 @@@
except Exception as socket_error:
# Log socket error but continue with the research process
print(f"Socket emit error (non-critical): {str(socket_error)}")
++
++ return not (research_id in termination_flags and termination_flags[research_id])
# Set the progress callback in the system
system.set_progress_callback(progress_callback)
# Run the search
progress_callback("Starting research process", 5, {"phase": "init"})
-- results = system.analyze_topic(query)
-- progress_callback("Search complete, generating output", 80, {"phase": "output_generation"})
++
++ 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':
@@@ -548,56 -548,56 +704,92 @@@
if results.get('findings'):
#initial_analysis = [finding['content'] for finding in results['findings']]
summary = ""
-- raw_formatted_findings = results['formatted_findings']
--
-- # ADDED CODE: Convert debug output to clean markdown
-- clean_markdown = convert_debug_to_markdown(raw_formatted_findings, query)
--
-- # Save as markdown file
-- output_dir = "research_outputs"
-- if not os.path.exists(output_dir):
-- os.makedirs(output_dir)
--
-- safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[:50]
-- safe_query = safe_query.replace(" ", "_").lower()
-- report_path = os.path.join(output_dir, f"quick_summary_{safe_query}.md")
--
-- with open(report_path, "w", encoding="utf-8") as f:
-- f.write("# Quick Research Summary\n\n")
-- f.write(f"Query: {query}\n\n")
-- f.write(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()
-- }
++ # Safer access to formatted_findings with logging
++ print(f"Results keys: {list(results.keys())}")
-- # Calculate duration in seconds - using UTC consistently
-- now = datetime.utcnow()
-- completed_at = now.isoformat()
++ # Check if formatted_findings exists in results
++ if 'formatted_findings' not in results:
++ print("WARNING: 'formatted_findings' not found in results, using fallback")
++ # Create fallback formatted findings from available data
++ raw_formatted_findings = "# Research Findings\n\n"
++ for i, finding in enumerate(results.get('findings', [])):
++ raw_formatted_findings += f"## Finding {i+1}\n\n{finding.get('content', '')}\n\n"
++ else:
++ raw_formatted_findings = results['formatted_findings']
++ print(f"Found formatted_findings of length: {len(str(raw_formatted_findings))}")
-- # Get the start time from the database
-- conn = sqlite3.connect(DB_PATH)
-- cursor = conn.cursor()
-- cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))
-- result = cursor.fetchone()
--
-- # Use the helper function for consistent duration calculation
-- duration_seconds = calculate_duration(result[0])
--
-- # Update the record
-- cursor.execute(
-- 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?',
-- ('completed', completed_at, duration_seconds, report_path, json.dumps(metadata), research_id)
-- )
-- conn.commit()
-- conn.close()
--
-- progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})
++ try:
++ # 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"})
@@@ -643,23 -643,23 +835,47 @@@
progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})
-- # Clean up
-- if research_id in active_research:
-- del active_research[research_id]
++ # 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:
-- progress_callback(error_message, None, {"phase": "error", "error": str(e)})
++ # 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 str(e)
++ 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()
@@@ -676,7 -676,7 +892,7 @@@
cursor.execute(
'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, metadata = ? WHERE id = ?',
-- (status, completed_at, duration_seconds, json.dumps({'error': message}), research_id)
++ (status, completed_at, duration_seconds, json.dumps(metadata), research_id)
)
conn.commit()
conn.close()
@@@ -704,11 -704,11 +920,8 @@@
except Exception as inner_e:
print(f"Error in error handler: {str(inner_e)}")
-- # Clean up resources
-- if research_id in active_research:
-- del active_research[research_id]
-- if research_id in termination_flags:
-- del termination_flags[research_id]
++ # Clean up resources - moved to a separate function
++ cleanup_research_resources(research_id)
@research_bp.route('/api/research/<int:research_id>/terminate', methods=['POST'])
def terminate_research(research_id):
@@@ -858,38 -858,38 +1071,62 @@@ def convert_debug_to_markdown(raw_text
Returns:
Clean markdown formatted text
"""
-- # If there's a "DETAILED FINDINGS:" section, extract everything after it
-- if "DETAILED FINDINGS:" in raw_text:
-- detailed_index = raw_text.index("DETAILED FINDINGS:")
-- content = raw_text[detailed_index + len("DETAILED FINDINGS:"):].strip()
-- else:
-- content = raw_text
--
-- # Remove divider lines with === symbols
-- content = "\n".join([line for line in content.split("\n")
-- if not line.strip().startswith("===") and not line.strip() == "="*80])
--
-- # If COMPLETE RESEARCH OUTPUT exists, remove that section
-- if "COMPLETE RESEARCH OUTPUT" in content:
-- content = content.split("COMPLETE RESEARCH OUTPUT")[0].strip()
--
-- # Remove SEARCH QUESTIONS BY ITERATION section
-- if "SEARCH QUESTIONS BY ITERATION:" in content:
-- 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
++ try:
++ print(f"Starting markdown conversion for query: {query}")
++ print(f"Raw text type: {type(raw_text)}")
-- if next_major_section != -1:
-- content = content[:search_index] + content[next_major_section:]
++ # 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:
-- # If no later section, just remove everything from SEARCH QUESTIONS onwards
-- content = content[:search_index].strip()
--
-- return content.strip()
++ 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")
++
++ # If COMPLETE RESEARCH OUTPUT exists, remove that section
++ if "COMPLETE RESEARCH OUTPUT" in content:
++ print("Found and removing COMPLETE RESEARCH OUTPUT section")
++ content = content.split("COMPLETE RESEARCH OUTPUT")[0].strip()
++
++ # 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."
if __name__ == '__main__':
# Check for OpenAI availability but don't import it unless necessary
diff --cc config.py
index 2c043437b0,2c043437b0..8d977bd93e
--- a/config.py
+++ b/config.py
@@@ -49,10 -49,10 +49,12 @@@ from utilties.enums import KnowledgeAcc
import os
import re
from typing import Dict, List, Any, Optional, Callable
++import logging
# Load environment variables
load_dotenv()
# Choose search tool: "serp" or "duckduckgo" (serp requires API key)
++# auto, searxng, duckduckgo, serp, google_pse, guardian, local-all, wikipedia, arxiv
search_tool = "auto" # Change this variable to switch between search tools; for only local search "local-all"
KNOWLEDGE_ACCUMULATION = KnowledgeAccumulationApproach.ITERATION # None doesnt work with detailed report. It basically means the questions are seperate on the topic.
@@@ -244,20 -244,20 +246,67 @@@ def get_search()
# Import here to avoid circular import
from web_search_engines.search_engine_factory import get_search as factory_get_search
-- print(f"Creating search engine with tool: {search_tool}")
-- engine = factory_get_search(
-- search_tool=search_tool,
-- llm_instance=get_llm(),
-- max_results=MAX_SEARCH_RESULTS,
-- region=SEARCH_REGION,
-- time_period=TIME_PERIOD,
-- safe_search=SAFE_SEARCH,
-- search_snippets_only=SEARCH_SNIPPETS_ONLY,
-- search_language=SEARCH_LANGUAGE,
-- max_filtered_results=MAX_FILTERED_RESULTS
-- )
++ logger = logging.getLogger(__name__)
-- if engine is None:
-- print(f"Failed to create search engine with tool: {search_tool}")
--
-- return engine
++ try:
++ print(f"Creating search engine with tool: {search_tool}")
++ engine = factory_get_search(
++ search_tool=search_tool,
++ llm_instance=get_llm(),
++ max_results=MAX_SEARCH_RESULTS,
++ region=SEARCH_REGION,
++ time_period=TIME_PERIOD,
++ safe_search=SAFE_SEARCH,
++ search_snippets_only=SEARCH_SNIPPETS_ONLY,
++ search_language=SEARCH_LANGUAGE,
++ max_filtered_results=MAX_FILTERED_RESULTS
++ )
++
++ if engine is None:
++ logger.error(f"Critical: Failed to create search engine with tool: {search_tool}")
++ print(f"Critical: Failed to create search engine with tool: {search_tool}")
++ # Fall back to a different search engine if available
++ if search_tool == "searxng":
++ print("Attempting fallback to Wikipedia search engine")
++ return factory_get_search(
++ search_tool="wikipedia",
++ llm_instance=get_llm(),
++ max_results=MAX_SEARCH_RESULTS
++ )
++ else:
++ # Verify the engine has a run method
++ if not hasattr(engine, 'run'):
++ logger.error("Created search engine does not have a 'run' method!")
++ print("Created search engine does not have a 'run' method!")
++ return None
++
++ # For SearxNG, specifically check if it's properly configured
++ if search_tool == "searxng" and hasattr(engine, "is_available") and not engine.is_available:
++ logger.error("SearxNG engine is not properly configured (no instance URL)")
++ print("SearxNG engine is not properly configured (no instance URL)")
++ # Fall back to Wikipedia
++ print("Attempting fallback to Wikipedia search engine")
++ return factory_get_search(
++ search_tool="wikipedia",
++ llm_instance=get_llm(),
++ max_results=MAX_SEARCH_RESULTS
++ )
++
++ print(f"Search engine created: {type(engine).__name__}")
++ return engine
++
++ except Exception as e:
++ logger.error(f"Error creating search engine: {str(e)}")
++ print(f"Error creating search engine: {str(e)}")
++ # Fall back to Wikipedia as a last resort
++ try:
++ print("Attempting fallback to Wikipedia search engine due to error")
++ return factory_get_search(
++ search_tool="wikipedia",
++ llm_instance=get_llm(),
++ max_results=MAX_SEARCH_RESULTS
++ )
++ except Exception as fallback_e:
++ logger.error(f"Failed to create fallback search engine: {str(fallback_e)}")
++ print(f"Failed to create fallback search engine: {str(fallback_e)}")
++ return None
diff --cc search_system.py
index a401e85262,a401e85262..ae5c49e315
--- a/search_system.py
+++ b/search_system.py
@@@ -20,6 -20,6 +20,11 @@@ class AdvancedSearchSystem
self.citation_handler = CitationHandler(self.model)
self.progress_callback = None
self.all_links_of_system = list()
++
++ # Check if search is available, log warning if not
++ if self.search is None:
++ print("WARNING: Search system initialized with no search engine! Research will not be effective.")
++ self._update_progress("WARNING: No search engine available", None, {"error": "No search engine configured properly"})
def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:
"""Set a callback function to receive progress updates.
@@@ -103,6 -103,6 +108,23 @@@
"phase": "init",
"iterations_planned": total_iterations
})
++
++ # Check if search engine is available
++ if self.search is None:
++ error_msg = "Error: No search engine available. Please check your configuration."
++ self._update_progress(error_msg, 100, {
++ "phase": "error",
++ "error": "No search engine available",
++ "status": "failed"
++ })
++ return {
++ "findings": [],
++ "iterations": 0,
++ "questions": {},
++ "formatted_findings": "Error: Unable to conduct research without a search engine.",
++ "current_knowledge": "",
++ "error": error_msg
++ }
while iteration < self.max_iterations:
iteration_progress_base = (iteration / total_iterations) * 100
@@@ -122,7 -122,7 +144,21 @@@
int(question_progress_base),
{"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})
-- search_results = self.search.run(question)
++ try:
++ if self.search is None:
++ self._update_progress(f"Search engine unavailable, skipping search for: {question}",
++ int(question_progress_base + 2),
++ {"phase": "search_error", "error": "No search engine available"})
++ search_results = []
++ else:
++ search_results = self.search.run(question)
++ except Exception as e:
++ error_msg = f"Error during search: {str(e)}"
++ print(f"SEARCH ERROR: {error_msg}")
++ self._update_progress(error_msg,
++ int(question_progress_base + 2),
++ {"phase": "search_error", "error": str(e)})
++ search_results = []
if search_results is None:
self._update_progress(f"No search results found for question: {question}",
@@@ -144,40 -144,40 +180,48 @@@
int(question_progress_base + 5),
{"phase": "analysis"})
print("NR OF SOURCES: ", len(self.all_links_of_system))
-- result = self.citation_handler.analyze_followup(
-- question, search_results, current_knowledge, nr_of_links=len(self.all_links_of_system)
-- )
-- links = extract_links_from_search_results(search_results)
-- self.all_links_of_system.extend(links)
-- section_links.extend(links)
-- formatted_links = ""
-- if links:
-- formatted_links=format_links(links=links)
-- if result is not None:
-- results_with_links = str(result["content"])
-- findings.append(
-- {
-- "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
-- "content": results_with_links,
-- "question": question,
-- "search_results": search_results,
-- "documents": result["documents"],
-- }
++
++ try:
++ result = self.citation_handler.analyze_followup(
++ question, search_results, current_knowledge, nr_of_links=len(self.all_links_of_system)
)
++ links = extract_links_from_search_results(search_results)
++ self.all_links_of_system.extend(links)
++ section_links.extend(links)
++ formatted_links = ""
++ if links:
++ formatted_links=format_links(links=links)
++ if result is not None:
++ results_with_links = str(result["content"])
++ findings.append(
++ {
++ "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
++ "content": results_with_links,
++ "question": question,
++ "search_results": search_results,
++ "documents": result["documents"],
++ }
++ )
-- if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
-- current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
--
-- print(current_knowledge)
-- if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.QUESTION:
-- self._update_progress(f"Compress Knowledge for: {question}",
-- int(question_progress_base + 0),
-- {"phase": "analysis"})
-- current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
--
-- self._update_progress(f"Analysis complete for question: {question}",
-- int(question_progress_base + 10),
-- {"phase": "analysis_complete"})
++ if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
++ current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
++
++ print(current_knowledge)
++ if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.QUESTION:
++ self._update_progress(f"Compress Knowledge for: {question}",
++ int(question_progress_base + 0),
++ {"phase": "analysis"})
++ current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
++
++ self._update_progress(f"Analysis complete for question: {question}",
++ int(question_progress_base + 10),
++ {"phase": "analysis_complete"})
++ except Exception as e:
++ error_msg = f"Error analyzing results: {str(e)}"
++ print(f"ANALYSIS ERROR: {error_msg}")
++ self._update_progress(error_msg,
++ int(question_progress_base + 10),
++ {"phase": "analysis_error", "error": str(e)})
iteration += 1
@@@ -185,14 -185,14 +229,29 @@@
int((iteration / total_iterations) * 100 - 5),
{"phase": "knowledge_compression"})
if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.ITERATION:
-- current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
++ try:
++ current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
++ except Exception as e:
++ error_msg = f"Error compressing knowledge: {str(e)}"
++ print(f"COMPRESSION ERROR: {error_msg}")
++ self._update_progress(error_msg,
++ int((iteration / total_iterations) * 100 - 3),
++ {"phase": "compression_error", "error": str(e)})
self._update_progress(f"Iteration {iteration} complete",
int((iteration / total_iterations) * 100),
{"phase": "iteration_complete", "iteration": iteration})
-- formatted_findings = self._save_findings(findings, current_knowledge, query)
++ try:
++ formatted_findings = self._save_findings(findings, current_knowledge, query)
++ except Exception as e:
++ error_msg = f"Error saving findings: {str(e)}"
++ print(f"SAVE ERROR: {error_msg}")
++ self._update_progress(error_msg,
++ int((iteration / total_iterations) * 100),
++ {"phase": "save_error", "error": str(e)})
++ formatted_findings = "Error: Could not format findings due to an error."
self._update_progress("Research complete", 95, {"phase": "complete"})
@@@ -200,7 -200,7 +259,7 @@@
"findings": findings,
"iterations": iteration,
"questions": self.questions_by_iteration,
-- "formatted_findings": formatted_findings,
++ "formatted_findings": formatted_findings if 'formatted_findings' in locals() else "Error: Findings not available.",
"current_knowledge": current_knowledge
}
diff --cc static/css/styles.css
index 218f7898d3,218f7898d3..77a4acbbf0
--- a/static/css/styles.css
+++ b/static/css/styles.css
@@@ -422,8 -422,8 +422,9 @@@ textarea:focus, input[type="text"]:focu
}
.status-in-progress {
-- background-color: rgba(249, 188, 11, 0.15);
-- color: var(--warning-color);
++ background-color: rgba(64, 191, 255, 0.15);
++ color: var(--accent-tertiary);
++ animation: pulse 2s infinite;
}
.status-failed {
@@@ -432,6 -432,6 +433,7 @@@
}
.status-suspended {
++ background-color: rgba(243, 156, 18, 0.15);
color: #f39c12;
}
@@@ -980,4 -980,4 +982,27 @@@
display: flex;
justify-content: center;
margin-top: 1rem;
++}
++
++#try-again-btn {
++ margin-top: 15px;
++ display: flex;
++ align-items: center;
++ justify-content: center;
++ gap: 8px;
++ padding: 8px 16px;
++ background-color: #3498db;
++ color: white;
++ border: none;
++ border-radius: 4px;
++ cursor: pointer;
++ transition: background-color 0.2s;
++}
++
++#try-again-btn:hover {
++ background-color: #2980b9;
++}
++
++#try-again-btn i {
++ margin-right: 5px;
}
diff --cc static/js/app.js
index 5bed9b109e,5bed9b109e..99ed3a3858
--- a/static/js/app.js
+++ b/static/js/app.js
@@@ -17,6 -17,6 +17,24 @@@ document.addEventListener('DOMContentLo
let errorSound = null;
let notificationsEnabled = true;
++ // Add function to cleanup research resources globally
++ window.cleanupResearchResources = function() {
++ console.log('Cleaning up research resources');
++ if (pollingInterval) {
++ clearInterval(pollingInterval);
++ pollingInterval = null;
++ }
++ isResearchInProgress = false;
++ currentResearchId = null;
++ window.currentResearchId = null;
++
++ // Hide the terminate button if it exists
++ const terminateBtn = document.getElementById('terminate-research-btn');
++ if (terminateBtn) {
++ terminateBtn.style.display = 'none';
++ }
++ };
++
// Initialize notification sounds
function initializeSounds() {
successSound = new Audio('/research/static/sounds/success.mp3');
@@@ -47,25 -47,25 +65,46 @@@
// Initialize socket only when needed with a timeout for safety
function initializeSocket() {
-- if (socket) return socket; // Return existing socket if already initialized
++ if (socket) {
++ // If we already have a socket but it's disconnected, reconnect
++ if (!socketConnected) {
++ try {
++ console.log('Socket disconnected, reconnecting...');
++ socket.connect();
++ } catch (e) {
++ console.error('Error reconnecting socket:', e);
++ // Create a new socket
++ socket = null;
++ return initializeSocket();
++ }
++ }
++ return socket;
++ }
console.log('Initializing socket connection...');
// Create new socket connection with optimized settings for threading mode
socket = io({
path: '/research/socket.io',
-- transports: ['websocket', 'polling'],
-- reconnection: true,
-- reconnectionAttempts: 3,
-- reconnectionDelay: 1000,
-- timeout: 5000,
++ transports: ['polling', 'websocket'], // Try polling first, then websocket
++ reconnection: true,
++ reconnectionAttempts: 10,
++ reconnectionDelay: 1000,
++ timeout: 25000, // Increase timeout further
autoConnect: true,
-- forceNew: true
++ forceNew: true,
++ upgrade: false // Disable automatic transport upgrade for more stability
});
// Add event handlers
-- socket.on('connect', () => {
++ socket.on('connect', () => {
console.log('Socket connected');
socketConnected = true;
++
++ // If we're reconnecting and have a current research, resubscribe
++ if (currentResearchId) {
++ console.log(`Reconnected, resubscribing to research ${currentResearchId}`);
++ socket.emit('subscribe_to_research', { research_id: currentResearchId });
++ }
});
socket.on('disconnect', () => {
@@@ -78,18 -78,18 +117,52 @@@
socketConnected = false;
});
++ socket.on('error', (error) => {
++ console.error('Socket error:', error);
++ });
++
// Set a timeout to detect hanging connections
-- setTimeout(() => {
++ let connectionTimeoutId = setTimeout(() => {
if (!socketConnected) {
console.log('Socket connection timeout - forcing reconnect');
try {
-- socket.disconnect();
-- socket.connect();
++ if (socket) {
++ // First try to disconnect cleanly
++ try {
++ socket.disconnect();
++ } catch (disconnectErr) {
++ console.warn('Error disconnecting socket during timeout:', disconnectErr);
++ }
++
++ // Then try to reconnect
++ try {
++ socket.connect();
++ } catch (connectErr) {
++ console.warn('Error reconnecting socket during timeout:', connectErr);
++ // Create a new socket only if connect fails
++ socket = null;
++ socket = initializeSocket();
++ }
++ } else {
++ // Socket is already null, just create a new one
++ socket = initializeSocket();
++ }
} catch (e) {
console.error('Error during forced reconnect:', e);
++ // Force create a new socket
++ socket = null;
++ socket = initializeSocket();
}
}
-- }, 5000);
++ }, 15000); // Longer timeout before forcing reconnection
++
++ // Clean up timeout if socket connects
++ socket.on('connect', () => {
++ if (connectionTimeoutId) {
++ clearTimeout(connectionTimeoutId);
++ connectionTimeoutId = null;
++ }
++ });
return socket;
}
@@@ -99,22 -99,22 +172,50 @@@
try {
if (socket) {
console.log('Manually disconnecting socket');
-- socket.removeAllListeners();
-- socket.disconnect();
++ try {
++ // First remove all listeners
++ socket.removeAllListeners();
++ } catch (listenerErr) {
++ console.warn('Error removing socket listeners:', listenerErr);
++ }
++
++ try {
++ // Then disconnect
++ socket.disconnect();
++ } catch (disconnectErr) {
++ console.warn('Error during socket disconnect:', disconnectErr);
++ }
++
++ // Always set to null to allow garbage collection
socket = null;
socketConnected = false;
}
} catch (e) {
console.error('Error disconnecting socket:', e);
++ // Ensure socket is nullified even if errors occur
++ socket = null;
++ socketConnected = false;
}
};
// Helper function to connect to research updates
window.connectToResearchSocket = function(researchId) {
try {
++ // Check if the research ID is valid
++ if (!researchId) {
++ console.error('Invalid research ID for socket connection');
++ return false;
++ }
++
++ // First disconnect any existing socket to avoid duplicates
++ window.disconnectSocket();
++
// Initialize socket if needed
++ socket = initializeSocket();
++
if (!socket) {
-- socket = initializeSocket();
++ console.error('Failed to initialize socket for research updates');
++ return false;
}
// Subscribe to research updates
@@@ -124,66 -124,66 +225,97 @@@
const progressEventName = `research_progress_${researchId}`;
// Remove existing listeners to prevent duplicates
-- socket.off(progressEventName);
++ try {
++ socket.off(progressEventName);
++ } catch (e) {
++ console.warn(`Error removing existing listeners for ${progressEventName}`, e);
++ }
// Add new listener
socket.on(progressEventName, (data) => {
console.log('Received research progress update:', data);
-- updateProgressUI(data.progress, data.status, data.message);
-- // If research is complete, show the completion buttons
-- if (data.status === 'completed' || data.status === 'terminated' || data.status === 'failed' || data.status === 'suspended') {
-- console.log(`Socket received research final state: ${data.status}`);
++ // Handle different message types
++ if (data.status === 'in_progress') {
++ // Update progress
++ updateProgressUI(data.progress, data.status, data.message);
++ } else if (data.status === 'completed') {
++ // Research completed
++ console.log('Socket received research complete notification');
-- // Clear polling interval if it exists
++ // Clear polling interval
if (pollingInterval) {
console.log('Clearing polling interval from socket event');
clearInterval(pollingInterval);
pollingInterval = null;
}
-- // Update navigation state
-- if (data.status === 'completed') {
-- isResearchInProgress = false;
++ // Load the results
++ loadResearch(researchId);
++
++ // Play notification sound
++ console.log('Playing success notification sound from socket event');
++ playNotificationSound('success');
++
++ // Clean up resources
++ window.cleanupResearchResources();
++
++ // Update navigation and research status display
++ updateNavigationBasedOnResearchStatus();
++
++ // Update history item status if on history page
++ updateHistoryItemStatus(researchId, 'completed');
++
++ // Dispatch event for any other components that need to know about completion
++ document.dispatchEvent(new CustomEvent('research_completed', { detail: data }));
++ } else if (data.status === 'failed' || data.status === 'suspended') {
++ // Research failed or was suspended
++ console.log(`Socket received research final state: ${data.status}`);
++
++ // Clear polling interval
++ if (pollingInterval) {
++ console.log('Clearing polling interval from socket event');
++ clearInterval(pollingInterval);
++ pollingInterval = null;
}
-- // Update UI for completion
-- if (data.status === 'completed') {
-- console.log('Research completed via socket, loading results automatically');
--
-- // Hide terminate button
-- const terminateBtn = document.getElementById('terminate-research-btn');
-- if (terminateBtn) {
-- terminateBtn.style.display = 'none';
-- }
--
-- // Auto-load the results
-- loadResearch(researchId);
-- } else if (data.status === 'failed' || data.status === 'suspended') {
-- console.log(`Showing error message for status: ${data.status} from socket event`);
-- const errorMessage = document.getElementById('error-message');
-- if (errorMessage) {
-- errorMessage.style.display = 'block';
-- errorMessage.textContent = data.status === 'failed' ?
-- (data.metadata && data.metadata.error ? JSON.parse(data.metadata).error : 'Research failed') :
-- 'Research was suspended';
-- } else {
-- console.error('error-message element not found in socket handler');
-- }
++ // Get the error message from the socket response
++ const errorText = data.error || data.message || (data.status === 'failed' ? 'Research failed' : 'Research was suspended');
++ console.log(`Error message from socket: ${errorText}`);
++
++ // Show error message
++ console.log(`Showing error message for status: ${data.status} from socket event`);
++ const errorMessage = document.getElementById('error-message');
++ if (errorMessage) {
++ errorMessage.style.display = 'block';
++ errorMessage.textContent = errorText;
}
++ // Update UI with status
++ updateProgressUI(
++ 0,
++ data.status,
++ errorText
++ );
++
++ // Update history item status if on history page
++ updateHistoryItemStatus(researchId, data.status, errorText);
++
++ // Update navigation
updateNavigationBasedOnResearchStatus();
-- // Play notification sounds based on status
-- if (data.status === 'completed') {
-- console.log('Playing success notification sound from socket event');
-- playNotificationSound('success');
-- } else if (data.status === 'failed') {
++ if (data.status === 'failed') {
console.log('Playing error notification sound from socket event');
playNotificationSound('error');
}
-- // Force the UI to update with a manual trigger
++ // Clean up resources
++ window.cleanupResearchResources();
++
++ // Update navigation and research status display
++ updateNavigationBasedOnResearchStatus();
++
++ // Dispatch event for any other components that need to know about completion
document.dispatchEvent(new CustomEvent('research_completed', { detail: data }));
}
@@@ -210,22 -210,22 +342,62 @@@
const activeResearch = history.find(item => item.status === 'in_progress');
if (activeResearch) {
-- isResearchInProgress = true;
-- currentResearchId = activeResearch.id;
-- window.currentResearchId = currentResearchId;
--
-- // Check if we're on the new research page and redirect to progress
-- const currentPage = document.querySelector('.page.active');
--
-- if (currentPage && currentPage.id === 'new-research') {
-- // Navigate to progress page
-- switchPage('research-progress');
++ // Verify the research is truly active by checking its details
++ try {
++ const detailsResponse = await fetch(getApiUrl(`/api/research/${activeResearch.id}`));
++ const details = await detailsResponse.json();
-- // Connect to socket for this research
-- window.connectToResearchSocket(currentResearchId);
++ // If status is not in_progress in the details, it's stale
++ if (details.status !== 'in_progress') {
++ console.log(`Research ${activeResearch.id} is stale (status: ${details.status}), ignoring`);
++ return;
++ }
-- // Start polling for updates
-- pollResearchStatus(currentResearchId);
++ // Check when the research was started - if it's been more than 1 hour, it might be stale
++ if (details.created_at) {
++ const startTime = new Date(details.created_at);
++ const currentTime = new Date();
++ const hoursSinceStart = (currentTime - startTime) / (1000 * 60 * 60);
++
++ if (hoursSinceStart > 1) {
++ console.log(`Research ${activeResearch.id} has been running for ${hoursSinceStart.toFixed(2)} hours, which is unusually long. Checking for activity...`);
++
++ // Check if there has been log activity in the last 10 minutes
++ let recentActivity = false;
++ if (details.log && Array.isArray(details.log) && details.log.length > 0) {
++ const lastLogTime = new Date(details.log[details.log.length - 1].time);
++ const minutesSinceLastLog = (currentTime - lastLogTime) / (1000 * 60);
++
++ if (minutesSinceLastLog < 10) {
++ recentActivity = true;
++ } else {
++ console.log(`No recent activity for ${minutesSinceLastLog.toFixed(2)} minutes, treating as stale`);
++ return;
++ }
++ }
++ }
++ }
++
++ // If we get here, the research seems to be genuinely active
++ isResearchInProgress = true;
++ currentResearchId = activeResearch.id;
++ window.currentResearchId = currentResearchId;
++
++ // Check if we're on the new research page and redirect to progress
++ const currentPage = document.querySelector('.page.active');
++
++ if (currentPage && currentPage.id === 'new-research') {
++ // Navigate to progress page
++ switchPage('research-progress');
++
++ // Connect to socket for this research
++ window.connectToResearchSocket(currentResearchId);
++
++ // Start polling for updates
++ pollResearchStatus(currentResearchId);
++ }
++ } catch (detailsError) {
++ console.error('Error checking research details:', detailsError);
}
}
} catch (error) {
@@@ -240,10 -240,10 +412,27 @@@
// Function to start research
async function startResearch(query, mode) {
-- // Check if research is already in progress
++ // Reset potentially stale state
if (isResearchInProgress) {
-- alert('Another research is already in progress. Please wait for it to complete or check its status in the history tab.');
-- return;
++ // Force a fresh check of active research status
++ try {
++ const response = await fetch(getApiUrl('/api/history'));
++ const history = await response.json();
++
++ // Find any in-progress research
++ const activeResearch = history.find(item => item.status === 'in_progress');
++
++ // If no active research is found, reset the state
++ if (!activeResearch) {
++ console.log('Resetting stale research state - no active research found in history');
++ window.cleanupResearchResources();
++ } else {
++ alert('Another research is already in progress. Please wait for it to complete or check its status in the history tab.');
++ return;
++ }
++ } catch (error) {
++ console.error('Error checking for active research:', error);
++ }
}
// Get the start button
@@@ -255,6 -255,6 +444,9 @@@
startResearchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
try {
++ // Set the favicon based on research mode
++ setFavicon(mode);
++
const response = await fetch(getApiUrl('/api/start_research'), {
method: 'POST',
headers: {
@@@ -300,11 -300,11 +492,17 @@@
terminateBtn.disabled = false;
}
} else {
++ // Reset favicon to default on error
++ createDynamicFavicon('⚡');
++
alert('Error starting research: ' + (data.message || 'Unknown error'));
startResearchBtn.disabled = false;
startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
}
} catch (error) {
++ // Reset favicon to default on error
++ createDynamicFavicon('⚡');
++
console.error('Error:', error);
alert('An error occurred while starting the research. Please try again.');
startResearchBtn.disabled = false;
@@@ -324,12 -324,12 +522,26 @@@
})
.then(data => {
console.log('Research status response:', data);
-- // Update the UI with the current progress
-- updateProgressUI(data.progress, data.status, data.message);
++
++ // Get the latest progress and log data
++ const progress = data.progress || 0;
++ const status = data.status || 'in_progress';
++
++ // Get the latest message from the log if available
++ let latestMessage = "Processing research...";
++ if (data.log && Array.isArray(data.log) && data.log.length > 0) {
++ const latestLog = data.log[data.log.length - 1];
++ if (latestLog && latestLog.message) {
++ latestMessage = latestLog.message;
++ }
++ }
++
++ // Update the UI with the current progress - always
++ updateProgressUI(progress, status, latestMessage);
// If research is complete, show the completion buttons
-- if (data.status === 'completed' || data.status === 'failed' || data.status === 'suspended') {
-- console.log(`Research is in final state: ${data.status}`);
++ if (status === 'completed' || status === 'failed' || status === 'suspended') {
++ console.log(`Research is in final state: ${status}`);
// Clear the polling interval
if (pollingInterval) {
console.log('Clearing polling interval');
@@@ -338,7 -338,7 +550,7 @@@
}
// Update UI for completion
-- if (data.status === 'completed') {
++ if (status === 'completed') {
console.log('Research completed, loading results automatically');
// Hide the terminate button
const terminateBtn = document.getElementById('terminate-research-btn');
@@@ -346,26 -346,26 +558,49 @@@
terminateBtn.style.display = 'none';
}
++ // Update history item status
++ updateHistoryItemStatus(researchId, 'completed');
++
// Auto-load the results instead of showing a button
loadResearch(researchId);
-- } else if (data.status === 'failed' || data.status === 'suspended') {
-- console.log(`Showing error message for status: ${data.status}`);
++ } else if (status === 'failed' || status === 'suspended') {
++ console.log(`Showing error message for status: ${status}`);
++
++ // Get error message from metadata if available or use latest message
++ let errorText = latestMessage;
++ if (data.metadata && typeof data.metadata === 'string') {
++ try {
++ const metadataObj = JSON.parse(data.metadata);
++ if (metadataObj.error) {
++ errorText = metadataObj.error;
++ }
++ } catch (e) {
++ console.log('Error parsing metadata:', e);
++ }
++ }
++
++ // Show error message in UI
const errorMessage = document.getElementById('error-message');
if (errorMessage) {
errorMessage.style.display = 'block';
-- errorMessage.textContent = data.status === 'failed' ?
-- (data.metadata && data.metadata.error ? JSON.parse(data.metadata).error : 'Research failed') :
-- 'Research was suspended';
++ errorMessage.textContent = errorText;
++ console.log('Set error message to:', errorText);
} else {
console.error('error-message element not found');
}
++
++ // Update progress display with error
++ updateProgressUI(0, status, errorText);
++
++ // Update history item status
++ updateHistoryItemStatus(researchId, status, errorText);
}
// Play notification sound based on status
-- if (data.status === 'completed') {
++ if (status === 'completed') {
console.log('Playing success notification sound');
playNotificationSound('success');
-- } else if (data.status === 'failed') {
++ } else if (status === 'failed') {
console.log('Playing error notification sound');
playNotificationSound('error');
}
@@@ -381,7 -381,7 +616,7 @@@
}
// Continue polling if still in progress
-- if (data.status === 'in_progress') {
++ if (status === 'in_progress') {
console.log('Research is still in progress, continuing polling');
if (!pollingInterval) {
console.log('Setting up polling interval');
@@@ -403,6 -403,6 +638,9 @@@
// Initialize the sounds
initializeSounds();
++ // Create a dynamic favicon with the lightning emoji by default
++ createDynamicFavicon('⚡');
++
// Get navigation elements
const navItems = document.querySelectorAll('.sidebar-nav li');
const mobileNavItems = document.querySelectorAll('.mobile-tab-bar li');
@@@ -474,6 -474,6 +712,10 @@@
option.addEventListener('click', function() {
modeOptions.forEach(opt => opt.classList.remove('active'));
this.classList.add('active');
++
++ // Update favicon based on selected mode
++ const mode = this.dataset.mode;
++ setFavicon(mode);
});
});
@@@ -602,9 -602,9 +844,21 @@@
console.log('Termination request sent successfully');
// If we're on the history page, update the status of this item
-- if (document.getElementById('history').classList.contains('active')) {
++ if (document.getElementById('history').classList.contains('active')) {
updateHistoryItemStatus(researchId, 'terminating', 'Terminating...');
}
++
++ // Set a timeout to reset UI if socket doesn't respond
++ setTimeout(() => {
++ if (isTerminating) {
++ console.log('Termination timeout - resetting UI');
++ isTerminating = false;
++ resetProgressAnimations();
++
++ // Update the navigation
++ updateNavigationBasedOnResearchStatus();
++ }
++ }, 10000); // 10 second timeout
} else {
console.error('Termination request failed:', data.message);
alert(`Failed to terminate research: ${data.message}`);
@@@ -626,8 -626,8 +880,8 @@@
btn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate';
}
});
-- }
-- } catch (error) {
++ }
++ } catch (error) {
console.error('Error terminating research:', error);
alert('An error occurred while trying to terminate the research.');
@@@ -660,6 -660,6 +914,8 @@@
const progressFill = document.getElementById('progress-fill');
const progressPercentage = document.getElementById('progress-percentage');
const progressStatus = document.getElementById('progress-status');
++ const errorMessage = document.getElementById('error-message');
++ const tryAgainBtn = document.getElementById('try-again-btn');
if (progressFill && progressPercentage) {
progressFill.style.width = `${progress}%`;
@@@ -683,12 -683,12 +939,51 @@@
terminateBtn.style.display = 'inline-flex';
terminateBtn.disabled = false;
terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
++
++ // Hide try again button when in progress
++ if (tryAgainBtn) {
++ tryAgainBtn.style.display = 'none';
++ }
} else if (status === 'terminating') {
terminateBtn.style.display = 'inline-flex';
terminateBtn.disabled = true;
terminateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';
} else {
terminateBtn.style.display = 'none';
++
++ // Show try again button for failed or suspended research
++ if (tryAgainBtn && (status === 'failed' || status === 'suspended')) {
++ tryAgainBtn.style.display = 'inline-flex';
++
++ // Get the current query for retry
++ const currentQuery = document.getElementById('current-query');
++ const queryText = currentQuery ? currentQuery.textContent : '';
++
++ // Add click event to try again button to go back to research form with the query preserved
++ tryAgainBtn.onclick = function() {
++ // Switch to the research form
++ switchPage('new-research');
++
++ // Set the query text in the form
++ const queryTextarea = document.getElementById('query');
++ if (queryTextarea && queryText) {
++ queryTextarea.value = queryText;
++ }
++
++ // Clean up any remaining research state
++ window.cleanupResearchResources();
++ };
++ }
++ }
++ }
++
++ // Show error message when there's an error
++ if (errorMessage) {
++ if (status === 'failed' || status === 'suspended') {
++ errorMessage.style.display = 'block';
++ errorMessage.textContent = message || (status === 'failed' ? 'Research failed' : 'Research was suspended');
++ } else {
++ errorMessage.style.display = 'none';
}
}
}
@@@ -764,8 -764,8 +1059,11 @@@
title.textContent = item.query || 'Untitled Research';
const status = document.createElement('div');
-- status.className = `history-item-status status-${item.status || 'unknown'}`;
-- status.textContent = item.status ? (item.status.charAt(0).toUpperCase() + item.status.slice(1)) : 'Unknown';
++ status.className = `history-item-status status-${item.status ? item.status.replace('_', '-') : 'unknown'}`;
++ status.textContent = item.status ?
++ (item.status === 'in_progress' ? 'In Progress' :
++ item.status.charAt(0).toUpperCase() + item.status.slice(1)) :
++ 'Unknown';
header.appendChild(title);
header.appendChild(status);
@@@ -946,145 -946,145 +1244,160 @@@
}
}
-- // Function to load a specific research result
++ // Function to load research
async function loadResearch(researchId) {
-- // Navigate to results page
-- switchPage('research-results');
--
-- const resultsContent = document.getElementById('results-content');
-- resultsContent.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
--
try {
-- // Load research details
-- const detailsResponse = await fetch(getApiUrl(`/api/research/${researchId}`));
-- const details = await detailsResponse.json();
++ const response = await fetch(getApiUrl(`/api/research/${researchId}`));
++ if (!response.ok) {
++ throw new Error('Failed to load research');
++ }
-- // Display metadata
-- document.getElementById('result-query').textContent = details.query;
++ const data = await response.json();
-- // Format date with duration if available
-- let dateText = formatDate(new Date(details.completed_at || details.created_at));
-- if (details.duration_seconds) {
-- // Format duration
-- let durationText = '';
-- const duration = parseInt(details.duration_seconds);
++ if (data.status === 'completed' && data.report_path) {
++ // Set the favicon based on the research mode
++ setFavicon(data.mode || 'quick');
-- if (duration < 60) { // less than a minute
-- durationText = `${duration}s`;
-- } else if (duration < 3600) { // less than an hour
-- durationText = `${Math.floor(duration / 60)}m ${duration % 60}s`;
-- } else { // hours
-- durationText = `${Math.floor(duration / 3600)}h ${Math.floor((duration % 3600) / 60)}m`;
++ // Get report content
++ const reportResponse = await fetch(getApiUrl(`/api/report/${researchId}`));
++ if (!reportResponse.ok) {
++ throw new Error('Failed to load report');
}
-- dateText += ` (Duration: ${durationText})`;
-- }
-- document.getElementById('result-date').textContent = dateText;
--
-- document.getElementById('result-mode').textContent = details.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';
--
-- // Load the report content
-- const reportResponse = await fetch(getApiUrl(`/api/report/${researchId}`));
-- const reportData = await reportResponse.json();
--
-- if (reportData.status === 'success') {
-- // Render markdown
-- const renderedContent = marked.parse(reportData.content);
-- resultsContent.innerHTML = renderedContent;
++ const reportData = await reportResponse.json();
-- // Apply syntax highlighting
-- document.querySelectorAll('pre code').forEach((block) => {
-- hljs.highlightElement(block);
-- });
++ if (reportData.status === 'success') {
++ // Update UI with report content
++ document.getElementById('result-query').textContent = data.query || 'Unknown query';
++ document.getElementById('result-mode').textContent = data.mode === 'detailed' ? 'Detailed Report' : 'Quick Summary';
++
++ // Format date
++ const reportDate = data.completed_at ? formatDate(new Date(data.completed_at)) : 'Unknown';
++ document.getElementById('result-date').textContent = reportDate;
++
++ // Render markdown content
++ const resultsContent = document.getElementById('results-content');
++ if (resultsContent) {
++ resultsContent.innerHTML = '';
++ resultsContent.classList.add('markdown-body');
++
++ // Enable syntax highlighting
++ const renderedContent = marked.parse(reportData.content);
++ resultsContent.innerHTML = renderedContent;
++
++ // Apply syntax highlighting
++ document.querySelectorAll('pre code').forEach((block) => {
++ hljs.highlightElement(block);
++ });
++ }
++
++ // Switch to results page
++ switchPage('research-results');
++ } else {
++ throw new Error(reportData.message || 'Failed to load report content');
++ }
++ } else if (data.status === 'in_progress') {
++ // Set favicon based on the research mode
++ setFavicon(data.mode || 'quick');
++
++ // Redirect to progress page
++ navigateToResearchProgress(data);
} else {
-- resultsContent.innerHTML = '<div class="error-message">Error loading report. Please try again later.</div>';
++ // Show research details for failed or suspended research
++ loadResearchDetails(researchId);
}
} catch (error) {
console.error('Error loading research:', error);
-- resultsContent.innerHTML = '<div class="error-message">Error loading research results. Please try again later.</div>';
++ alert('Error loading research: ' + error.message);
++ // Reset favicon to default on error
++ createDynamicFavicon('⚡');
}
}
-- // Function to load research details page
++ // Function to load research details
async function loadResearchDetails(researchId) {
-- // Navigate to details page
-- switchPage('research-details');
--
-- // Initialize the research log area
-- const researchLog = document.getElementById('research-log');
-- researchLog.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
--
try {
-- // Load research details
-- const response = await fetch(getApiUrl(`/api/research/${researchId}/details`));
-- console.log('Research details API response status:', response.status);
++ // Navigate to details page
++ switchPage('research-details');
++
++ const researchLog = document.getElementById('research-log');
++ researchLog.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
++ const response = await fetch(getApiUrl(`/api/research/${researchId}/details`));
if (!response.ok) {
-- console.error('API error:', response.status, response.statusText);
-- researchLog.innerHTML = `<div class="error-message">Error loading research details. Status: ${response.status}</div>`;
-- return;
++ throw new Error('Failed to load research details');
}
const data = await response.json();
-- console.log('Research details data:', data);
-- if (data.status !== 'success') {
-- researchLog.innerHTML = `<div class="error-message">Error loading research details: ${data.message || 'Unknown error'}</div>`;
-- return;
-- }
++ // Set the favicon based on the research mode
++ setFavicon(data.mode || 'quick');
-- // Display metadata
-- document.getElementById('detail-query').textContent = data.query || 'N/A';
++ // Update UI with research details
++ document.getElementById('detail-query').textContent = data.query || 'Unknown query';
document.getElementById('detail-status').textContent = capitalizeFirstLetter(data.status || 'unknown');
-- document.getElementById('detail-status').className = `metadata-value status-${data.status || 'unknown'}`;
-- document.getElementById('detail-mode').textContent = (data.mode === 'quick' ? 'Quick Summary' : 'Detailed Report') || 'N/A';
++ document.getElementById('detail-mode').textContent = data.mode === 'detailed' ? 'Detailed Report' : 'Quick Summary';
-- // Update progress bar
++ // Update progress indicator
const progress = data.progress || 0;
document.getElementById('detail-progress-fill').style.width = `${progress}%`;
document.getElementById('detail-progress-percentage').textContent = `${progress}%`;
-- // Render log entries
-- renderLogEntries(data.log || []);
++ // Add status classes
++ document.getElementById('detail-status').className = 'metadata-value status-' + (data.status || 'unknown');
-- // Connect to socket for real-time updates
-- window.connectToResearchSocket(researchId);
++ // Clear existing log entries
++ researchLog.innerHTML = '';
++
++ // Render log entries
++ if (data.log && Array.isArray(data.log)) {
++ renderLogEntries(data.log);
++ } else {
++ researchLog.innerHTML = '<div class="empty-message">No log entries available</div>';
++ }
-- // Add appropriate actions based on research status
-- const detailActions = document.getElementById('detail-actions');
-- detailActions.innerHTML = '';
++ // Update actions based on status
++ const actionsContainer = document.getElementById('detail-actions');
++ actionsContainer.innerHTML = '';
-- if (data.status === 'completed') {
++ if (data.status === 'completed' && data.report_path) {
++ // Add button to view results
const viewResultsBtn = document.createElement('button');
viewResultsBtn.className = 'btn btn-primary';
viewResultsBtn.innerHTML = '<i class="fas fa-eye"></i> View Results';
viewResultsBtn.addEventListener('click', () => loadResearch(researchId));
-- detailActions.appendChild(viewResultsBtn);
--
-- // Add download PDF button
-- const downloadPdfBtn = document.createElement('button');
-- downloadPdfBtn.className = 'btn btn-outline';
-- downloadPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';
-- downloadPdfBtn.addEventListener('click', () => generatePdfFromResearch(researchId));
-- detailActions.appendChild(downloadPdfBtn);
++ actionsContainer.appendChild(viewResultsBtn);
} else if (data.status === 'in_progress') {
++ // Add button to view progress
const viewProgressBtn = document.createElement('button');
viewProgressBtn.className = 'btn btn-primary';
-- viewProgressBtn.innerHTML = '<i class="fas fa-sync"></i> View Live Progress';
-- viewProgressBtn.addEventListener('click', () => {
-- document.getElementById('current-query').textContent = data.query || '';
--
-- // Navigate to progress page
-- switchPage('research-progress');
--
-- // Connect to socket
-- window.connectToResearchSocket(researchId);
-- });
-- detailActions.appendChild(viewProgressBtn);
++ viewProgressBtn.innerHTML = '<i class="fas fa-spinner"></i> View Progress';
++ viewProgressBtn.addEventListener('click', () => navigateToResearchProgress(data));
++ actionsContainer.appendChild(viewProgressBtn);
++
++ // Add button to terminate research
++ const terminateBtn = document.createElement('button');
++ terminateBtn.className = 'btn btn-outline terminate-btn';
++ terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
++ terminateBtn.addEventListener('click', () => terminateResearch(researchId));
++ actionsContainer.appendChild(terminateBtn);
}
++
++ // Add delete button for all research items
++ const deleteBtn = document.createElement('button');
++ deleteBtn.className = 'btn btn-outline delete-btn';
++ deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete Research';
++ deleteBtn.addEventListener('click', () => {
++ if (confirm('Are you sure you want to delete this research? This action cannot be undone.')) {
++ deleteResearch(researchId);
++ }
++ });
++ actionsContainer.appendChild(deleteBtn);
} catch (error) {
console.error('Error loading research details:', error);
-- researchLog.innerHTML = `<div class="error-message">Error loading research details: ${error.message}</div>`;
++ document.getElementById('research-log').innerHTML = '<div class="error-message">Error loading research details. Please try again later.</div>';
++ // Reset favicon to default on error
++ createDynamicFavicon('⚡');
}
}
@@@ -1213,15 -1213,15 +1526,13 @@@
researchLog.scrollTop = researchLog.scrollHeight;
}
-- // Back to history button handlers
-- document.getElementById('back-to-history').addEventListener('click', () => {
-- const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');
-- historyNav.click();
++ // Back to history button handlers - using direct page switching
++ document.getElementById('back-to-history')?.addEventListener('click', () => {
++ switchPage('history');
});
-- document.getElementById('back-to-history-from-details').addEventListener('click', () => {
-- const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');
-- historyNav.click();
++ document.getElementById('back-to-history-from-details')?.addEventListener('click', () => {
++ switchPage('history');
});
// Helper functions
@@@ -1323,6 -1323,6 +1634,25 @@@
newResearchNav.removeAttribute('data-original-page');
}
++ // Reset progress UI elements
++ const progressFill = document.getElementById('progress-fill');
++ const progressPercentage = document.getElementById('progress-percentage');
++ const progressStatus = document.getElementById('progress-status');
++
++ if (progressFill) progressFill.style.width = '0%';
++ if (progressPercentage) progressPercentage.textContent = '0%';
++ if (progressStatus) {
++ const errorMessage = document.getElementById('error-message');
++ if (errorMessage && errorMessage.style.display === 'block') {
++ // If there's an error message displayed, show a more informative status
++ progressStatus.textContent = 'Research process encountered an error. Please check the error message above and try again.';
++ progressStatus.classList.add('status-failed');
++ } else {
++ progressStatus.textContent = 'Start a new research query when you\'re ready...';
++ progressStatus.classList.remove('status-failed');
++ }
++ }
++
// If the terminate button is visible, hide it
const terminateBtn = document.getElementById('terminate-research-btn');
if (terminateBtn) {
@@@ -1330,6 -1330,6 +1660,20 @@@
terminateBtn.disabled = false;
terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
}
++
++ // Also hide error message if visible
++ const errorMessage = document.getElementById('error-message');
++ if (errorMessage) {
++ errorMessage.style.display = 'none';
++ errorMessage.textContent = '';
++ }
++
++ // Reset research form submit button
++ const startResearchBtn = document.getElementById('start-research-btn');
++ if (startResearchBtn) {
++ startResearchBtn.disabled = false;
++ startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
++ }
}
// Make sure the navigation highlights the correct item
@@@ -1346,9 -1346,9 +1690,16 @@@
});
}
-- // Connect to socket for updates
-- if (currentResearchId) {
++ // Connect to socket for updates only if research is in progress
++ if (isResearchInProgress && currentResearchId) {
window.connectToResearchSocket(currentResearchId);
++ } else {
++ // Disconnect socket if no active research
++ window.disconnectSocket();
++
++ // Also reset the current research ID
++ currentResearchId = null;
++ window.currentResearchId = null;
}
}
@@@ -1389,14 -1389,14 +1740,22 @@@
function updateHistoryItemStatus(researchId, status, statusText) {
const historyList = document.getElementById('history-list');
++ // Format the status for display
++ const displayStatus = statusText ||
++ (status === 'in_progress' ? 'In Progress' :
++ status.charAt(0).toUpperCase() + status.slice(1));
++
++ // Format the CSS class
++ const statusClass = `status-${status.replace('_', '-')}`;
++
// Look for the item in the active research banner
const activeBanner = historyList.querySelector(`.active-research-banner[data-research-id="${researchId}"]`);
if (activeBanner) {
const statusEl = activeBanner.querySelector('.history-item-status');
if (statusEl) {
-- statusEl.textContent = statusText || capitalizeFirstLetter(status);
++ statusEl.textContent = displayStatus;
statusEl.className = 'history-item-status';
-- statusEl.classList.add(`status-${status}`);
++ statusEl.classList.add(statusClass);
}
// Update buttons
@@@ -1423,9 -1423,9 +1782,9 @@@
if (historyItem) {
const statusEl = historyItem.querySelector('.history-item-status');
if (statusEl) {
-- statusEl.textContent = statusText || capitalizeFirstLetter(status);
++ statusEl.textContent = displayStatus;
statusEl.className = 'history-item-status';
-- statusEl.classList.add(`status-${status}`);
++ statusEl.classList.add(statusClass);
}
// Update view button
@@@ -1437,6 -1437,6 +1796,15 @@@
} else if (status === 'failed') {
viewBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';
viewBtn.disabled = true;
++ } else if (status === 'completed') {
++ viewBtn.innerHTML = '<i class="fas fa-eye"></i> View';
++ viewBtn.disabled = false;
++
++ // Also make the PDF button visible if not already
++ const pdfBtn = historyItem.querySelector('.pdf-btn');
++ if (pdfBtn) {
++ pdfBtn.style.display = 'inline-flex';
++ }
}
}
}
@@@ -2075,4 -2075,4 +2443,79 @@@
// Update navigation
updateNavigationBasedOnResearchStatus();
});
++
++ // Function to reset progress animations and UI elements
++ function resetProgressAnimations() {
++ // Reset the progress bar animation
++ const progressFill = document.getElementById('progress-fill');
++ if (progressFill) {
++ // Force a reflow to reset the animation
++ progressFill.style.display = 'none';
++ progressFill.offsetHeight; // Trigger reflow
++ progressFill.style.display = 'block';
++ }
++
++ // Reset any spinning icons
++ const spinners = document.querySelectorAll('.fa-spinner.fa-spin');
++ spinners.forEach(spinner => {
++ const parent = spinner.parentElement;
++ if (parent && parent.tagName === 'BUTTON') {
++ if (parent.classList.contains('terminate-btn')) {
++ parent.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
++ parent.disabled = false;
++ }
++ }
++ });
++
++ // Ensure the isTerminating flag is reset
++ isTerminating = false;
++ }
++
++ // Create a dynamic favicon
++ function createDynamicFavicon(emoji = '⚡') {
++ console.log(`Creating dynamic favicon with emoji: ${emoji}`);
++
++ // Create a canvas element
++ const canvas = document.createElement('canvas');
++ canvas.width = 32;
++ canvas.height = 32;
++
++ // Get the canvas context
++ const ctx = canvas.getContext('2d');
++
++ // Clear the canvas with a transparent background
++ ctx.clearRect(0, 0, 32, 32);
++
++ // Set the font size and font family
++ ctx.font = '24px Arial';
++ ctx.textAlign = 'center';
++ ctx.textBaseline = 'middle';
++
++ // Draw the emoji in the center of the canvas
++ ctx.fillText(emoji, 16, 16);
++
++ // Convert canvas to favicon URL
++ const faviconUrl = canvas.toDataURL('image/png');
++
++ // Find existing favicon or create a new one
++ let link = document.querySelector('link[rel="icon"]');
++ if (!link) {
++ link = document.createElement('link');
++ link.rel = 'icon';
++ link.id = 'dynamic-favicon';
++ document.head.appendChild(link);
++ }
++
++ // Update the favicon
++ link.type = 'image/x-icon';
++ link.href = faviconUrl;
++
++ return faviconUrl;
++ }
++
++ // Function to set favicon based on research mode
++ function setFavicon(mode) {
++ const emoji = mode === 'detailed' ? '🔬' : '⚡';
++ return createDynamicFavicon(emoji);
++ }
});
diff --cc templates/index.html
index d0f00d43de,d0f00d43de..a758a29c65
--- a/templates/index.html
+++ b/templates/index.html
@@@ -8,7 -8,7 +8,6 @@@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<!-- Change to CDN version that works in browsers -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">
-- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<div class="app-container">
@@@ -118,6 -118,6 +117,9 @@@
<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>
diff --cc web_search_engines/engines/search_engine_searxng.py
index 99111e7c6d,99111e7c6d..7104a2b8a1
--- a/web_search_engines/engines/search_engine_searxng.py
+++ b/web_search_engines/engines/search_engine_searxng.py
@@@ -61,14 -61,14 +61,22 @@@ class SearXNGSearchEngine(BaseSearchEng
# 4. Default to None, which will disable the engine
self.instance_url = api_key or os.getenv("SEARXNG_INSTANCE") or instance_url
++ # Add debug logging for instance URL
++ logger.info(f"SearXNG init - Instance URL sources: api_key={api_key}, env={os.getenv('SEARXNG_INSTANCE')}, param={instance_url}")
++
# Validate and normalize the instance URL if provided
if self.instance_url:
self.instance_url = self.instance_url.rstrip('/')
self.is_available = True
++ logger.info(f"SearXNG initialized with instance URL: {self.instance_url}")
else:
self.is_available = False
-- logger.warning("No SearXNG instance URL provided. The engine is disabled. "
-- "Set SEARXNG_INSTANCE environment variable or provide instance_url parameter.")
++ logger.error("No SearXNG instance URL provided. The engine is disabled. "
++ "Set SEARXNG_INSTANCE environment variable or provide instance_url parameter.")
++
++ # Add debug logging for all parameters
++ logger.info(f"SearXNG init params: max_results={max_results}, language={language}, "
++ f"max_filtered_results={max_filtered_results}, is_available={self.is_available}")
self.max_results = max_results
self.categories = categories or ["general"]
@@@ -122,9 -122,9 +130,11 @@@
List of search results from SearXNG
"""
if not self.is_available:
-- logger.warning("SearXNG engine is disabled (no instance URL provided)")
++ logger.error("SearXNG engine is disabled (no instance URL provided) - cannot run search")
return []
++ logger.info(f"SearXNG running search for query: {query}")
++
try:
self._respect_rate_limit()
@@@ -423,4 -423,4 +433,22 @@@ docker-compose up -
For more detailed instructions and configuration options, visit:
https://searxng.github.io/searxng/admin/installation.html
--"""
++"""
++
++ def run(self, query: str) -> List[Dict[str, Any]]:
++ """
++ Override BaseSearchEngine run method to add SearXNG-specific error handling.
++ """
++ if not self.is_available:
++ logger.error("SearXNG run method called but engine is not available (missing instance URL)")
++ return []
++
++ logger.info(f"SearXNG run method called with query: {query}")
++
++ try:
++ # Call the parent class's run method
++ return super().run(query)
++ except Exception as e:
++ logger.error(f"Error in SearXNG run method: {str(e)}")
++ # Return empty results on error
++ return []
diff --cc web_search_engines/search_engine_factory.py
index 07cf2a7a1f,07cf2a7a1f..41513c9c0e
--- a/web_search_engines/search_engine_factory.py
+++ b/web_search_engines/search_engine_factory.py
@@@ -223,4 -223,4 +223,23 @@@ def get_search(search_tool: str, llm_in
params["time_period"] = time_period
# Create and return the search engine
-- return create_search_engine(search_tool, **params)
++ logger.info(f"Creating search engine for tool: {search_tool} with params: {params.keys()}")
++ engine = create_search_engine(search_tool, **params)
++
++ # Add debugging to check if engine is None
++ if engine is None:
++ logger.error(f"Failed to create search engine for {search_tool} - returned None")
++ else:
++ engine_type = type(engine).__name__
++ logger.info(f"Successfully created search engine of type: {engine_type}")
++ # Check if the engine has run method
++ if hasattr(engine, 'run'):
++ logger.info(f"Engine has 'run' method: {getattr(engine, 'run')}")
++ else:
++ logger.error(f"Engine does NOT have 'run' method!")
++
++ # For SearxNG, check availability flag
++ if hasattr(engine, 'is_available'):
++ logger.info(f"Engine availability flag: {engine.is_available}")
++
++ return engine