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.

fix: delegate api_start_research to research_routes.start_research (#2241)

LearningCircuit1e675aba8a42
diff --git a/src/local_deep_research/api/client.py b/src/local_deep_research/api/client.py
index 4bbcc68abf..eedce2c334 100644
--- a/src/local_deep_research/api/client.py
+++ b/src/local_deep_research/api/client.py
@@ -277,7 +277,7 @@ class LDRClient:
while time.time() - start_time < timeout:
status_response = self.session.get(
- f"{self.base_url}/research/api/research/{research_id}/status"
+ f"{self.base_url}/research/api/status/{research_id}"
)
if status_response.status_code == 200:
@@ -286,7 +286,7 @@ class LDRClient:
if status.get("status") == ResearchStatus.COMPLETED:
# Get final results
results_response = self.session.get(
- f"{self.base_url}/research/api/research/{research_id}/result"
+ f"{self.base_url}/api/report/{research_id}"
)
if results_response.status_code == 200:
return results_response.json()
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
index c47f4ca1cd..435d84e2b9 100644
--- a/src/local_deep_research/news/flask_api.py
+++ b/src/local_deep_research/news/flask_api.py
@@ -575,7 +575,7 @@ def run_subscription_now(subscription_id: str) -> Dict[str, Any]:
if response.ok:
data = response.json()
- if data.get("status") == "success":
+ if data.get("status") in ("success", "queued"):
return jsonify(
{
"status": "success",
@@ -1087,7 +1087,7 @@ def check_overdue_subscriptions():
"error": f"HTTP {response.status_code}: {response.text}",
}
- if result.get("status") == "success":
+ if result.get("status") in ("success", "queued"):
overdue_count += 1
# Update subscription's last/next refresh times
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 87a680d051..1040d93aa6 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -6,18 +6,13 @@ from flask import (
request,
)
from loguru import logger
-from datetime import datetime, UTC
-from ...constants import ResearchStatus
from ...database.models import ResearchHistory
from ...database.session_context import get_user_db_session
from ...utilities.url_utils import normalize_url
from ..auth.decorators import login_required
-from ..routes.research_routes import active_research, termination_flags
from ..services.research_service import (
cancel_research,
- run_research_process,
- start_research_process,
)
from ..services.resource_service import (
add_resource,
@@ -73,64 +68,15 @@ def get_current_config():
@login_required
def api_start_research():
"""
- Start a new research process
- """
- data = request.json
- query = data.get("query", "")
- mode = data.get("mode", "quick")
-
- if not query:
- return jsonify({"status": "error", "message": "Query is required"}), 400
-
- try:
- # Create a record in the database with explicit UTC timestamp
- created_at = datetime.now(UTC).isoformat()
-
- # Save basic research settings for API route
- research_settings = {
- "model_provider": "OLLAMA", # Default
- "model": "llama2", # Default
- "search_engine": "searxng", # Default
- }
-
- with get_user_db_session() as db_session:
- research = ResearchHistory(
- query=query,
- mode=mode,
- status=ResearchStatus.IN_PROGRESS,
- created_at=created_at,
- progress_log=[{"time": created_at, "progress": 0}],
- research_meta=research_settings,
- )
- db_session.add(research)
- db_session.commit()
- research_id = research.id
-
- # Start the research process
- research_thread = start_research_process(
- research_id,
- query,
- mode,
- active_research,
- termination_flags,
- run_research_process,
- )
+ Start a new research process.
- # Store the thread reference
- active_research[research_id]["thread"] = research_thread
+ Delegates to the full-featured start_research() in research_routes,
+ which reads settings from the database, handles queueing, and starts
+ the research thread.
+ """
+ from ..routes.research_routes import start_research
- return jsonify(
- {
- "status": "success",
- "message": "Research started successfully",
- "research_id": research_id,
- }
- )
- except Exception:
- logger.exception("Error starting research")
- return jsonify(
- {"status": "error", "message": "Failed to start research"}, 500
- )
+ return start_research()
@api_bp.route("/status/<string:research_id>", methods=["GET"])
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index b8bcba0575..24e00b7e03 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -437,7 +437,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', model
const data = await response.json();
SafeLogger.log('Research API response:', data);
- if (data.status === 'success' && data.research_id) {
+ if ((data.status === 'success' || data.status === 'queued') && data.research_id) {
showAlert('Analyzing news... Results will appear below when ready.', 'info');
// Show loading state in news feed FIRST
diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.js
index 01abd64a53..1e72f78772 100644
--- a/src/local_deep_research/web/static/js/pages/subscriptions.js
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -332,7 +332,7 @@ async function runSubscriptionNow(subscriptionId) {
const data = await response.json();
SafeLogger.log('Research API response:', data);
- if (data.status === 'success' && data.research_id) {
+ if ((data.status === 'success' || data.status === 'queued') && data.research_id) {
// Validate research_id is a safe UUID format before using in URL
const safeResearchId = String(data.research_id).replace(/[^a-zA-Z0-9-]/g, '');
showAlert(`Research started! <a href="/progress/${safeResearchId}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');
diff --git a/tests/api_tests/test_all_apis.py b/tests/api_tests/test_all_apis.py
index f809845e6c..1832972e11 100644
--- a/tests/api_tests/test_all_apis.py
+++ b/tests/api_tests/test_all_apis.py
@@ -134,13 +134,13 @@ class TestAllAPIs:
# Check status
response = authenticated_client.get(
- f"/research/api/research/{research_id}/status"
+ f"/research/api/status/{research_id}"
)
assert response.status_code == 200
# Terminate research
response = authenticated_client.post(
- f"/research/api/research/{research_id}/terminate"
+ f"/research/api/terminate/{research_id}"
)
assert response.status_code in [200, 404]
diff --git a/tests/web/routes/test_api_routes.py b/tests/web/routes/test_api_routes.py
index 2d5d5e9612..1fc2117280 100644
--- a/tests/web/routes/test_api_routes.py
+++ b/tests/web/routes/test_api_routes.py
@@ -80,42 +80,54 @@ class TestApiStartResearch:
assert response.status_code == 400
def test_starts_research_successfully(self, authenticated_client):
- """Should start research with valid input."""
+ """Should delegate to start_research and return success."""
with patch(
- "local_deep_research.web.routes.api_routes.get_user_db_session"
- ) as mock_session_ctx:
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
+ "local_deep_research.web.routes.research_routes.start_research"
+ ) as mock_start:
+ mock_start.return_value = (
+ authenticated_client.application.make_response(
+ (
+ '{"status": "success", "research_id": "test-uuid"}',
+ 200,
+ {"Content-Type": "application/json"},
+ )
+ )
)
- mock_session_ctx.return_value.__exit__ = MagicMock(
- return_value=None
+
+ response = authenticated_client.post(
+ f"{API_PREFIX}/start",
+ json={"query": "What is AI?", "mode": "quick"},
)
- with patch(
- "local_deep_research.web.routes.api_routes.start_research_process"
- ) as mock_start:
- mock_thread = MagicMock()
- mock_start.return_value = mock_thread
-
- with patch(
- "local_deep_research.web.routes.api_routes.active_research",
- {},
- ):
- # Mock the research object that gets created
- mock_research = MagicMock()
- mock_research.id = "test-research-id"
- mock_session.add = MagicMock()
- mock_session.commit = MagicMock()
-
- response = authenticated_client.post(
- f"{API_PREFIX}/start",
- json={"query": "What is AI?", "mode": "quick"},
- )
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["status"] == "success"
+ assert data["research_id"] == "test-uuid"
+ mock_start.assert_called_once()
+
+ def test_starts_research_queued(self, authenticated_client):
+ """Should delegate to start_research and return queued status."""
+ with patch(
+ "local_deep_research.web.routes.research_routes.start_research"
+ ) as mock_start:
+ mock_start.return_value = authenticated_client.application.make_response(
+ (
+ '{"status": "queued", "research_id": "test-uuid", "queue_position": 1}',
+ 200,
+ {"Content-Type": "application/json"},
+ )
+ )
+
+ response = authenticated_client.post(
+ f"{API_PREFIX}/start",
+ json={"query": "What is AI?", "mode": "quick"},
+ )
- # Since we're not fully mocking the DB, this may return 500
- # In a real scenario with proper mocking, it would be 200
- assert response.status_code in [200, 500]
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["status"] == "queued"
+ assert data["research_id"] == "test-uuid"
+ mock_start.assert_called_once()
class TestApiResearchStatus: