~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
fix: Restore iteration and questions controls in research UI
LearningCircuit76f370f51f51
diff --git a/.github/workflows/followup-research-tests.yml b/.github/workflows/followup-research-tests.ymlnew file mode 100644index 0000000000..897036647e--- /dev/null+++ b/.github/workflows/followup-research-tests.yml@@ -0,0 +1,120 @@+name: Follow-up Research Tests++on:+ push:+ paths:+ - 'src/local_deep_research/followup_research/**'+ - 'src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py'+ - 'src/local_deep_research/search_system.py'+ - 'tests/test_followup_api.py'+ - 'tests/ui_tests/test_followup_research.js'+ - '.github/workflows/followup-research-tests.yml'+ pull_request:+ types: [opened, synchronize, reopened]+ paths:+ - 'src/local_deep_research/followup_research/**'+ - 'src/local_deep_research/advanced_search_system/strategies/contextual_followup_strategy.py'+ - 'tests/test_followup_api.py'+ - 'tests/ui_tests/test_followup_research.js'++jobs:+ test-followup-research:+ runs-on: ubuntu-latest+ timeout-minutes: 30++ steps:+ - uses: actions/checkout@v4++ - name: Set up Python+ uses: actions/setup-python@v5+ with:+ python-version: '3.11'++ - name: Install PDM+ uses: pdm-project/setup-pdm@v3+ with:+ python-version: '3.11'+ cache: true++ - name: Install Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '18'++ - name: Install dependencies+ run: |+ pdm sync -d+ cd tests/ui_tests && npm install++ - name: Install browser+ run: |+ npx playwright install chromium++ - name: Create test directories+ run: |+ mkdir -p data+ mkdir -p tests/ui_tests/screenshots/followup+ mkdir -p tests/ui_tests/results/followup++ - name: Start server+ env:+ FLASK_ENV: testing+ TESTING: true+ SECRET_KEY: test-secret-key+ DATABASE_URL: sqlite:///test.db+ run: |+ cd src+ nohup pdm run python -m local_deep_research.web.app --port 5000 > ../server.log 2>&1 &+ echo $! > ../server.pid+ sleep 10+ curl -f http://127.0.0.1:5000 || (cat ../server.log && exit 1)++ - name: Run API tests+ run: |+ pdm run pytest tests/test_followup_api.py -v --tb=short++ - name: Run UI tests+ env:+ HEADLESS: true+ DISPLAY: ':99'+ run: |+ export DISPLAY=:99+ cd tests/ui_tests++ # Run follow-up research UI test+ timeout 300 node test_followup_research.js || {+ echo "Follow-up research test failed or timed out"+ exit 1+ }++ - name: Upload screenshots+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: followup-test-screenshots+ path: tests/ui_tests/screenshots/followup/++ - name: Upload test results+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: followup-test-results+ path: |+ tests/ui_tests/results/followup/+ server.log++ - name: Stop server+ if: always()+ run: |+ if [ -f server.pid ]; then+ kill $(cat server.pid) || true+ fi++ - name: Test Summary+ if: always()+ run: |+ echo "Follow-up Research Tests completed"+ echo "API tests and UI tests have been executed"+ if [ -f tests/ui_tests/results/followup/test_report.json ]; then+ cat tests/ui_tests/results/followup/test_report.json+ fidiff --git a/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py b/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.pyindex 952eec35ee..6e265ffbed 100644--- a/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py+++ b/src/local_deep_research/advanced_search_system/query_generation/followup_query_reformulator.py@@ -172,8 +172,8 @@ Return only the search query, no explanation.return queryreturn reformulated- except Exception as e:- logger.error(f"Failed to combine query with findings: {e}")+ except Exception:+ logger.exception("Failed to combine query with findings")# Fallback: combine query with key conceptsif key_concepts:return f"{query} {' '.join(key_concepts[:2])}"diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.pyindex 356348b58e..becfd83840 100644--- a/src/local_deep_research/followup_research/routes.py+++ b/src/local_deep_research/followup_research/routes.py@@ -103,7 +103,7 @@ def prepare_followup():return jsonify(response)except Exception as e:- logger.error(f"Error preparing follow-up: {e}")+ logger.exception("Error preparing follow-up")return jsonify({"success": False, "error": str(e)}), 500@@ -282,7 +282,7 @@ def start_followup():"llm.openai_endpoint.url", {}).get("value")- research_thread = start_research_process(+ start_research_process(research_id,research_params["query"],"quick", # Use 'quick' for quick summary mode@@ -317,8 +317,5 @@ def start_followup():)except Exception as e:- import traceback-- logger.error(f"Error starting follow-up: {e}")- logger.error(f"Traceback: {traceback.format_exc()}")+ logger.exception("Error starting follow-up")return jsonify({"success": False, "error": str(e)}), 500diff --git a/src/local_deep_research/followup_research/service.py b/src/local_deep_research/followup_research/service.pyindex 084faae1fe..fb9183498d 100644--- a/src/local_deep_research/followup_research/service.py+++ b/src/local_deep_research/followup_research/service.py@@ -127,8 +127,8 @@ class FollowUpResearchService:return parent_data- except Exception as e:- logger.error(f"Error loading parent research: {e}")+ except Exception:+ logger.exception("Error loading parent research")return {}def prepare_research_context(diff --git a/src/local_deep_research/web/services/research_sources_service.py b/src/local_deep_research/web/services/research_sources_service.pyindex 385f2c3526..f658a22641 100644--- a/src/local_deep_research/web/services/research_sources_service.py+++ b/src/local_deep_research/web/services/research_sources_service.py@@ -105,8 +105,8 @@ class ResearchSourcesService:f"Saved {saved_count} sources for research {research_id}")- except Exception as e:- logger.error(f"Error saving research sources: {e}")+ except Exception:+ logger.exception("Error saving research sources")raisereturn saved_count@@ -154,8 +154,8 @@ class ResearchSourcesService:f"Retrieved {len(sources)} sources for research {research_id}")- except Exception as e:- logger.error(f"Error retrieving research sources: {e}")+ except Exception:+ logger.exception("Error retrieving research sources")raisereturn sources@@ -218,8 +218,8 @@ class ResearchSourcesService:f"Copied {copied_count} sources from {from_research_id} to {to_research_id}")- except Exception as e:- logger.error(f"Error copying research sources: {e}")+ except Exception:+ logger.exception("Error copying research sources")raisereturn copied_count@@ -275,6 +275,6 @@ class ResearchSourcesService:)return False- except Exception as e:- logger.error(f"Error updating research with sources: {e}")+ except Exception:+ logger.exception("Error updating research with sources")return Falsediff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 2a96d6529b..d96444d929 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -665,6 +665,25 @@});}+ // Iterations change - save to settings manager+ const iterationsInput = document.getElementById('iterations');+ if (iterationsInput) {+ iterationsInput.addEventListener('change', function() {+ const iterations = parseInt(this.value);+ console.log('Iterations changed to:', iterations);+ saveSearchSetting('search.iterations', iterations);+ });+ }++ // Questions per iteration change - save to settings manager+ const questionsInput = document.getElementById('questions_per_iteration');+ if (questionsInput) {+ questionsInput.addEventListener('change', function() {+ const questions = parseInt(this.value);+ console.log('Questions per iteration changed to:', questions);+ saveSearchSetting('search.questions_per_iteration', questions);+ });+ }// Load options data from APIsPromise.all([@@ -2057,6 +2076,12 @@const strategySelect = document.getElementById('strategy');const strategy = strategySelect ? strategySelect.value : 'source-based';+ // Get iterations and questions per iteration+ const iterationsInput = document.getElementById('iterations');+ const iterations = iterationsInput ? parseInt(iterationsInput.value) : 2;+ const questionsInput = document.getElementById('questions_per_iteration');+ const questionsPerIteration = questionsInput ? parseInt(questionsInput.value) : 3;+// Validate the queryif (!query) {// Show error if query is empty@@ -2081,7 +2106,9 @@model: model,custom_endpoint: customEndpoint,search_engine: searchEngine,- strategy: strategy+ strategy: strategy,+ iterations: iterations,+ questions_per_iteration: questionsPerIteration};console.log('Submitting research with data:', formData);diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 1155543fe9..7e2972136b 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -126,6 +126,21 @@</div></div>+ <div class="form-row">+ <!-- Search Iterations -->+ <div class="form-group half">+ <label for="iterations">Search Iterations</label>+ <input type="number" id="iterations" name="iterations" class="form-control" min="1" max="5" value="{{ settings.search_iterations }}">+ <span class="input-help">Number of research cycles to perform</span>+ </div>++ <!-- Questions Per Iteration -->+ <div class="form-group half">+ <label for="questions_per_iteration">Questions Per Iteration</label>+ <input type="number" id="questions_per_iteration" name="questions_per_iteration" class="form-control" min="1" max="10" value="{{ settings.search_questions_per_iteration }}">+ <span class="input-help">Follow-up questions in each cycle</span>+ </div>+ </div><div class="form-row"><!-- Search Strategy -->diff --git a/tests/run_followup_tests.sh b/tests/run_followup_tests.shnew file mode 100755index 0000000000..28afb3fbbb--- /dev/null+++ b/tests/run_followup_tests.sh@@ -0,0 +1,120 @@+#!/bin/bash+# Script to run follow-up research tests locally++echo "🚀 Running Follow-up Research Tests"+echo "===================================="++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m' # No Color++# Check if server is running+check_server() {+ curl -s -f http://127.0.0.1:5000 > /dev/null 2>&1+ return $?+}++# Start server if not running+if ! check_server; then+ echo -e "${YELLOW}Starting local server...${NC}"+ cd src+ nohup python -m local_deep_research.web.app --port 5000 > ../server_test.log 2>&1 &+ SERVER_PID=$!+ cd ..++ # Wait for server to start+ for i in {1..30}; do+ if check_server; then+ echo -e "${GREEN}Server started successfully${NC}"+ break+ fi+ sleep 1+ done++ if ! check_server; then+ echo -e "${RED}Failed to start server${NC}"+ cat server_test.log+ exit 1+ fi+else+ echo -e "${GREEN}Server already running${NC}"+ SERVER_PID=""+fi++# Create test directories+mkdir -p tests/ui_tests/screenshots/followup+mkdir -p tests/ui_tests/results/followup++# Run API tests+echo ""+echo "📝 Running API Tests..."+echo "----------------------"+pdm run pytest tests/test_followup_api.py -v --tb=short+API_EXIT_CODE=$?++if [ $API_EXIT_CODE -eq 0 ]; then+ echo -e "${GREEN}✓ API tests passed${NC}"+else+ echo -e "${RED}✗ API tests failed${NC}"+fi++# Run UI tests+echo ""+echo "🖥️ Running UI Tests..."+echo "---------------------"+cd tests/ui_tests++# Install npm dependencies if needed+if [ ! -d "node_modules" ]; then+ echo "Installing npm dependencies..."+ npm install+fi++# Run the follow-up research test+HEADLESS=false timeout 300 node test_followup_research.js+UI_EXIT_CODE=$?++cd ../..++if [ $UI_EXIT_CODE -eq 0 ]; then+ echo -e "${GREEN}✓ UI tests passed${NC}"+else+ echo -e "${RED}✗ UI tests failed or timed out${NC}"+fi++# Stop server if we started it+if [ ! -z "$SERVER_PID" ]; then+ echo ""+ echo "Stopping test server..."+ kill $SERVER_PID 2>/dev/null+fi++# Summary+echo ""+echo "===================================="+echo "Test Summary:"+echo "===================================="+if [ $API_EXIT_CODE -eq 0 ]; then+ echo -e "${GREEN}✓ API Tests: PASSED${NC}"+else+ echo -e "${RED}✗ API Tests: FAILED${NC}"+fi++if [ $UI_EXIT_CODE -eq 0 ]; then+ echo -e "${GREEN}✓ UI Tests: PASSED${NC}"+else+ echo -e "${RED}✗ UI Tests: FAILED${NC}"+fi++# Exit with error if any test failed+if [ $API_EXIT_CODE -ne 0 ] || [ $UI_EXIT_CODE -ne 0 ]; then+ echo ""+ echo -e "${RED}Some tests failed. Please check the output above.${NC}"+ exit 1+else+ echo ""+ echo -e "${GREEN}All tests passed successfully! 🎉${NC}"+ exit 0+fidiff --git a/tests/test_followup_api.py b/tests/test_followup_api.pynew file mode 100644index 0000000000..2dc72f3214--- /dev/null+++ b/tests/test_followup_api.py@@ -0,0 +1,342 @@+"""+API tests for the Follow-up Research feature.++Tests the API endpoints for preparing and starting follow-up research.+"""++import json+import uuid+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.database.models import (+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.followup_research.models import FollowUpRequest+from local_deep_research.followup_research.service import (+ FollowUpResearchService,+)+++class TestFollowUpAPI:+ """Test suite for follow-up research API endpoints."""++ @pytest.fixture+ def app(self):+ """Create test Flask app."""+ from local_deep_research.web.app_factory import create_app++ app = create_app(testing=True)+ app.config["TESTING"] = True+ app.config["WTF_CSRF_ENABLED"] = False+ return app++ @pytest.fixture+ def client(self, app):+ """Create test client."""+ return app.test_client()++ @pytest.fixture+ def authenticated_client(self, client, app):+ """Create authenticated test client."""+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["authenticated"] = True+ return client++ @pytest.fixture+ def mock_research_data(self):+ """Mock parent research data."""+ research_id = str(uuid.uuid4())+ return {+ "research_id": research_id,+ "research": ResearchHistory(+ id=research_id,+ query="What is quantum computing?",+ mode="quick_summary",+ status="completed",+ created_at="2024-01-01 10:00:00",+ report_content="Quantum computing uses quantum bits...",+ formatted_findings="Key findings about quantum computing...",+ strategy_name="source-based",+ ),+ "resources": [+ ResearchResource(+ research_id=research_id,+ title="Introduction to Quantum Computing",+ url="https://example.com/quantum",+ content_preview="Quantum computing is a revolutionary...",+ source_type="web",+ ),+ ResearchResource(+ research_id=research_id,+ title="Quantum Gates Explained",+ url="https://example.com/gates",+ content_preview="Quantum gates are the building blocks...",+ source_type="web",+ ),+ ],+ }++ def test_prepare_followup_success(+ self, authenticated_client, mock_research_data+ ):+ """Test successful preparation of follow-up research."""+ with patch(+ "local_deep_research.followup_research.routes.FollowUpResearchService"+ ) as MockService:+ # Setup mock+ mock_service = MockService.return_value+ mock_service.load_parent_research.return_value = {+ "query": mock_research_data["research"].query,+ "resources": [+ {+ "url": r.url,+ "title": r.title,+ "content_preview": r.content_preview,+ "source_type": r.source_type,+ }+ for r in mock_research_data["resources"]+ ],+ }++ # Make request+ response = authenticated_client.post(+ "/api/followup/prepare",+ json={+ "parent_research_id": mock_research_data["research_id"],+ "question": "How do quantum gates work?",+ },+ )++ # Verify response+ assert response.status_code == 200+ data = json.loads(response.data)+ assert data["success"] is True+ assert data["parent_summary"] == "What is quantum computing?"+ assert data["available_sources"] == 2+ assert data["suggested_strategy"] == "source-based"++ def test_prepare_followup_missing_params(self, authenticated_client):+ """Test prepare endpoint with missing parameters."""+ response = authenticated_client.post(+ "/api/followup/prepare", json={"question": "Test question"}+ )++ assert response.status_code == 400+ data = json.loads(response.data)+ assert data["success"] is False+ assert "Missing parent_research_id" in data["error"]++ def test_prepare_followup_not_found(self, authenticated_client):+ """Test prepare endpoint with non-existent parent research."""+ with patch(+ "local_deep_research.followup_research.routes.FollowUpResearchService"+ ) as MockService:+ mock_service = MockService.return_value+ mock_service.load_parent_research.return_value = {}++ response = authenticated_client.post(+ "/api/followup/prepare",+ json={+ "parent_research_id": "non-existent-id",+ "question": "Test question",+ },+ )++ assert response.status_code == 404+ data = json.loads(response.data)+ assert data["success"] is False+ assert "not found" in data["error"]++ def test_start_followup_success(+ self, authenticated_client, mock_research_data+ ):+ """Test successful start of follow-up research."""+ with (+ patch(+ "local_deep_research.followup_research.routes.FollowUpResearchService"+ ) as MockService,+ patch(+ "local_deep_research.followup_research.routes.perform_research_task"+ ) as mock_perform,+ ):+ # Setup mock+ mock_service = MockService.return_value+ mock_service.perform_followup.return_value = {+ "query": "How do quantum gates work?",+ "strategy": "contextual-followup",+ "delegate_strategy": "source-based",+ "max_iterations": 1,+ "questions_per_iteration": 3,+ "research_context": {+ "parent_research_id": mock_research_data["research_id"],+ "past_links": [],+ "past_findings": "",+ },+ }++ # Make request+ response = authenticated_client.post(+ "/api/followup/start",+ json={+ "parent_research_id": mock_research_data["research_id"],+ "question": "How do quantum gates work?",+ "strategy": "source-based",+ "max_iterations": 1,+ "questions_per_iteration": 3,+ },+ )++ # Verify response+ assert response.status_code == 200+ data = json.loads(response.data)+ assert data["success"] is True+ assert "research_id" in data+ assert data["message"] == "Follow-up research started"++ # Verify perform_research_task was called+ mock_perform.assert_called_once()++ def test_start_followup_unauthorized(self, client):+ """Test start endpoint without authentication."""+ response = client.post(+ "/api/followup/start",+ json={"parent_research_id": "test-id", "question": "Test question"},+ )++ # Should redirect to login or return 401+ assert response.status_code in [302, 401]++ def test_followup_service_load_parent(self, mock_research_data):+ """Test FollowUpResearchService.load_parent_research method."""+ with patch(+ "local_deep_research.followup_research.service.get_user_db_session"+ ) as mock_session:+ # Setup mock database session+ mock_db = MagicMock()+ mock_session.return_value.__enter__.return_value = mock_db++ # Setup query results+ mock_db.query.return_value.filter_by.return_value.first.return_value = mock_research_data[+ "research"+ ]+ mock_db.query.return_value.filter_by.return_value.all.return_value = mock_research_data[+ "resources"+ ]++ # Test service+ service = FollowUpResearchService(username="testuser")+ result = service.load_parent_research(+ mock_research_data["research_id"]+ )++ # Verify result+ assert result["research_id"] == mock_research_data["research_id"]+ assert result["query"] == "What is quantum computing?"+ assert len(result["resources"]) == 2+ assert len(result["all_links_of_system"]) == 2++ def test_followup_service_prepare_context(self, mock_research_data):+ """Test FollowUpResearchService.prepare_research_context method."""+ with patch.object(+ FollowUpResearchService, "load_parent_research"+ ) as mock_load:+ # Setup mock+ mock_load.return_value = {+ "query": mock_research_data["research"].query,+ "formatted_findings": mock_research_data[+ "research"+ ].formatted_findings,+ "report_content": mock_research_data["research"].report_content,+ "resources": [+ {+ "url": r.url,+ "title": r.title,+ "content_preview": r.content_preview,+ "source_type": r.source_type,+ }+ for r in mock_research_data["resources"]+ ],+ "all_links_of_system": [+ {+ "url": r.url,+ "title": r.title,+ "snippet": r.content_preview,+ }+ for r in mock_research_data["resources"]+ ],+ }++ # Test service+ service = FollowUpResearchService(username="testuser")+ context = service.prepare_research_context(+ mock_research_data["research_id"]+ )++ # Verify context+ assert (+ context["parent_research_id"]+ == mock_research_data["research_id"]+ )+ assert len(context["past_links"]) == 2+ assert (+ context["past_findings"]+ == mock_research_data["research"].formatted_findings+ )+ assert context["original_query"] == "What is quantum computing?"++ def test_followup_request_model(self):+ """Test FollowUpRequest model."""+ request = FollowUpRequest(+ parent_research_id="test-id",+ question="How does it work?",+ strategy="source-based",+ max_iterations=2,+ questions_per_iteration=5,+ )++ # Test to_dict+ data = request.to_dict()+ assert data["parent_research_id"] == "test-id"+ assert data["question"] == "How does it work?"+ assert data["strategy"] == "source-based"+ assert data["max_iterations"] == 2+ assert data["questions_per_iteration"] == 5++ def test_contextual_strategy_registration(self):+ """Test that contextual-followup strategy is properly registered."""+ from local_deep_research.search_system import AdvancedSearchSystem++ with (+ patch("local_deep_research.search_system.get_llm") as mock_llm,+ patch(+ "local_deep_research.search_system.get_search"+ ) as mock_search,+ ):+ # Setup mocks+ mock_llm.return_value = MagicMock()+ mock_search.return_value = MagicMock()++ # Create system with contextual-followup strategy+ research_context = {+ "delegate_strategy": "source-based",+ "past_links": [],+ "past_findings": "",+ }++ system = AdvancedSearchSystem(+ llm=mock_llm.return_value,+ search=mock_search.return_value,+ strategy_name="contextual-followup",+ research_context=research_context,+ )++ # Verify strategy type+ from local_deep_research.advanced_search_system.strategies.contextual_followup_strategy import (+ ContextualFollowUpStrategy,+ )++ assert isinstance(system.strategy, ContextualFollowUpStrategy)diff --git a/tests/test_followup_manual.py b/tests/test_followup_manual.pynew file mode 100644index 0000000000..dbf317a04f--- /dev/null+++ b/tests/test_followup_manual.py@@ -0,0 +1,77 @@+#!/usr/bin/env python3+"""+Manual test script for follow-up research feature.+Run this after starting the server to verify the API works.+"""++import requests+import json++BASE_URL = "http://127.0.0.1:5000"+++def test_followup_api():+ """Test the follow-up research API endpoints."""++ # Create a session to maintain cookies+ session = requests.Session()++ print("🔐 Testing authentication...")+ # First, try to login (or register if needed)+ auth_response = session.post(+ f"{BASE_URL}/auth/login",+ data={"username": "testuser", "password": "T3st!Secure#2024$LDR"},+ )++ if auth_response.status_code == 302: # Redirect after successful login+ print("✅ Authenticated successfully")+ else:+ print(f"⚠️ Auth returned status: {auth_response.status_code}")+ # Try registration+ reg_response = session.post(+ f"{BASE_URL}/auth/register",+ data={+ "username": "testuser",+ "password": "T3st!Secure#2024$LDR",+ "confirm_password": "T3st!Secure#2024$LDR",+ "acknowledge": "on",+ },+ )+ if reg_response.status_code == 302:+ print("✅ Registered and authenticated")+ else:+ print(f"❌ Registration failed: {reg_response.status_code}")+ return++ print("\n📝 Testing /api/followup/prepare endpoint...")++ # Test with a dummy parent research ID+ prepare_data = {+ "parent_research_id": "test-parent-id",+ "question": "How does this work in more detail?",+ }++ prepare_response = session.post(+ f"{BASE_URL}/api/followup/prepare",+ json=prepare_data,+ headers={"Content-Type": "application/json"},+ )++ print(f"Response status: {prepare_response.status_code}")+ if prepare_response.status_code == 200:+ print(f"Response data: {json.dumps(prepare_response.json(), indent=2)}")+ else:+ print(f"Response text: {prepare_response.text[:500]}")++ print("\n✅ API endpoint is accessible!")++ # Test if the button exists on a results page+ print("\n🔍 Checking if follow-up button exists on UI...")+ # This would require actually having a completed research, so we'll skip for now+ print("⚠️ Skipping UI check (requires completed research)")++ print("\n🎉 Follow-up research API test completed!")+++if __name__ == "__main__":+ test_followup_api()diff --git a/tests/ui_tests/test_followup_api.js b/tests/ui_tests/test_followup_api.jsnew file mode 100644index 0000000000..4619a52211--- /dev/null+++ b/tests/ui_tests/test_followup_api.js@@ -0,0 +1,62 @@+const axios = require('axios');++async function testFollowupAPI() {+ try {+ console.log('Testing follow-up API directly...');++ // First login+ const loginRes = await axios.post('http://127.0.0.1:5000/auth/login', {+ username: 'testuser',+ password: 'testpass'+ }, {+ headers: { 'Content-Type': 'application/json' },+ withCredentials: true+ });++ const cookies = loginRes.headers['set-cookie'];+ console.log('Login successful, got cookies');++ // Test follow-up prepare endpoint+ console.log('Testing prepare endpoint...');+ const prepareRes = await axios.post('http://127.0.0.1:5000/api/followup/prepare', {+ parent_research_id: '175a78a1-a1ce-4a65-8507-167575babedf',+ question: 'test question'+ }, {+ headers: {+ 'Content-Type': 'application/json',+ 'Cookie': cookies.join('; ')+ }+ });++ console.log('Prepare response:', prepareRes.data);++ // Test follow-up start endpoint+ console.log('Testing start endpoint...');+ const startRes = await axios.post('http://127.0.0.1:5000/api/followup/start', {+ parent_research_id: '175a78a1-a1ce-4a65-8507-167575babedf',+ question: 'test question',+ strategy: 'source-based',+ max_iterations: 1,+ questions_per_iteration: 3+ }, {+ headers: {+ 'Content-Type': 'application/json',+ 'Cookie': cookies.join('; ')+ }+ });++ console.log('Start response:', startRes.data);+ console.log('Test completed successfully');++ } catch (error) {+ console.error('Test failed:', error.message);+ if (error.response) {+ console.error('Response data:', error.response.data);+ console.error('Response status:', error.response.status);+ }+ process.exit(1);+ }+}++// Run the test+testFollowupAPI().catch(console.error);diff --git a/tests/ui_tests/test_followup_research.js b/tests/ui_tests/test_followup_research.jsnew file mode 100644index 0000000000..59b675c28b--- /dev/null+++ b/tests/ui_tests/test_followup_research.js@@ -0,0 +1,318 @@+/**+ * UI Test for Follow-up Research Feature+ * Tests the complete flow of asking follow-up questions on research results+ */++const puppeteer = require('puppeteer');+const AuthHelper = require('./auth_helper');+const { getPuppeteerLaunchOptions } = require('./puppeteer_config');++// Test configuration+const BASE_URL = 'http://127.0.0.1:5000';+const TIMEOUT = 60000; // 60 seconds for research operations++// Colors for console output+const colors = {+ reset: '\x1b[0m',+ bright: '\x1b[1m',+ green: '\x1b[32m',+ red: '\x1b[31m',+ yellow: '\x1b[33m',+ blue: '\x1b[34m',+ cyan: '\x1b[36m'+};++function log(message, type = 'info') {+ const timestamp = new Date().toISOString().split('T')[1].split('.')[0];+ const typeColors = {+ 'info': colors.cyan,+ 'success': colors.green,+ 'error': colors.red,+ 'warning': colors.yellow,+ 'section': colors.blue+ };+ const color = typeColors[type] || colors.reset;+ console.log(`${color}[${timestamp}] ${message}${colors.reset}`);+}++async function delay(ms) {+ return new Promise(resolve => setTimeout(resolve, ms));+}++/**+ * Create a research and wait for it to complete+ */+async function createAndCompleteResearch(page, query) {+ log(`🔬 Creating research: "${query}"`, 'info');++ // Navigate to home page+ await page.goto(BASE_URL, { waitUntil: 'networkidle2' });++ // Wait for and fill the query input+ await page.waitForSelector('#query', { timeout: 10000 });+ await page.click('#query', { clickCount: 3 });+ await page.type('#query', query);++ // Select quick summary mode for faster testing+ const modeSelect = await page.$('#mode');+ if (modeSelect) {+ await page.select('#mode', 'quick_summary');+ }++ // Submit the research+ log('📤 Submitting research...', 'info');+ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }),+ page.click('button[type="submit"]')+ ]);++ // Wait for research to complete+ log('⏳ Waiting for research to complete...', 'info');+ const startTime = Date.now();++ while (Date.now() - startTime < TIMEOUT) {+ const url = page.url();++ // Check if we're on the results page+ if (url.includes('/results/')) {+ log('✅ Research completed, on results page', 'success');++ // Extract research ID from URL+ const match = url.match(/\/results\/([a-zA-Z0-9-]+)/);+ if (match) {+ return match[1];+ }+ break;+ }++ // Check if we're on progress page and research is complete+ if (url.includes('/progress/')) {+ const isComplete = await page.evaluate(() => {+ const statusEl = document.querySelector('.progress-status, .status-text');+ if (statusEl) {+ const text = statusEl.textContent.toLowerCase();+ return text.includes('completed') || text.includes('100%');+ }+ return false;+ });++ if (isComplete) {+ // Click view results button if available+ const viewResultsBtn = await page.$('a[href*="/results/"], button:has-text("View Results")');+ if (viewResultsBtn) {+ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }),+ viewResultsBtn.click()+ ]);+ }+ }+ }++ await delay(2000);+ }++ // Try to extract research ID from current URL+ const finalUrl = page.url();+ const match = finalUrl.match(/\/(results|progress)\/([a-zA-Z0-9-]+)/);+ return match ? match[2] : null;+}++/**+ * Test the follow-up research feature+ */+async function testFollowUpResearch() {+ let browser;+ let exitCode = 0;++ try {+ log('🚀 Starting Follow-up Research UI Test', 'section');++ // Launch browser+ browser = await puppeteer.launch(getPuppeteerLaunchOptions());+ const page = await browser.newPage();++ // Set viewport+ await page.setViewport({ width: 1280, height: 800 });++ // Initialize auth helper+ const auth = new AuthHelper(page, BASE_URL);++ // Ensure authenticated+ log('🔐 Authenticating...', 'info');+ await auth.ensureAuthenticated();++ // Step 1: Create initial research+ log('\n📝 Step 1: Creating initial research', 'section');+ const initialQuery = 'What is quantum computing?';+ const researchId = await createAndCompleteResearch(page, initialQuery);++ if (!researchId) {+ throw new Error('Failed to create initial research or get research ID');+ }+ log(`✅ Initial research created with ID: ${researchId}`, 'success');++ // Step 2: Navigate to results page if not already there+ const currentUrl = page.url();+ if (!currentUrl.includes(`/results/${researchId}`)) {+ log('📍 Navigating to results page...', 'info');+ await page.goto(`${BASE_URL}/results/${researchId}`, { waitUntil: 'networkidle2' });+ }++ // Wait for results to load+ await page.waitForSelector('#results-content, .results-content', { timeout: 10000 });++ // Step 3: Test follow-up button presence+ log('\n🔍 Step 2: Testing follow-up button', 'section');+ const followUpBtn = await page.$('#ask-followup-btn');++ if (!followUpBtn) {+ throw new Error('Follow-up button not found on results page');+ }+ log('✅ Follow-up button found', 'success');++ // Step 4: Click follow-up button and test modal+ log('\n🖱️ Step 3: Opening follow-up modal', 'section');+ await followUpBtn.click();+ await delay(1000); // Wait for modal animation++ // Check if modal opened+ const modal = await page.$('#followUpModal');+ if (!modal) {+ throw new Error('Follow-up modal did not open');+ }++ // Check if modal is visible+ const modalVisible = await page.evaluate(() => {+ const modal = document.getElementById('followUpModal');+ if (!modal) return false;++ // Check Bootstrap modal classes or inline styles+ const hasShowClass = modal.classList.contains('show');+ const displayStyle = window.getComputedStyle(modal).display;++ return hasShowClass || displayStyle !== 'none';+ });++ if (!modalVisible) {+ log('⚠️ Modal exists but may not be visible, continuing...', 'warning');+ }++ log('✅ Follow-up modal opened', 'success');++ // Step 5: Check parent context is loaded+ log('\n📊 Step 4: Checking parent context', 'section');++ // Wait a bit for context to load+ await delay(2000);++ const parentContextVisible = await page.evaluate(() => {+ const contextDiv = document.getElementById('parentContext');+ return contextDiv && contextDiv.style.display !== 'none';+ });++ if (parentContextVisible) {+ const parentSummary = await page.$eval('#parentSummary', el => el.textContent);+ const parentSources = await page.$eval('#parentSources', el => el.textContent);++ log(`✅ Parent context loaded:`, 'success');+ log(` Summary: ${parentSummary.substring(0, 50)}...`, 'info');+ log(` Sources: ${parentSources} available`, 'info');+ } else {+ log('⚠️ Parent context not visible (may be due to async loading)', 'warning');+ }++ // Step 6: Enter follow-up question+ log('\n✍️ Step 5: Entering follow-up question', 'section');+ const followUpQuestion = 'How do quantum gates work?';++ await page.waitForSelector('#followUpQuestion', { timeout: 5000 });+ await page.type('#followUpQuestion', followUpQuestion);+ log(`✅ Entered follow-up question: "${followUpQuestion}"`, 'success');++ // Step 7: Test advanced options+ log('\n⚙️ Step 6: Testing advanced options', 'section');++ // Try to expand advanced options+ const advancedLink = await page.$('a[onclick*="toggleAdvancedOptions"]');+ if (advancedLink) {+ await advancedLink.click();+ await delay(500);++ const advancedVisible = await page.evaluate(() => {+ const panel = document.getElementById('advancedOptionsPanel');+ return panel && panel.style.display !== 'none';+ });++ if (advancedVisible) {+ // Set to quick summary (1 iteration)+ await page.select('#followUpIterations', '1');+ log('✅ Advanced options configured for quick summary', 'success');+ }+ }++ // Step 8: Submit follow-up research+ log('\n🚀 Step 7: Submitting follow-up research', 'section');++ // Find and click submit button in modal+ const submitBtn = await page.$('#followUpModal button.btn-primary');+ if (!submitBtn) {+ throw new Error('Submit button not found in follow-up modal');+ }++ // Click submit and wait for navigation+ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: TIMEOUT }).catch(e => {+ log('⚠️ Navigation timeout, checking URL...', 'warning');+ }),+ submitBtn.click()+ ]);++ await delay(2000);++ // Step 9: Verify follow-up research started+ log('\n✔️ Step 8: Verifying follow-up research', 'section');++ const newUrl = page.url();++ // Check if we're on a new research page+ if (newUrl.includes('/progress/') || newUrl.includes('/results/')) {+ const newResearchId = newUrl.match(/\/(progress|results)\/([a-zA-Z0-9-]+)/)?.[2];++ if (newResearchId && newResearchId !== researchId) {+ log(`✅ Follow-up research started with ID: ${newResearchId}`, 'success');++ // Check for follow-up indicator in URL params+ if (newUrl.includes('followup=true')) {+ log('✅ Follow-up flag detected in URL', 'success');+ }+ } else {+ log('⚠️ May be on same research page, checking content...', 'warning');+ }+ } else {+ log(`⚠️ Unexpected URL after submission: ${newUrl}`, 'warning');+ }++ // Final success+ log('\n🎉 Follow-up Research Test Completed Successfully!', 'section');++ } catch (error) {+ log(`\n❌ Test Failed: ${error.message}`, 'error');+ console.error(error);+ exitCode = 1;+ } finally {+ if (browser) {+ await browser.close();+ }+ process.exit(exitCode);+ }+}++// Run the test+(async () => {+ try {+ await testFollowUpResearch();+ } catch (error) {+ console.error('Test execution failed:', error);+ process.exit(1);+ }+})();diff --git a/tests/ui_tests/test_followup_simple.js b/tests/ui_tests/test_followup_simple.jsnew file mode 100755index 0000000000..e0f75d454d--- /dev/null+++ b/tests/ui_tests/test_followup_simple.js@@ -0,0 +1,161 @@+#!/usr/bin/env node++/**+ * Simple test for follow-up research using existing testuser+ */++const puppeteer = require('puppeteer');++const BASE_URL = 'http://127.0.0.1:5000';+const PARENT_RESEARCH_ID = '6fe358f9-82de-43b1-8cae-0b673e61fe4d';+const TEST_USER = 'testuser';+const TEST_PASSWORD = 'testpass';++async function testFollowupResearch() {+ let browser;+ let page;++ try {+ console.log('🚀 Starting Simple Follow-up Research Test');+ console.log(` Parent Research: ${PARENT_RESEARCH_ID}`);+ console.log(` User: ${TEST_USER}`);++ // Launch browser+ browser = await puppeteer.launch({+ headless: process.env.HEADLESS === 'true',+ args: ['--no-sandbox', '--disable-setuid-sandbox']+ });++ page = await browser.newPage();++ // Set viewport+ await page.setViewport({ width: 1280, height: 800 });++ // Enable console logging+ page.on('console', msg => {+ if (msg.type() === 'error') {+ console.log('Browser console error:', msg.text());+ }+ });++ // Step 1: Login+ console.log('\n1️⃣ Logging in as testuser...');+ await page.goto(`${BASE_URL}/auth/login`, { waitUntil: 'networkidle2' });++ await page.type('input[name="username"]', TEST_USER);+ await page.type('input[name="password"]', TEST_PASSWORD);++ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2' }),+ page.click('button[type="submit"]')+ ]);++ console.log('✅ Logged in successfully');++ // Step 2: Navigate to parent research+ console.log(`\n2️⃣ Navigating to parent research...`);+ await page.goto(`${BASE_URL}/results/${PARENT_RESEARCH_ID}`, {+ waitUntil: 'networkidle2',+ timeout: 30000+ });++ // Wait for page to load+ await new Promise(resolve => setTimeout(resolve, 2000));++ // Step 3: Test direct API call for follow-up+ console.log('\n3️⃣ Testing follow-up API directly...');++ const apiResponse = await page.evaluate(async (parentId) => {+ try {+ const response = await fetch('/api/followup/start', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ credentials: 'include',+ body: JSON.stringify({+ parent_research_id: parentId,+ question: 'What are the key points from this research?'+ })+ });++ const data = await response.json();+ return {+ status: response.status,+ data: data+ };+ } catch (error) {+ return {+ error: error.message+ };+ }+ }, PARENT_RESEARCH_ID);++ console.log('API Response:', JSON.stringify(apiResponse, null, 2));++ if (apiResponse.status === 200 && apiResponse.data.success) {+ console.log(`\n✅ Follow-up research started successfully!`);+ console.log(` Research ID: ${apiResponse.data.research_id}`);++ // Navigate to the new research+ const newResearchId = apiResponse.data.research_id;+ console.log(`\n4️⃣ Navigating to follow-up research: ${newResearchId}`);++ await page.goto(`${BASE_URL}/results/${newResearchId}`, {+ waitUntil: 'networkidle2',+ timeout: 30000+ });++ // Wait a bit to see the page+ await new Promise(resolve => setTimeout(resolve, 3000));++ // Check if we're on the results page+ const currentUrl = page.url();+ if (currentUrl.includes(`/results/${newResearchId}`) || currentUrl.includes(`/progress/${newResearchId}`)) {+ console.log('✅ Successfully navigated to follow-up research page');+ }++ } else {+ console.log(`\n❌ Follow-up failed:`);+ console.log(` Status: ${apiResponse.status}`);+ console.log(` Error: ${apiResponse.data?.error || 'Unknown error'}`);++ // Try to get more error details from server logs+ const serverLogs = await page.evaluate(() => {+ return document.body.innerText;+ });++ if (serverLogs.includes('Error') || serverLogs.includes('error')) {+ console.log('\nPage content (may contain error details):');+ console.log(serverLogs.substring(0, 500));+ }+ }++ console.log('\n✅ Test completed!');++ } catch (error) {+ console.error('\n❌ Test failed:', error.message);+ console.error(error.stack);++ // Take screenshot on error+ if (page) {+ await page.screenshot({+ path: '/tmp/followup_test_error.png',+ fullPage: true+ });+ console.log('Screenshot saved to /tmp/followup_test_error.png');+ }++ process.exit(1);+ } finally {+ if (browser) {+ await browser.close();+ }+ }+}++// Run the test+testFollowupResearch().catch(error => {+ console.error('Fatal error:', error);+ process.exit(1);+});