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.

Complete error explanation system with 3-tier priority

LearningCircuitb403f8b6eb50
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 1d830f8112..4796998d95 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -399,15 +399,15 @@ def get_llm(
)
# Log the actual client configuration after creation
- logger.info(f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}")
+ logger.debug(f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}")
if hasattr(llm, '_client'):
client = llm._client
- logger.info(f"ChatOllama _client type: {type(client)}")
+ logger.debug(f"ChatOllama _client type: {type(client)}")
if hasattr(client, '_client'):
inner_client = client._client
- logger.info(f"ChatOllama inner client type: {type(inner_client)}")
+ logger.debug(f"ChatOllama inner client type: {type(inner_client)}")
if hasattr(inner_client, 'base_url'):
- logger.info(f"ChatOllama inner client base_url: {inner_client.base_url}")
+ logger.debug(f"ChatOllama inner client base_url: {inner_client.base_url}")
# Test invoke to validate model works
logger.info("Testing Ollama model with simple invocation")
@@ -559,24 +559,24 @@ def wrap_llm_without_think_tags(
def invoke(self, *args, **kwargs):
# Log detailed request information for Ollama models
if hasattr(self.base_llm, 'base_url'):
- logger.info(f"LLM Request - Base URL: {self.base_llm.base_url}")
- logger.info(f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}")
- logger.info(f"LLM Request - Args count: {len(args)}, Kwargs: {list(kwargs.keys())}")
+ 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.info(f"LLM Request - Prompt preview: {prompt_text}")
+ 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.info(f"LLM Request - Client base URL: {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.info(f"LLM Response - Success, type: {type(response)}")
+ 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
diff --git a/src/local_deep_research/error_handling/llm_explainer.py b/src/local_deep_research/error_handling/llm_explainer.py
index ef3fa018b8..bbac54a369 100644
--- a/src/local_deep_research/error_handling/llm_explainer.py
+++ b/src/local_deep_research/error_handling/llm_explainer.py
@@ -61,7 +61,7 @@ class LLMExplainer:
def generate_explanation(self, error_analysis: Dict[str, Any]) -> str:
"""
- Generate a helpful explanation for an error
+ Generate a helpful explanation for an error - Priority: specific patterns -> LLM -> category templates
Args:
error_analysis: Error analysis from ErrorReporter
@@ -73,7 +73,12 @@ class LLMExplainer:
original_error = error_analysis.get("original_error", "")
context = error_analysis.get("context", {})
- # Try to use LLM for explanation if available
+ # Priority 1: Check for specific known error patterns first
+ specific_explanation = self._get_specific_error_explanation(original_error)
+ if specific_explanation:
+ return specific_explanation
+
+ # Priority 2: Try LLM for unknown/complex errors
if self.llm:
try:
llm_explanation = self._generate_llm_explanation(category, original_error, context)
@@ -82,8 +87,8 @@ class LLMExplainer:
except Exception as e:
logger.warning(f"Failed to generate LLM explanation: {e}")
- # Fallback to template-based explanation
- return self._get_template_explanation(category, error_analysis)
+ # Priority 3: Simple fallback
+ return "An unexpected error occurred during your research. Check the technical details below for more information."
def _generate_llm_explanation(self, category: ErrorCategory, error_message: str, context: Dict[str, Any]) -> Optional[str]:
"""
@@ -98,19 +103,31 @@ class LLMExplainer:
Optional[str]: LLM-generated explanation
"""
try:
- # Prepare prompt for LLM
+ # Prepare prompt for LLM with category context
+ category_hint = ""
+ if category:
+ category_hints = {
+ ErrorCategory.CONNECTION_ERROR: "This appears to be a connection or network issue with the AI service",
+ ErrorCategory.MODEL_ERROR: "This seems to be related to AI model configuration or availability",
+ ErrorCategory.SEARCH_ERROR: "This looks like an issue with the search functionality",
+ ErrorCategory.SYNTHESIS_ERROR: "This appears to be a problem during report generation",
+ ErrorCategory.FILE_ERROR: "This seems to be a file system or permissions issue",
+ ErrorCategory.UNKNOWN_ERROR: "This is an unexpected error that needs analysis"
+ }
+ category_hint = category_hints.get(category, "")
+
prompt = f"""
You are helping a user understand what went wrong with their research process.
Please provide a brief, friendly, and helpful explanation of this error.
-Error Category: {category.value}
+Error Type: {category_hint}
Technical Error: {error_message}
-Context: {context}
+Research Context: {context}
Please explain:
1. What happened in simple terms
-2. Why this might have occurred
-3. That partial results may still be available
+2. Why this might have occurred
+3. That partial results may still be available if applicable
4. Reassurance that this can usually be fixed
Keep it concise, helpful, and friendly. Avoid technical jargon.
diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.py
index 3a47b0afdb..38e9b618c8 100644
--- a/src/local_deep_research/error_handling/report_generator.py
+++ b/src/local_deep_research/error_handling/report_generator.py
@@ -72,6 +72,15 @@ class ErrorReportGenerator:
report_parts.append(f"\n**What happened:** {user_friendly_message}")
report_parts.append(f"\n*For detailed error information, scroll down to the research logs and select \"Errors\" from the filter.*")
+ # Add the explanation (either template-based or LLM-generated)
+ if explanation and explanation.strip():
+ report_parts.append(f"\n## Understanding the Error\n")
+ report_parts.append(explanation)
+
+ # Add quick tip if available
+ if quick_tip:
+ report_parts.append(f"\n{quick_tip}")
+
# Support links - moved up for better visibility
report_parts.append(f"\n## 💬 Get Help")
report_parts.append("We're here to help you get this working:")
diff --git a/tests/accessibility_tests/README.md b/tests/accessibility_tests/README.md
new file mode 100644
index 0000000000..f1461c8101
--- /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)
\ No newline at end of file
diff --git a/tests/accessibility_tests/__init__.py b/tests/accessibility_tests/__init__.py
new file mode 100644
index 0000000000..127f06b784
--- /dev/null
+++ b/tests/accessibility_tests/__init__.py
@@ -0,0 +1 @@
+# Accessibility Tests Module
\ No newline at end of file
diff --git a/tests/accessibility_tests/test_accessibility.js b/tests/accessibility_tests/test_accessibility.js
new file mode 100644
index 0000000000..63a1b03678
--- /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);
+ }
+ });
+});
\ No newline at end of file
diff --git a/tests/accessibility_tests/test_accessibility_backend.py b/tests/accessibility_tests/test_accessibility_backend.py
new file mode 100644
index 0000000000..27ad0425f0
--- /dev/null
+++ b/tests/accessibility_tests/test_accessibility_backend.py
@@ -0,0 +1,256 @@
+"""
+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', f"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', []), f"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 = [l for l in radio_labels if l.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_='keyboard-hint')
+ assert hint_container is not None, "Should have keyboard hint container"
+
+ hint_text = hint_container.find(class_='hint-text')
+ assert hint_text is not None, "Should have hint text element"
+
+ hint_content = hint_text.get_text()
+ assert 'Enter to search' in hint_content, "Should mention Enter key"
+ assert 'Shift+Enter for new line' in hint_content, "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'])
\ No newline at end of file