~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
Improve error handling system and add Ollama debugging capabilities
LearningCircuit1044ef65ddb3
diff --git a/.github/workflows/version_check.yml b/.github/workflows/version_check.ymlindex 243f2794d5..2ad0a4c329 100644--- a/.github/workflows/version_check.yml+++ b/.github/workflows/version_check.yml@@ -8,6 +8,10 @@ on:branches:- 'main'+permissions:+ contents: write+ pull-requests: write+jobs:version-check:runs-on: ubuntu-latest@@ -16,6 +20,8 @@ jobs:uses: actions/checkout@v4with:fetch-depth: 0+ token: ${{ secrets.GITHUB_TOKEN }}+ ref: ${{ github.head_ref }}- name: Set up Pythonuses: actions/setup-python@v5@@ -23,6 +29,7 @@ jobs:python-version: '3.13.2'- name: Check and auto-bump version+ if: "!contains(github.event.head_commit.message, 'chore: auto-bump version')"run: |if ! git diff origin/${{ github.base_ref }}..HEAD -G"__version__" | grep -E '\+.*__version__.*='; thenecho "Version not updated. Auto-bumping patch version..."@@ -51,8 +58,10 @@ jobs:# Commit the version bumpgit add src/local_deep_research/__version__.py- git commit -m "chore: auto-bump version to $new_version"- git push+ git commit -m "chore: auto-bump version to $new_version [skip ci]"++ # Push to the PR branch+ git push origin ${{ github.head_ref }}echo "Version automatically bumped to $new_version"elsediff --git a/src/local_deep_research/__version__.py b/src/local_deep_research/__version__.pyindex 722515271f..43a1e95ba4 100644--- a/src/local_deep_research/__version__.py+++ b/src/local_deep_research/__version__.py@@ -1 +1 @@-__version__ = "0.5.2"+__version__ = "0.5.3"diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex fc47a2786c..b0b0f77b0c 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -397,6 +397,24 @@ def get_llm(llm = ChatOllama(model=model_name, base_url=base_url, **common_params)++ # Log the actual client configuration after creation+ logger.debug(+ f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}"+ )+ if hasattr(llm, "_client"):+ client = llm._client+ logger.debug(f"ChatOllama _client type: {type(client)}")+ if hasattr(client, "_client"):+ inner_client = client._client+ logger.debug(+ f"ChatOllama inner client type: {type(inner_client)}"+ )+ if hasattr(inner_client, "base_url"):+ logger.debug(+ f"ChatOllama inner client base_url: {inner_client.base_url}"+ )+# Test invoke to validate model workslogger.info("Testing Ollama model with simple invocation")test_result = llm.invoke("Hello")@@ -545,7 +563,49 @@ def wrap_llm_without_think_tags(self.base_llm = base_llmdef invoke(self, *args, **kwargs):- response = self.base_llm.invoke(*args, **kwargs)+ # Log detailed request information for Ollama models+ if hasattr(self.base_llm, "base_url"):+ logger.debug(+ f"LLM Request - Base URL: {self.base_llm.base_url}"+ )+ logger.debug(+ f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}"+ )+ logger.debug(+ f"LLM Request - Args count: {len(args)}, Kwargs: {list(kwargs.keys())}"+ )++ # Log the prompt if it's in args+ if args and len(args) > 0:+ prompt_text = (+ str(args[0])[:200] + "..."+ if len(str(args[0])) > 200+ else str(args[0])+ )+ logger.debug(f"LLM Request - Prompt preview: {prompt_text}")++ # Check if there's any client configuration+ if hasattr(self.base_llm, "_client"):+ client = self.base_llm._client+ if hasattr(client, "_client") and hasattr(+ client._client, "base_url"+ ):+ logger.debug(+ f"LLM Request - Client base URL: {client._client.base_url}"+ )++ try:+ response = self.base_llm.invoke(*args, **kwargs)+ logger.debug(f"LLM Response - Success, type: {type(response)}")+ except Exception as e:+ logger.error(f"LLM Request - Failed with error: {str(e)}")+ # Log any URL information from the error+ error_str = str(e)+ if "http://" in error_str or "https://" in error_str:+ logger.error(+ f"LLM Request - Error contains URL info: {error_str}"+ )+ raise# Process the response content if it has a content attributeif hasattr(response, "content"):diff --git a/src/local_deep_research/error_handling/__init__.py b/src/local_deep_research/error_handling/__init__.pynew file mode 100644index 0000000000..7c1d00319a--- /dev/null+++ b/src/local_deep_research/error_handling/__init__.py@@ -0,0 +1,13 @@+"""+Error Handling Module for Local Deep Research++This module provides comprehensive error handling capabilities including:+- Error categorization and analysis+- User-friendly error report generation+- Integration with partial research results+"""++from .error_reporter import ErrorReporter+from .report_generator import ErrorReportGenerator++__all__ = ["ErrorReporter", "ErrorReportGenerator"]diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pynew file mode 100644index 0000000000..8fa4061648--- /dev/null+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -0,0 +1,236 @@+"""+ErrorReporter - Main error categorization and handling logic+"""++import re+from enum import Enum+from typing import Dict, Optional, Any+from loguru import logger+++class ErrorCategory(Enum):+ """Categories of errors that can occur during research"""++ CONNECTION_ERROR = "connection_error"+ MODEL_ERROR = "model_error"+ SEARCH_ERROR = "search_error"+ SYNTHESIS_ERROR = "synthesis_error"+ FILE_ERROR = "file_error"+ UNKNOWN_ERROR = "unknown_error"+++class ErrorReporter:+ """+ Analyzes and categorizes errors to provide better user feedback+ """++ def __init__(self):+ self.error_patterns = {+ ErrorCategory.CONNECTION_ERROR: [+ r"POST predict.*EOF",+ r"Connection refused",+ r"timeout",+ r"Connection.*failed",+ r"HTTP error \d+",+ r"network.*error",+ r"\[Errno 111\]",+ r"host\.docker\.internal",+ r"host.*localhost.*Docker",+ r"127\.0\.0\.1.*Docker",+ r"localhost.*1234.*Docker",+ r"LM.*Studio.*Docker.*Mac",+ ],+ ErrorCategory.MODEL_ERROR: [+ r"Model.*not found",+ r"Invalid.*model",+ r"Ollama.*not available",+ r"API key.*invalid",+ r"Authentication.*error",+ r"max_workers must be greater than 0",+ r"TypeError.*Context.*Size",+ r"'<' not supported between",+ r"No auth credentials found",+ r"401.*API key",+ ],+ ErrorCategory.SEARCH_ERROR: [+ r"Search.*failed",+ r"No search results",+ r"Search engine.*error",+ r"Rate limit.*exceeded",+ r"The search is longer than 256 characters",+ r"Failed to create search engine",+ r"could not be found",+ r"GitHub API error",+ r"database.*locked",+ ],+ ErrorCategory.SYNTHESIS_ERROR: [+ r"Error.*synthesis",+ r"Failed.*generate",+ r"Synthesis.*timeout",+ r"detailed.*report.*stuck",+ r"report.*taking.*long",+ r"progress.*100.*stuck",+ ],+ ErrorCategory.FILE_ERROR: [+ r"Permission denied",+ r"File.*not found",+ r"Cannot write.*file",+ r"Disk.*full",+ r"No module named.*local_deep_research",+ r"HTTP error 404.*research results",+ r"Attempt to write readonly database",+ ],+ }++ def categorize_error(self, error_message: str) -> ErrorCategory:+ """+ Categorize an error based on its message++ Args:+ error_message: The error message to categorize++ Returns:+ ErrorCategory: The categorized error type+ """+ error_message = str(error_message).lower()++ for category, patterns in self.error_patterns.items():+ for pattern in patterns:+ if re.search(pattern.lower(), error_message):+ logger.debug(+ f"Categorized error as {category.value}: {pattern}"+ )+ return category++ return ErrorCategory.UNKNOWN_ERROR++ def get_user_friendly_title(self, category: ErrorCategory) -> str:+ """+ Get a user-friendly title for an error category++ Args:+ category: The error category++ Returns:+ str: User-friendly title+ """+ titles = {+ ErrorCategory.CONNECTION_ERROR: "Connection Issue",+ ErrorCategory.MODEL_ERROR: "LLM Service Error",+ ErrorCategory.SEARCH_ERROR: "Search Service Error",+ ErrorCategory.SYNTHESIS_ERROR: "Report Generation Error",+ ErrorCategory.FILE_ERROR: "File System Error",+ ErrorCategory.UNKNOWN_ERROR: "Unexpected Error",+ }+ return titles.get(category, "Error")++ def get_suggested_actions(self, category: ErrorCategory) -> list:+ """+ Get suggested actions for resolving an error++ Args:+ category: The error category++ Returns:+ list: List of suggested actions+ """+ suggestions = {+ ErrorCategory.CONNECTION_ERROR: [+ "Check if the LLM service (Ollama/LM Studio) is running",+ "Verify network connectivity",+ "Try switching to a different model provider",+ "Check the service logs for more details",+ ],+ ErrorCategory.MODEL_ERROR: [+ "Verify the model name is correct",+ "Check if the model is downloaded and available",+ "Validate API keys if using external services",+ "Try switching to a different model",+ ],+ ErrorCategory.SEARCH_ERROR: [+ "Check internet connectivity",+ "Try reducing the number of search results",+ "Wait a moment and try again",+ "Check if search service is configured correctly",+ "For local documents: ensure the path is absolute and folder exists",+ "Try a different search engine if one is failing",+ ],+ ErrorCategory.SYNTHESIS_ERROR: [+ "The research data was collected successfully",+ "Try switching to a different model for report generation",+ "Check the partial results below",+ "Review the detailed logs for more information",+ ],+ ErrorCategory.FILE_ERROR: [+ "Check disk space availability",+ "Verify write permissions",+ "Try changing the output directory",+ "Restart the application",+ ],+ ErrorCategory.UNKNOWN_ERROR: [+ "Check the detailed logs below for more information",+ "Try running the research again",+ "Report this issue if it persists",+ "Contact support with the error details",+ ],+ }+ return suggestions.get(category, ["Check the logs for more details"])++ def analyze_error(+ self, error_message: str, context: Optional[Dict[str, Any]] = None+ ) -> Dict[str, Any]:+ """+ Perform comprehensive error analysis++ Args:+ error_message: The error message to analyze+ context: Optional context information++ Returns:+ dict: Comprehensive error analysis+ """+ category = self.categorize_error(error_message)++ analysis = {+ "category": category,+ "title": self.get_user_friendly_title(category),+ "original_error": error_message,+ "suggestions": self.get_suggested_actions(category),+ "severity": self._determine_severity(category),+ "recoverable": self._is_recoverable(category),+ }++ # Add context-specific information+ if context:+ analysis["context"] = context+ analysis["has_partial_results"] = bool(+ context.get("findings")+ or context.get("current_knowledge")+ or context.get("search_results")+ )++ return analysis++ def _determine_severity(self, category: ErrorCategory) -> str:+ """Determine error severity level"""+ severity_map = {+ ErrorCategory.CONNECTION_ERROR: "high",+ ErrorCategory.MODEL_ERROR: "high",+ ErrorCategory.SEARCH_ERROR: "medium",+ ErrorCategory.SYNTHESIS_ERROR: "low", # Can often show partial results+ ErrorCategory.FILE_ERROR: "medium",+ ErrorCategory.UNKNOWN_ERROR: "high",+ }+ return severity_map.get(category, "medium")++ def _is_recoverable(self, category: ErrorCategory) -> bool:+ """Determine if error is recoverable with user action"""+ recoverable = {+ ErrorCategory.CONNECTION_ERROR: True,+ ErrorCategory.MODEL_ERROR: True,+ ErrorCategory.SEARCH_ERROR: True,+ ErrorCategory.SYNTHESIS_ERROR: True,+ ErrorCategory.FILE_ERROR: True,+ ErrorCategory.UNKNOWN_ERROR: False,+ }+ return recoverable.get(category, False)diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.pynew file mode 100644index 0000000000..064f5add0c--- /dev/null+++ b/src/local_deep_research/error_handling/report_generator.py@@ -0,0 +1,403 @@+"""+ErrorReportGenerator - Create user-friendly error reports+"""++from typing import Dict, Any, Optional+from loguru import logger++from .error_reporter import ErrorReporter+++class ErrorReportGenerator:+ """+ Generates comprehensive, user-friendly error reports+ """++ def __init__(self, llm=None):+ """+ Initialize error report generator++ Args:+ llm: Optional LLM instance (unused, kept for compatibility)+ """+ self.error_reporter = ErrorReporter()++ def generate_error_report(+ self,+ error_message: str,+ query: str,+ partial_results: Optional[Dict[str, Any]] = None,+ search_iterations: int = 0,+ research_id: Optional[int] = None,+ ) -> str:+ """+ Generate a comprehensive error report++ Args:+ error_message: The error that occurred+ query: The research query+ partial_results: Any partial results that were collected+ search_iterations: Number of search iterations completed+ research_id: Research ID for reference++ Returns:+ str: Formatted error report in Markdown+ """+ try:+ # Analyze the error+ context = {+ "query": query,+ "search_iterations": search_iterations,+ "research_id": research_id,+ "partial_results": partial_results,+ }++ if partial_results:+ context.update(partial_results)++ error_analysis = self.error_reporter.analyze_error(+ error_message, context+ )++ # Build the simplified report+ report_parts = []++ # Header with user-friendly error message and logs reference+ user_friendly_message = self._make_error_user_friendly(+ error_message+ )+ category_title = error_analysis.get("title", "Error")++ report_parts.append("# ⚠️ Research Failed")+ report_parts.append(f"\n**Error Type:** {category_title}")+ report_parts.append(f"\n**What happened:** {user_friendly_message}")+ report_parts.append(+ '\n*For detailed error information, scroll down to the research logs and select "Errors" from the filter.*'+ )++ # Support links - moved up for better visibility+ report_parts.append("\n## 💬 Get Help")+ report_parts.append("We're here to help you get this working:")+ report_parts.append(+ "- 📖 **Documentation & guides:** [Wiki](https://github.com/LearningCircuit/local-deep-research/wiki)"+ )+ report_parts.append(+ "- 💬 **Chat with the community:** [Discord #help-and-support](https://discord.gg/ttcqQeFcJ3)"+ )+ report_parts.append(+ "- 🐛 **Report bugs or get help:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues) *(don't hesitate to ask if you're stuck!)*"+ )+ report_parts.append(+ "- 💭 **Join discussions:** [Reddit r/LocalDeepResearch](https://www.reddit.com/r/LocalDeepResearch/) *(checked less frequently)*"+ )++ # Show partial results if available (in expandable section)+ if error_analysis.get("has_partial_results"):+ partial_content = self._format_partial_results(partial_results)+ if partial_content:+ report_parts.append(+ f"\n<details>\n<summary>📊 Partial Results Available</summary>\n\n{partial_content}\n</details>"+ )++ return "\n".join(report_parts)++ except Exception as e:+ # Fallback: always return something, even if error report generation fails+ logger.exception(f"Failed to generate error report: {e}")+ return f"""# ⚠️ Research Failed++**What happened:** {error_message}++## 💬 Get Help+We're here to help you get this working:+- 📖 **Documentation & guides:** [Wiki](https://github.com/LearningCircuit/local-deep-research/wiki)+- 💬 **Chat with the community:** [Discord #help-and-support](https://discord.gg/ttcqQeFcJ3)+- 🐛 **Report bugs or get help:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues) *(don't hesitate to ask if you're stuck!)*++*Note: Error report generation failed - showing basic error information.*"""++ def _format_partial_results(+ self, partial_results: Optional[Dict[str, Any]]+ ) -> str:+ """+ Format partial results for display++ Args:+ partial_results: Partial results data++ Returns:+ str: Formatted partial results+ """+ if not partial_results:+ return ""++ formatted_parts = []++ # Current knowledge summary+ if "current_knowledge" in partial_results:+ knowledge = partial_results["current_knowledge"]+ if knowledge and len(knowledge.strip()) > 50:+ formatted_parts.append("### Research Summary\n")+ formatted_parts.append(+ knowledge[:1000] + "..."+ if len(knowledge) > 1000+ else knowledge+ )+ formatted_parts.append("")++ # Search results+ if "search_results" in partial_results:+ results = partial_results["search_results"]+ if results:+ formatted_parts.append("### Search Results Found\n")+ for i, result in enumerate(results[:5], 1): # Show top 5+ title = result.get("title", "Untitled")+ url = result.get("url", "")+ formatted_parts.append(f"{i}. **{title}**")+ if url:+ formatted_parts.append(f" - URL: {url}")+ formatted_parts.append("")++ # Findings+ if "findings" in partial_results:+ findings = partial_results["findings"]+ if findings:+ formatted_parts.append("### Research Findings\n")+ for i, finding in enumerate(findings[:3], 1): # Show top 3+ content = finding.get("content", "")+ if content and not content.startswith("Error:"):+ phase = finding.get("phase", f"Finding {i}")+ formatted_parts.append(f"**{phase}:**")+ formatted_parts.append(+ content[:500] + "..."+ if len(content) > 500+ else content+ )+ formatted_parts.append("")++ if formatted_parts:+ formatted_parts.append(+ "*Note: The above results were successfully collected before the error occurred.*"+ )++ return "\n".join(formatted_parts) if formatted_parts else ""++ def _get_technical_context(+ self,+ error_analysis: Dict[str, Any],+ partial_results: Optional[Dict[str, Any]],+ ) -> str:+ """+ Get additional technical context for the error++ Args:+ error_analysis: Error analysis results+ partial_results: Partial results if available++ Returns:+ str: Technical context information+ """+ context_parts = []++ # Add timing information if available+ if partial_results:+ if "start_time" in partial_results:+ context_parts.append(+ f"- **Start Time:** {partial_results['start_time']}"+ )++ if "last_activity" in partial_results:+ context_parts.append(+ f"- **Last Activity:** {partial_results['last_activity']}"+ )++ # Add model information+ if "model_config" in partial_results:+ config = partial_results["model_config"]+ context_parts.append(+ f"- **Model:** {config.get('model_name', 'Unknown')}"+ )+ context_parts.append(+ f"- **Provider:** {config.get('provider', 'Unknown')}"+ )++ # Add search information+ if "search_config" in partial_results:+ search_config = partial_results["search_config"]+ context_parts.append(+ f"- **Search Engine:** {search_config.get('engine', 'Unknown')}"+ )+ context_parts.append(+ f"- **Max Results:** {search_config.get('max_results', 'Unknown')}"+ )++ # Add any error codes or HTTP status+ if "status_code" in partial_results:+ context_parts.append(+ f"- **Status Code:** {partial_results['status_code']}"+ )++ if "error_code" in partial_results:+ context_parts.append(+ f"- **Error Code:** {partial_results['error_code']}"+ )++ # Add error-specific context based on category+ category = error_analysis.get("category")+ if category:+ if "connection" in category.value.lower():+ context_parts.append(+ "- **Network Error:** Connection-related issue detected"+ )+ context_parts.append(+ "- **Retry Recommended:** Check service status and try again"+ )+ elif "model" in category.value.lower():+ context_parts.append(+ "- **Model Error:** Issue with AI model or configuration"+ )+ context_parts.append(+ "- **Check:** Model service availability and parameters"+ )++ return "\n".join(context_parts) if context_parts else ""++ def generate_quick_error_summary(+ self, error_message: str+ ) -> Dict[str, str]:+ """+ Generate a quick error summary for API responses++ Args:+ error_message: The error message++ Returns:+ dict: Quick error summary+ """+ error_analysis = self.error_reporter.analyze_error(error_message)++ return {+ "title": error_analysis["title"],+ "category": error_analysis["category"].value,+ "severity": error_analysis["severity"],+ "recoverable": error_analysis["recoverable"],+ }++ def _make_error_user_friendly(self, error_message: str) -> str:+ """+ Replace cryptic technical error messages with user-friendly versions++ Args:+ error_message: The original technical error message++ Returns:+ str: User-friendly error message, or original if no replacement found+ """+ # Dictionary of technical errors to user-friendly messages+ error_replacements = {+ "max_workers must be greater than 0": (+ "The LLM failed to generate search questions. This usually means the LLM service isn't responding properly.\n\n"+ "**Try this:**\n"+ "- Check if your LLM service (Ollama/LM Studio) is running\n"+ "- Restart the LLM service\n"+ "- Try a different model"+ ),+ "POST predict.*EOF": (+ "Lost connection to Ollama. This usually means Ollama stopped responding or there's a network issue.\n\n"+ "**Try this:**\n"+ "- Restart Ollama: `ollama serve`\n"+ "- Check if Ollama is still running: `ps aux | grep ollama`\n"+ "- Try a different port if 11434 is in use"+ ),+ "HTTP error 404.*research results": (+ "The research completed but the results can't be displayed. The files were likely generated successfully.\n\n"+ "**Try this:**\n"+ "- Check the `research_outputs` folder for your report\n"+ "- Ensure the folder has proper read/write permissions\n"+ "- Restart the LDR web interface"+ ),+ "Connection refused|\\[Errno 111\\]": (+ "Cannot connect to the LLM service. The service might not be running or is using a different address.\n\n"+ "**Try this:**\n"+ "- Start your LLM service (Ollama: `ollama serve`, LM Studio: launch the app)\n"+ "- **Docker on Mac/Windows:** Change URL from `http://localhost:1234` to `http://host.docker.internal:1234`\n"+ "- **Docker on Linux:** Use your host IP instead of localhost (find with `hostname -I`)\n"+ "- Check the service URL in settings matches where your LLM is running\n"+ "- Verify the port number is correct (Ollama: 11434, LM Studio: 1234)"+ ),+ "The search is longer than 256 characters": (+ "Your search query is too long for GitHub's API (max 256 characters).\n\n"+ "**Try this:**\n"+ "- Shorten your research query\n"+ "- Use a different search engine (DuckDuckGo, Searx, etc.)\n"+ "- Break your research into smaller, focused queries"+ ),+ "No module named.*local_deep_research": (+ "Installation issue detected. The package isn't properly installed.\n\n"+ "**Try this:**\n"+ "- Reinstall: `pip install -e .` from the project directory\n"+ "- Check you're using the right Python environment\n"+ "- For Docker users: rebuild the container"+ ),+ "Failed to create search engine|could not be found": (+ "Search engine configuration problem.\n\n"+ "**Try this:**\n"+ "- Use the default search engine (auto)\n"+ "- Check search engine settings in Advanced Options\n"+ "- Ensure required API keys are set for external search engines"+ ),+ "TypeError.*Context.*Size|'<' not supported between": (+ "Model configuration issue. The context size setting might not be compatible with your model.\n\n"+ "**Try this:**\n"+ "- Check your model's maximum context size\n"+ "- Leave context size settings at default\n"+ "- Try a different model"+ ),+ "Model.*not found in Ollama": (+ "The specified model isn't available in Ollama.\n\n"+ "**Try this:**\n"+ "- Check available models: `ollama list`\n"+ "- Pull the model: `ollama pull <model-name>`\n"+ "- Use the exact model name shown in `ollama list` (e.g., 'gemma2:9b' not 'gemma:latest')"+ ),+ "No auth credentials found|401.*API key": (+ "API key is missing or incorrectly configured.\n\n"+ "**Try this:**\n"+ "- Set API key in the web UI settings (not in .env files)\n"+ "- Go to Settings → Advanced → enter your API key\n"+ "- For custom endpoints, ensure the key format matches what your provider expects"+ ),+ "Attempt to write readonly database": (+ "Permission issue with the database file.\n\n"+ "**Try this:**\n"+ "- On Windows: Run as Administrator\n"+ "- On Linux/Mac: Check folder permissions\n"+ "- Delete and recreate the database file if corrupted"+ ),+ "Invalid value.*SearXNG|database.*locked": (+ "SearXNG configuration or rate limiting issue.\n\n"+ "**Try this:**\n"+ "- Keep 'Search snippets only' enabled (don't turn it off)\n"+ "- Restart SearXNG: `docker restart searxng`\n"+ "- If rate limited, wait a few minutes or use a VPN"+ ),+ "host.*localhost.*Docker|127\\.0\\.0\\.1.*Docker|localhost.*1234.*Docker|LM.*Studio.*Docker.*Mac": (+ "Docker networking issue - can't connect to services on host.\n\n"+ "**Try this:**\n"+ "- **On Mac/Windows Docker:** Replace 'localhost' or '127.0.0.1' with 'host.docker.internal'\n"+ "- **On Linux Docker:** Use your host's actual IP address (find with `hostname -I`)\n"+ "- **Example:** Change `http://localhost:1234` to `http://host.docker.internal:1234`\n"+ "- Ensure the service port isn't blocked by firewall\n"+ "- Alternative: Use host networking mode (see wiki for setup)"+ ),+ }++ # Check each pattern and replace if found+ for pattern, replacement in error_replacements.items():+ import re++ if re.search(pattern, error_message, re.IGNORECASE):+ return f"{replacement}\n\nTechnical error: {error_message}"++ # If no specific replacement found, return original message+ return error_messagediff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex 7c6269ae0a..5f48b75852 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -254,7 +254,7 @@ def get_research_details(research_id):)-@history_bp.route("/report/<int:research_id>")+@history_bp.route("/history/report/<int:research_id>")def get_report(research_id):conn = get_db_connection()conn.row_factory = lambda cursor, row: {diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex b7e37452b4..39e59200fb 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -17,6 +17,7 @@ from ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..database.models import ResearchStrategy, ResearchHistoryfrom ..models.database import calculate_durationfrom .socket_service import SocketIOService+from ...error_handling.report_generator import ErrorReportGenerator# Output directory for research results_PROJECT_ROOT = Path(__file__).parents[4]@@ -657,8 +658,40 @@ def run_research_process()try:- # Get the synthesized content from the LLM directly- clean_markdown = raw_formatted_findings+ # Check if we have an error in the findings and use enhanced error handling+ if isinstance(+ raw_formatted_findings, str+ ) and raw_formatted_findings.startswith("Error:"):+ logger.info(+ "Generating enhanced error report using ErrorReportGenerator"+ )++ # Get LLM for error explanation if available+ try:+ llm = get_llm(research_id=research_id)+ except Exception:+ llm = None+ logger.warning(+ "Could not get LLM for error explanation"+ )++ # Generate comprehensive error report+ error_generator = ErrorReportGenerator(llm)+ clean_markdown = error_generator.generate_error_report(+ error_message=raw_formatted_findings,+ query=query,+ partial_results=results,+ search_iterations=results.get("iterations", 0),+ research_id=research_id,+ )++ logger.info(+ "Generated enhanced error report with %d characters",+ len(clean_markdown),+ )+ else:+ # Get the synthesized content from the LLM directly+ clean_markdown = raw_formatted_findings# Extract all sources from findings to add them to the summaryall_links = []@@ -878,10 +911,77 @@ def run_research_process("solution": "Check API configuration and credentials."}+ # Generate enhanced error report for failed research+ enhanced_report_content = None+ try:+ # Get LLM for error explanation if available+ try:+ llm = get_llm(research_id=research_id)+ except Exception:+ llm = None+ logger.warning(+ "Could not get LLM for error explanation in failure handler"+ )++ # Get partial results if they exist+ partial_results = results if "results" in locals() else None+ search_iterations = (+ results.get("iterations", 0) if partial_results else 0+ )++ # Generate comprehensive error report+ error_generator = ErrorReportGenerator(llm)+ enhanced_report_content = error_generator.generate_error_report(+ error_message=f"Research failed: {str(e)}",+ query=query,+ partial_results=partial_results,+ search_iterations=search_iterations,+ research_id=research_id,+ )++ logger.info(+ "Generated enhanced error report for failed research (length: %d)",+ len(enhanced_report_content),+ )++ # Save enhanced error report as the actual report file+ try:+ reports_folder = OUTPUT_DIR+ report_filename = f"research_{research_id}_error_report.md"+ report_path = reports_folder / report_filename++ with open(report_path, "w", encoding="utf-8") as f:+ f.write(enhanced_report_content)++ logger.info(+ "Saved enhanced error report to: %s", report_path+ )++ # Store the report path so it can be retrieved later+ report_path_to_save = str(+ report_path.relative_to(reports_folder.parent)+ )++ except Exception as report_error:+ logger.exception(+ "Failed to save enhanced error report: %s", report_error+ )+ report_path_to_save = None++ except Exception as error_gen_error:+ logger.exception(+ "Failed to generate enhanced error report: %s",+ error_gen_error,+ )+ enhanced_report_content = None+ report_path_to_save = None+# Update metadata with more context about the errormetadata = {"phase": "error", "error": user_friendly_error}if error_context:metadata.update(error_context)+ if enhanced_report_content:+ metadata["has_enhanced_report"] = True# If we still have an active research record, update its logif research_id in active_research:@@ -934,6 +1034,10 @@ def run_research_process(research.duration_seconds = duration_secondsresearch.metadata = metadata+ # Add error report path if available+ if "report_path_to_save" in locals() and report_path_to_save:+ research.report_path = report_path_to_save+db_session.commit()try:diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.jsindex 35ab760d9f..7ca9bc61db 100644--- a/src/local_deep_research/web/static/js/components/progress.js+++ b/src/local_deep_research/web/static/js/components/progress.js@@ -630,18 +630,20 @@cancelButton.style.display = 'none';}} else if (data.status === 'failed' || data.status === 'cancelled') {- // Show error message- if (window.ui) {- window.ui.showError(data.error || 'Research was unsuccessful');+ // For failed research, try to show the error report if available+ if (data.status === 'failed') {+ if (viewResultsButton) {+ viewResultsButton.textContent = 'View Error Report';+ viewResultsButton.href = `/research/results/${currentResearchId}`;+ viewResultsButton.style.display = 'inline-block';+ }} else {- console.error('Research failed:', data.error || 'Unknown error');- }-- // Update button to go back to home- if (viewResultsButton) {- viewResultsButton.textContent = 'Start New Research';- viewResultsButton.href = '/';- viewResultsButton.style.display = 'inline-block';+ // For cancelled research, go back to home+ if (viewResultsButton) {+ viewResultsButton.textContent = 'Start New Research';+ viewResultsButton.href = '/';+ viewResultsButton.style.display = 'inline-block';+ }}// Hide cancel button@@ -917,8 +919,12 @@cancelButton.style.display = 'none';}- // Show results button (might have partial results)- showResultsButton();+ // Show error report button+ if (viewResultsButton) {+ viewResultsButton.textContent = 'View Error Report';+ viewResultsButton.href = `/research/results/${currentResearchId}`;+ viewResultsButton.style.display = 'inline-block';+ }// Show notification if enabledshowNotification('Research Error', `There was an error with your research: ${data.error}`);diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.jsindex 2469e28c0f..0120f9388d 100644--- a/src/local_deep_research/web/static/js/components/results.js+++ b/src/local_deep_research/web/static/js/components/results.js@@ -98,7 +98,7 @@resultsContainer.innerHTML = '<div class="text-center my-5"><i class="fas fa-spinner fa-pulse"></i><p class="mt-3">Loading research results...</p></div>';// Fetch result from API- const response = await fetch(`/research/api/report/${researchId}`);+ const response = await fetch(`/research/api/history/report/${researchId}`);if (!response.ok) {throw new Error(`HTTP error ${response.status}`);diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 62c7051d03..f9f7bba781 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -48,7 +48,7 @@<label for="mode-quick" class="mode-option active" data-mode="quick" role="radio" aria-checked="true" tabindex="0"><div class="mode-icon"><i class="fas fa-bolt" aria-hidden="true"></i></div><div class="mode-info">- <h3>Quick Summary</h3>+ <h2>Quick Summary</h2><p>Generated in a few minutes</p></div></label>@@ -57,7 +57,7 @@<label for="mode-detailed" class="mode-option" data-mode="detailed" role="radio" aria-checked="false" tabindex="-1"><div class="mode-icon"><i class="fas fa-microscope" aria-hidden="true"></i></div><div class="mode-info">- <h3>Detailed Report</h3>+ <h2>Detailed Report</h2><p>In-depth analysis (takes longer)</p></div></label>diff --git a/tests/accessibility_tests/README.md b/tests/accessibility_tests/README.mdnew file mode 100644index 0000000000..cb4003dcfe--- /dev/null+++ b/tests/accessibility_tests/README.md@@ -0,0 +1,209 @@+# Accessibility Tests++This directory contains accessibility tests for the Local Deep Research web interface, focusing on ensuring compliance with WCAG 2.1 AA standards and screen reader compatibility.++## Test Coverage++### JavaScript Tests (`test_accessibility.js`)+These tests use Playwright to verify:++- **Screen Reader Compatibility**+ - Proper radio button structure for research mode selection+ - ARIA attributes and roles+ - Screen reader only elements (`.sr-only` class)+ - Fieldset and legend usage++- **Keyboard Navigation**+ - Tab order and focus management+ - Arrow key navigation for radio button groups+ - Enter and Space key activation+ - Keyboard shortcuts (Enter to submit, Shift+Enter for new lines)++- **Form Accessibility**+ - Proper labeling of form controls+ - Keyboard hint visibility+ - Form submission via keyboard+ - Focus indicators++- **WCAG Compliance**+ - Automated accessibility testing with axe-core+ - Color contrast and focus visibility+ - Semantic markup validation++### Python Tests (`test_accessibility_backend.py`)+These tests verify server-side HTML structure:++- **HTML Structure**+ - Proper form labeling+ - Semantic markup usage+ - Heading hierarchy+ - Required field marking++- **ARIA Implementation**+ - Radio button group structure+ - ARIA roles and attributes+ - Screen reader support elements++- **Configuration**+ - HTML lang attribute+ - Viewport meta tag+ - CSS focus styles++## Running the Tests++### Prerequisites+```bash+# Install Python dependencies+pip install pytest beautifulsoup4 requests++# Install Node.js dependencies for Playwright tests+npm install playwright @playwright/test+npx playwright install+```++### Running JavaScript Tests+```bash+# Run all accessibility tests+npx playwright test test_accessibility.js++# Run with UI mode for debugging+npx playwright test test_accessibility.js --ui++# Run specific test+npx playwright test test_accessibility.js -g "mode selection should have proper radio button structure"+```++### Running Python Tests+```bash+# Run from the tests directory+cd tests+python -m pytest ui_tests/test_accessibility_backend.py -v++# Run with coverage+python -m pytest ui_tests/test_accessibility_backend.py --cov=src++# Run specific test+python -m pytest ui_tests/test_accessibility_backend.py::TestHTMLAccessibility::test_radio_button_structure -v+```++## Test Environment Setup++### Environment Variables+```bash+# Set base URL for testing (default: http://localhost:5000)+export TEST_BASE_URL=http://localhost:8080+```++### Running the Application+Make sure the application is running before executing tests:+```bash+# Start the web server+python app.py+# or+python -m src.local_deep_research.web.app+```++## Accessibility Features Tested++### Issue #75 - Screen Reader Compatibility+- ✅ Radio buttons replace div-based mode selection+- ✅ Proper ARIA roles and attributes+- ✅ Keyboard navigation with arrow keys+- ✅ Screen reader announcements+- ✅ Focus management++### Keyboard Shortcuts Enhancement+- ✅ Enter key submits form from textarea+- ✅ Shift+Enter creates new lines in textarea+- ✅ Ctrl+Enter alternative submission method+- ✅ Visible keyboard hints for users+- ✅ Tab navigation through form elements++### WCAG 2.1 AA Compliance+- ✅ Proper heading hierarchy+- ✅ Semantic HTML elements+- ✅ Focus indicators+- ✅ Color contrast (automated testing)+- ✅ Keyboard accessibility+- ✅ Screen reader support++## Common Test Failures and Solutions++### Radio Button Structure Issues+**Error**: Missing radio button or improper labeling+**Solution**: Ensure HTML template includes proper `<input type="radio">` elements with corresponding `<label>` elements++### ARIA Attribute Mismatches+**Error**: `aria-checked` not matching actual radio state+**Solution**: Verify JavaScript `selectMode()` function updates both visual state and ARIA attributes++### Keyboard Navigation Failures+**Error**: Arrow keys not working for mode selection+**Solution**: Check that event listeners are properly attached in `research.js`++### Focus Visibility Issues+**Error**: Focus indicators not visible+**Solution**: Verify CSS focus styles are properly defined in `custom_dropdown.css`++## Integration with CI/CD++These tests are designed to be integrated into the CI pipeline. See the main CI configuration for setup details.++### Test Commands for CI+```bash+# Quick accessibility check+npm run test:accessibility:quick++# Full accessibility suite+npm run test:accessibility:full++# Python accessibility tests+python -m pytest tests/ui_tests/test_accessibility_backend.py+```++## Browser Compatibility++The JavaScript tests are run against multiple browsers:+- Chromium (Chrome/Edge)+- Firefox+- WebKit (Safari)++Each browser may have different accessibility behaviors, particularly around screen reader APIs.++## Manual Testing Recommendations++While automated tests catch many accessibility issues, manual testing is still recommended:++1. **Screen Reader Testing**+ - Test with NVDA (Windows)+ - Test with JAWS (Windows)+ - Test with VoiceOver (macOS)++2. **Keyboard-Only Navigation**+ - Disconnect mouse and navigate using only keyboard+ - Verify all functionality is accessible++3. **High Contrast Mode**+ - Test in Windows High Contrast mode+ - Verify focus indicators remain visible++4. **Zoom Testing**+ - Test at 200% zoom level+ - Ensure all content remains accessible++## Contributing++When adding new UI features:++1. Add corresponding accessibility tests+2. Ensure ARIA attributes are properly implemented+3. Test keyboard navigation+4. Verify screen reader compatibility+5. Run full accessibility test suite before submitting PR++## Resources++- [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)+- [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/)+- [Playwright Accessibility Testing](https://playwright.dev/docs/accessibility-testing)+- [axe-core Documentation](https://github.com/dequelabs/axe-core)diff --git a/tests/accessibility_tests/__init__.py b/tests/accessibility_tests/__init__.pynew file mode 100644index 0000000000..6dc78a9e38--- /dev/null+++ b/tests/accessibility_tests/__init__.py@@ -0,0 +1 @@+# Accessibility Tests Modulediff --git a/tests/accessibility_tests/test_accessibility.js b/tests/accessibility_tests/test_accessibility.jsnew file mode 100644index 0000000000..e056ba7287--- /dev/null+++ b/tests/accessibility_tests/test_accessibility.js@@ -0,0 +1,344 @@+/**+ * Accessibility Tests+ * Tests for screen reader compatibility and keyboard navigation+ */++const { test, expect } = require('playwright/test');++test.describe('Research Form Accessibility', () => {+ test.beforeEach(async ({ page }) => {+ // Navigate to the research page+ await page.goto('/research/');++ // Wait for the page to load completely+ await page.waitForLoadState('networkidle');+ });++ test('mode selection should have proper radio button structure', async ({ page }) => {+ // Check that radio buttons exist and are properly structured+ const radioButtons = await page.locator('input[name="research_mode"]');+ await expect(radioButtons).toHaveCount(2);++ // Check that each radio button has a proper ID and label+ const quickRadio = await page.locator('#mode-quick');+ const detailedRadio = await page.locator('#mode-detailed');++ await expect(quickRadio).toBeVisible();+ await expect(detailedRadio).toBeVisible();++ // Check that labels are properly associated+ const quickLabel = await page.locator('label[for="mode-quick"]');+ const detailedLabel = await page.locator('label[for="mode-detailed"]');++ await expect(quickLabel).toBeVisible();+ await expect(detailedLabel).toBeVisible();++ // Check default selection+ await expect(quickRadio).toBeChecked();+ await expect(detailedRadio).not.toBeChecked();+ });++ test('mode selection should be accessible via keyboard', async ({ page }) => {+ const quickLabel = await page.locator('label[for="mode-quick"]');+ const detailedLabel = await page.locator('label[for="mode-detailed"]');++ // Focus on quick mode first+ await quickLabel.focus();++ // Check initial state+ await expect(quickLabel).toBeFocused();+ await expect(await page.locator('#mode-quick')).toBeChecked();++ // Navigate to detailed mode with arrow keys+ await page.keyboard.press('ArrowRight');+ await expect(detailedLabel).toBeFocused();+ await expect(await page.locator('#mode-detailed')).toBeChecked();++ // Navigate back with arrow keys+ await page.keyboard.press('ArrowLeft');+ await expect(quickLabel).toBeFocused();+ await expect(await page.locator('#mode-quick')).toBeChecked();+ });++ test('mode selection should respond to Enter and Space keys', async ({ page }) => {+ const detailedLabel = await page.locator('label[for="mode-detailed"]');++ // Focus on detailed mode+ await detailedLabel.focus();++ // Press Enter to select+ await page.keyboard.press('Enter');+ await expect(await page.locator('#mode-detailed')).toBeChecked();++ // Focus back to quick mode and test Space key+ const quickLabel = await page.locator('label[for="mode-quick"]');+ await quickLabel.focus();+ await page.keyboard.press('Space');+ await expect(await page.locator('#mode-quick')).toBeChecked();+ });++ test('fieldset and legend should be properly structured', async ({ page }) => {+ // Check for fieldset and legend elements+ const fieldset = await page.locator('fieldset');+ const legend = await page.locator('legend');++ await expect(fieldset).toBeVisible();+ await expect(legend).toBeVisible();+ await expect(legend).toHaveText('Research Mode');++ // Check that radiogroup role is present+ const radioGroup = await page.locator('[role="radiogroup"]');+ await expect(radioGroup).toBeVisible();+ });++ test('keyboard shortcuts should work in textarea', async ({ page }) => {+ const textarea = await page.locator('#query');++ // Focus on textarea+ await textarea.focus();++ // Type some text+ await textarea.fill('Test research query');++ // Test Shift+Enter for new line+ await page.keyboard.press('Shift+Enter');+ await textarea.type('Second line');++ // Check that text contains newline+ const textValue = await textarea.inputValue();+ expect(textValue).toContain('\n');+ expect(textValue).toContain('Test research query');+ expect(textValue).toContain('Second line');+ });++ test('Enter key should submit form from textarea', async ({ page }) => {+ const textarea = await page.locator('#query');+ const startButton = await page.locator('#start-research-btn');++ // Focus on textarea+ await textarea.focus();+ await textarea.fill('Test query for submission');++ // Mock the form submission to avoid actual API call+ await page.route('/research/api/start_research', (route) => {+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ status: 'success', research_id: 'test-123' })+ });+ });++ // Press Enter to submit+ await page.keyboard.press('Enter');++ // Check that button shows loading state+ await expect(startButton).toHaveText(/Starting.../);+ });++ test('keyboard hints should be visible', async ({ page }) => {+ const keyboardHint = await page.locator('.keyboard-hint');+ const hintText = await page.locator('.hint-text');++ await expect(keyboardHint).toBeVisible();+ await expect(hintText).toBeVisible();+ await expect(hintText).toHaveText('Press Enter to search • Shift+Enter for new line');+ });++ test('ARIA attributes should be properly set', async ({ page }) => {+ // Check ARIA attributes on mode options+ const quickLabel = await page.locator('label[for="mode-quick"]');+ const detailedLabel = await page.locator('label[for="mode-detailed"]');++ // Check role attributes+ await expect(quickLabel).toHaveAttribute('role', 'radio');+ await expect(detailedLabel).toHaveAttribute('role', 'radio');++ // Check aria-checked attributes+ await expect(quickLabel).toHaveAttribute('aria-checked', 'true');+ await expect(detailedLabel).toHaveAttribute('aria-checked', 'false');++ // Check tabindex attributes+ await expect(quickLabel).toHaveAttribute('tabindex', '0');+ await expect(detailedLabel).toHaveAttribute('tabindex', '-1');++ // Check that icons have aria-hidden+ const icons = await page.locator('.mode-icon i');+ for (let i = 0; i < await icons.count(); i++) {+ await expect(icons.nth(i)).toHaveAttribute('aria-hidden', 'true');+ }+ });++ test('mode selection should update radio buttons correctly', async ({ page }) => {+ const detailedLabel = await page.locator('label[for="mode-detailed"]');+ const detailedRadio = await page.locator('#mode-detailed');+ const quickRadio = await page.locator('#mode-quick');++ // Click on detailed mode+ await detailedLabel.click();++ // Check that radio button state is updated+ await expect(detailedRadio).toBeChecked();+ await expect(quickRadio).not.toBeChecked();++ // Check visual state is updated+ await expect(detailedLabel).toHaveClass(/active/);+ await expect(detailedLabel).toHaveAttribute('aria-checked', 'true');+ });++ test('form should be navigable with Tab key', async ({ page }) => {+ // Start from textarea+ const textarea = await page.locator('#query');+ await textarea.focus();++ // Tab to mode selection+ await page.keyboard.press('Tab');+ const quickLabel = await page.locator('label[for="mode-quick"]');+ await expect(quickLabel).toBeFocused();++ // Tab through advanced options toggle+ await page.keyboard.press('Tab');+ const advancedToggle = await page.locator('.advanced-options-toggle');+ await expect(advancedToggle).toBeFocused();++ // Tab to notification toggle+ await page.keyboard.press('Tab');+ const notificationToggle = await page.locator('#notification-toggle');+ await expect(notificationToggle).toBeFocused();++ // Tab to submit button+ await page.keyboard.press('Tab');+ const submitButton = await page.locator('#start-research-btn');+ await expect(submitButton).toBeFocused();+ });++ test('screen reader only elements should be properly hidden', async ({ page }) => {+ const radioButtons = await page.locator('input[name="research_mode"]');++ // Check that radio buttons have sr-only class+ for (let i = 0; i < await radioButtons.count(); i++) {+ await expect(radioButtons.nth(i)).toHaveClass(/sr-only/);+ }++ // Check that sr-only elements are visually hidden but accessible+ const srOnlyStyle = await page.evaluate(() => {+ const element = document.querySelector('.sr-only');+ return window.getComputedStyle(element);+ });++ expect(srOnlyStyle.position).toBe('absolute');+ expect(srOnlyStyle.width).toBe('1px');+ expect(srOnlyStyle.height).toBe('1px');+ });++ test('form submission should use radio button values', async ({ page }) => {+ const detailedLabel = await page.locator('label[for="mode-detailed"]');++ // Select detailed mode+ await detailedLabel.click();++ // Fill in required fields+ await page.locator('#query').fill('Test query');++ // Mock the API to capture the form data+ let capturedData = null;+ await page.route('/research/api/start_research', (route) => {+ capturedData = JSON.parse(route.request().postData());+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ status: 'success', research_id: 'test-123' })+ });+ });++ // Submit the form+ await page.locator('#start-research-btn').click();++ // Wait for the API call+ await page.waitForTimeout(1000);++ // Check that the correct mode was sent+ expect(capturedData.mode).toBe('detailed');+ });+});++test.describe('Accessibility Compliance', () => {+ test('page should not have accessibility violations', async ({ page }) => {+ await page.goto('/research/');+ await page.waitForLoadState('networkidle');++ // Inject axe-core for accessibility testing+ await page.addScriptTag({+ url: 'https://unpkg.com/[email protected]/axe.min.js'+ });++ // Run accessibility scan+ const results = await page.evaluate(() => {+ return new Promise((resolve) => {+ axe.run({+ rules: {+ // Focus on WCAG 2.1 AA standards+ 'color-contrast': { enabled: true },+ 'keyboard-navigation': { enabled: true },+ 'focus-management': { enabled: true },+ 'aria-usage': { enabled: true }+ }+ }, (err, results) => {+ resolve(results);+ });+ });+ });++ // Check for violations+ if (results.violations.length > 0) {+ console.log('Accessibility violations found:');+ results.violations.forEach(violation => {+ console.log(`- ${violation.id}: ${violation.description}`);+ violation.nodes.forEach(node => {+ console.log(` Target: ${node.target}`);+ });+ });+ }++ // Expect no critical violations+ const criticalViolations = results.violations.filter(v =>+ v.impact === 'critical' || v.impact === 'serious'+ );+ expect(criticalViolations).toHaveLength(0);+ });++ test('focus should be visible and logical', async ({ page }) => {+ await page.goto('/research/');++ // Test that focus is visible on all interactive elements+ const interactiveElements = [+ '#query',+ 'label[for="mode-quick"]',+ 'label[for="mode-detailed"]',+ '.advanced-options-toggle',+ '#notification-toggle',+ '#start-research-btn'+ ];++ for (const selector of interactiveElements) {+ await page.locator(selector).focus();++ // Check that focus is visible (outline or box-shadow)+ const element = await page.locator(selector);+ const styles = await element.evaluate(el => {+ const computed = window.getComputedStyle(el);+ return {+ outline: computed.outline,+ boxShadow: computed.boxShadow,+ outlineOffset: computed.outlineOffset+ };+ });++ // Should have either outline or box-shadow for focus+ const hasFocusStyle = styles.outline !== 'none' ||+ styles.boxShadow !== 'none' ||+ styles.outlineOffset !== '0px';++ expect(hasFocusStyle).toBe(true);+ }+ });+});diff --git a/tests/accessibility_tests/test_accessibility_backend.py b/tests/accessibility_tests/test_accessibility_backend.pynew file mode 100644index 0000000000..c934d931c3--- /dev/null+++ b/tests/accessibility_tests/test_accessibility_backend.py@@ -0,0 +1,313 @@+"""+Accessibility Backend Tests+Tests for HTML structure and semantic markup accessibility+"""++import pytest+import requests+from bs4 import BeautifulSoup+import re+from urllib.parse import urljoin+++class TestHTMLAccessibility:+ """Test HTML structure for accessibility compliance"""++ @pytest.fixture+ def research_page_html(self, base_url):+ """Fetch the research page HTML"""+ response = requests.get(urljoin(base_url, "/research/"))+ response.raise_for_status()+ return BeautifulSoup(response.content, "html.parser")++ def test_form_has_proper_labels(self, research_page_html):+ """Test that all form inputs have proper labels"""+ soup = research_page_html++ # Find all input elements that should have labels+ inputs = soup.find_all(["input", "textarea", "select"])++ for input_element in inputs:+ input_id = input_element.get("id")+ input_type = input_element.get("type", "text")++ # Skip hidden inputs and buttons+ if input_type in ["hidden", "submit", "button"]:+ continue++ # Check for associated label+ if input_id:+ label = soup.find("label", {"for": input_id})+ assert label is not None, (+ f"Input with id '{input_id}' missing associated label"+ )++ def test_radio_button_structure(self, research_page_html):+ """Test that radio buttons are properly structured"""+ soup = research_page_html++ # Find radio button group+ radio_inputs = soup.find_all("input", {"name": "research_mode"})+ assert len(radio_inputs) == 2, (+ "Should have exactly 2 research mode radio buttons"+ )++ # Check that radio buttons have proper IDs and labels+ expected_modes = ["quick", "detailed"]+ for mode in expected_modes:+ radio = soup.find("input", {"id": f"mode-{mode}"})+ assert radio is not None, f"Missing radio button for {mode} mode"+ assert radio.get("type") == "radio", (+ f"Input for {mode} mode should be type='radio'"+ )+ assert radio.get("name") == "research_mode", (+ "Radio button should have name='research_mode'"+ )++ # Check associated label+ label = soup.find("label", {"for": f"mode-{mode}"})+ assert label is not None, (+ f"Missing label for {mode} mode radio button"+ )+ assert "mode-option" in label.get("class", []), (+ "Label should have mode-option class"+ )++ def test_fieldset_and_legend(self, research_page_html):+ """Test that radio button group has proper fieldset and legend"""+ soup = research_page_html++ fieldset = soup.find("fieldset")+ assert fieldset is not None, (+ "Radio button group should be wrapped in fieldset"+ )++ legend = fieldset.find("legend")+ assert legend is not None, "Fieldset should have a legend"+ assert "Research Mode" in legend.get_text(), (+ "Legend should describe the radio button group"+ )++ def test_aria_attributes(self, research_page_html):+ """Test that ARIA attributes are properly set"""+ soup = research_page_html++ # Check radiogroup role+ radiogroup = soup.find(attrs={"role": "radiogroup"})+ assert radiogroup is not None, (+ "Should have element with role='radiogroup'"+ )++ # Check radio labels have proper ARIA attributes+ radio_labels = soup.find_all("label", class_="mode-option")+ assert len(radio_labels) >= 2, "Should have at least 2 radio labels"++ for label in radio_labels:+ assert label.get("role") == "radio", (+ "Label should have role='radio'"+ )+ assert "aria-checked" in label.attrs, (+ "Label should have aria-checked attribute"+ )+ assert "tabindex" in label.attrs, (+ "Label should have tabindex attribute"+ )++ # Check that one radio is initially checked+ checked_labels = [+ label+ for label in radio_labels+ if label.get("aria-checked") == "true"+ ]+ assert len(checked_labels) == 1, (+ "Exactly one radio should be initially checked"+ )++ def test_screen_reader_only_class(self, research_page_html):+ """Test that radio inputs have screen reader only class"""+ soup = research_page_html++ radio_inputs = soup.find_all("input", {"name": "research_mode"})+ for radio in radio_inputs:+ classes = radio.get("class", [])+ assert "sr-only" in classes, (+ "Radio inputs should have sr-only class"+ )++ def test_keyboard_hints_present(self, research_page_html):+ """Test that keyboard hint text is present"""+ soup = research_page_html++ hint_container = soup.find(class_="search-hints")+ assert hint_container is not None, "Should have search hints container"++ hint_texts = hint_container.find_all(class_="hint-text")+ assert len(hint_texts) >= 2, "Should have at least 2 hint text elements"++ # Get all hint text content+ all_hints = " ".join([hint.get_text() for hint in hint_texts])+ assert "Enter to search" in all_hints, "Should mention Enter key"+ assert "Shift+Enter for new line" in all_hints, (+ "Should mention Shift+Enter for new line"+ )++ def test_icons_have_aria_hidden(self, research_page_html):+ """Test that decorative icons have aria-hidden attribute"""+ soup = research_page_html++ # Find icons in mode options+ mode_icons = soup.find_all(class_="mode-icon")+ for icon_container in mode_icons:+ icon = icon_container.find("i")+ if icon:+ assert icon.get("aria-hidden") == "true", (+ "Decorative icons should have aria-hidden='true'"+ )++ def test_form_structure(self, research_page_html):+ """Test overall form structure and accessibility"""+ soup = research_page_html++ # Find the main form+ form = soup.find("form", {"id": "research-form"})+ assert form is not None, "Should have main research form"++ # Check that form has proper method (should be handled by JS)+ # Form should not have action attribute as it's handled by JavaScript+ assert form.get("action") is None, (+ "Form should not have action attribute (handled by JS)"+ )++ def test_heading_structure(self, research_page_html):+ """Test that headings follow proper hierarchy"""+ soup = research_page_html++ # Find all headings+ headings = soup.find_all(re.compile(r"^h[1-6]$"))++ if headings:+ # Check that we start with h1 or h2 (allowing for page structure)+ first_heading_level = int(headings[0].name[1])+ assert first_heading_level <= 2, "First heading should be h1 or h2"++ # Check for logical progression (no skipping levels)+ prev_level = first_heading_level+ for heading in headings[1:]:+ current_level = int(heading.name[1])+ # Level can stay same, go up by 1, or go down any amount+ if current_level > prev_level:+ assert current_level <= prev_level + 1, (+ f"Heading level jumped from h{prev_level} to h{current_level}"+ )+ prev_level = current_level++ def test_semantic_markup(self, research_page_html):+ """Test that semantic HTML elements are used appropriately"""+ soup = research_page_html++ # Check for semantic landmarks+ main_content = soup.find(+ ["main", "div"], class_=re.compile(r"(content|main)")+ )+ assert main_content is not None, "Should have main content area"++ # Check that buttons are actually button elements+ submit_button = soup.find("button", {"id": "start-research-btn"})+ assert submit_button is not None, "Submit should be a button element"+ assert submit_button.get("type") == "submit", (+ "Submit button should have type='submit'"+ )++ def test_required_fields_marked(self, research_page_html):+ """Test that required fields are properly marked"""+ soup = research_page_html++ # The query textarea should be required (if it has required attribute)+ query_field = soup.find("textarea", {"id": "query"})+ assert query_field is not None, "Should have query textarea"++ # If required attribute is present, it should be properly marked+ if query_field.get("required"):+ # Should have aria-required or required attribute+ assert query_field.get(+ "aria-required"+ ) == "true" or query_field.has_attr("required"), (+ "Required fields should be marked with aria-required or required attribute"+ )++ def test_error_handling_structure(self, research_page_html):+ """Test that error display areas are properly structured"""+ soup = research_page_html++ # Check for alert container+ alert_container = soup.find("div", {"id": "research-alert"})+ assert alert_container is not None, (+ "Should have alert container for error messages"+ )++ # Container should have proper ARIA role or be ready for dynamic content+ # When alerts are shown, they should have role="alert" or aria-live region+++class TestAccessibilityConfiguration:+ """Test accessibility-related configuration and setup"""++ def test_html_lang_attribute(self, base_url):+ """Test that HTML has proper lang attribute"""+ response = requests.get(urljoin(base_url, "/research/"))+ response.raise_for_status()+ soup = BeautifulSoup(response.content, "html.parser")++ html_element = soup.find("html")+ assert html_element is not None, "Should have html element"++ lang = html_element.get("lang")+ assert lang is not None, "HTML element should have lang attribute"+ assert lang.startswith("en"), "Language should be English (en)"++ def test_viewport_meta_tag(self, base_url):+ """Test that viewport meta tag is present for mobile accessibility"""+ response = requests.get(urljoin(base_url, "/research/"))+ response.raise_for_status()+ soup = BeautifulSoup(response.content, "html.parser")++ viewport_meta = soup.find("meta", {"name": "viewport"})+ assert viewport_meta is not None, "Should have viewport meta tag"++ content = viewport_meta.get("content", "")+ assert "width=device-width" in content, (+ "Viewport should include width=device-width"+ )+ assert "initial-scale=1" in content, (+ "Viewport should include initial-scale=1"+ )++ def test_css_focus_styles(self, base_url):+ """Test that CSS includes focus styles (basic check)"""+ # This is a basic test - ideally we'd parse CSS files+ # For now, we just check that custom CSS files are loaded+ response = requests.get(urljoin(base_url, "/research/"))+ response.raise_for_status()+ soup = BeautifulSoup(response.content, "html.parser")++ css_links = soup.find_all("link", {"rel": "stylesheet"})+ css_hrefs = [link.get("href", "") for link in css_links]++ # Check that our custom CSS file is loaded+ custom_css_loaded = any(+ "custom_dropdown.css" in href for href in css_hrefs+ )+ assert custom_css_loaded, "Custom dropdown CSS should be loaded"+++def base_url():+ """Base URL for the application"""+ # This should be configured based on your test environment+ import os++ return os.getenv("TEST_BASE_URL", "http://localhost:5000")+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])