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.

feat: add UI warnings for context-related issues (#2375)

LearningCircuit2af9c4e382f0
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 1f40fdf151..2fb1a43206 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -941,7 +941,7 @@
},
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -4317,13 +4317,13 @@
"value": false,
"visible": true
},
- "app.warnings.dismiss_low_context_focused": {
+ "app.warnings.dismiss_model_mismatch": {
"category": "warnings",
- "description": "Dismiss warnings about using focused iteration with low context window sizes",
+ "description": "Dismiss warnings about context size vs model size mismatches",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Dismiss Low Context + Focused Strategy Warnings",
+ "name": "Dismiss Model Mismatch Warnings",
"options": null,
"step": null,
"type": "APP",
@@ -4331,13 +4331,13 @@
"value": false,
"visible": true
},
- "app.warnings.dismiss_model_mismatch": {
+ "app.warnings.dismiss_searxng_recommendation": {
"category": "warnings",
- "description": "Dismiss warnings about context size vs model size mismatches",
+ "description": "Dismiss recommendations about using more questions instead of iterations with SearXNG",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Dismiss Model Mismatch Warnings",
+ "name": "Dismiss SearXNG Optimization Tips",
"options": null,
"step": null,
"type": "APP",
@@ -4345,13 +4345,13 @@
"value": false,
"visible": true
},
- "app.warnings.dismiss_searxng_recommendation": {
+ "app.warnings.dismiss_context_reduced": {
"category": "warnings",
- "description": "Dismiss recommendations about using more questions instead of iterations with SearXNG",
+ "description": "Dismiss warnings based on historical context usage and truncation",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Dismiss SearXNG Optimization Tips",
+ "name": "Dismiss Context Reduced Warnings",
"options": null,
"step": null,
"type": "APP",
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index e216cf634a..e7741450ef 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -228,6 +228,72 @@ def calculate_warnings():
}
)
+ # History-based context warning
+ # Compare current setting against actual historical usage
+ with get_user_db_session(username) as db_session:
+ if db_session and is_local_provider:
+ from sqlalchemy import desc, func
+ from ...database.models import TokenUsage
+
+ settings_manager = get_settings_manager(db_session, username)
+ dismiss_context_warning = settings_manager.get_setting(
+ "app.warnings.dismiss_context_reduced", False
+ )
+
+ if not dismiss_context_warning:
+ # Get context usage from recent researches (last 100)
+ recent_contexts = (
+ db_session.query(TokenUsage.context_limit)
+ .filter(TokenUsage.context_limit.isnot(None))
+ .order_by(desc(TokenUsage.timestamp))
+ .limit(100)
+ .all()
+ )
+
+ if recent_contexts and len(recent_contexts) >= 5:
+ # Calculate percentile-based threshold
+ context_values = sorted(
+ [r[0] for r in recent_contexts if r[0]]
+ )
+ if context_values:
+ # Use 1st percentile (bottom 1%) as minimum safe context
+ # This means 99% of researches used at least this much
+ percentile_idx = max(
+ 0, int(len(context_values) * 0.01)
+ )
+ min_safe_context = context_values[percentile_idx]
+
+ # Warn if current setting is below the safe minimum
+ if local_context < min_safe_context:
+ warnings.append(
+ {
+ "type": "context_below_history",
+ "icon": "📉",
+ "title": "Context Below Historical Usage",
+ "message": f"Current context ({local_context:,}) is below the context window size that 99% of your past researches ran with (min safe: {min_safe_context:,}). This may cause truncation.",
+ "dismissKey": "app.warnings.dismiss_context_reduced",
+ }
+ )
+
+ # Also check if previous researches had truncation issues
+ truncation_count = (
+ db_session.query(func.count(TokenUsage.id))
+ .filter(TokenUsage.context_truncated.is_(True))
+ .filter(TokenUsage.context_limit >= local_context)
+ .scalar()
+ )
+
+ if truncation_count and truncation_count > 0:
+ warnings.append(
+ {
+ "type": "context_truncation_history",
+ "icon": "⚠️",
+ "title": "Previous Truncation Detected",
+ "message": f"Research was truncated {truncation_count} time(s) with similar or higher context. Consider increasing context window.",
+ "dismissKey": "app.warnings.dismiss_context_reduced",
+ }
+ )
+
except Exception as e:
logger.warning(f"Error calculating warnings: {e}")
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.js
index 4a31432959..296bf83f43 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -41,7 +41,7 @@
SafeLogger.error('No research ID found');
if (window.ui) window.ui.showError('No active research found. Please start a new research.');
setTimeout(() => {
- window.location.href = '/';
+ URLValidator.safeAssign(window.location, 'href', '/');
}, 3000);
return;
}
@@ -629,26 +629,29 @@
// Show view results button
if (viewResultsButton) {
viewResultsButton.style.display = 'inline-block';
- viewResultsButton.href = URLBuilder.resultsPage(currentResearchId);
+ URLValidator.safeAssign(viewResultsButton, 'href', URLBuilder.resultsPage(currentResearchId));
}
// Hide cancel button
if (cancelButton) {
cancelButton.style.display = 'none';
}
+
+ // Check for context overflow and show warning toast
+ checkContextOverflowOnCompletion();
} else if (data.status === 'failed' || data.status === 'cancelled') {
// For failed research, try to show the error report if available
if (data.status === 'failed') {
if (viewResultsButton) {
viewResultsButton.textContent = 'View Error Report';
- viewResultsButton.href = URLBuilder.resultsPage(currentResearchId);
+ URLValidator.safeAssign(viewResultsButton, 'href', URLBuilder.resultsPage(currentResearchId));
viewResultsButton.style.display = 'inline-block';
}
} else {
// For cancelled research, go back to home
if (viewResultsButton) {
viewResultsButton.textContent = 'Start New Research';
- viewResultsButton.href = '/';
+ URLValidator.safeAssign(viewResultsButton, 'href', '/');
viewResultsButton.style.display = 'inline-block';
}
}
@@ -660,6 +663,36 @@
}
}
+ /**
+ * Check for context overflow after research completion and show toast if detected
+ */
+ async function checkContextOverflowOnCompletion() {
+ try {
+ const response = await fetch(`/metrics/api/research/${currentResearchId}/context-overflow`);
+ if (!response.ok) {
+ SafeLogger.warn('Context overflow API not available');
+ return;
+ }
+
+ const data = await response.json();
+ if (data.status === 'success' && data.data?.overview?.truncation_occurred) {
+ const overview = data.data.overview;
+ const tokensLost = overview.tokens_lost || 0;
+ const truncatedCount = overview.truncated_count || 0;
+
+ let message = `Context truncated ${truncatedCount} time(s) during research.`;
+ if (tokensLost > 0) {
+ message += ` ~${tokensLost.toLocaleString()} tokens lost.`;
+ }
+ message += ' Consider increasing context window.';
+
+ showNotification('Context Overflow Warning', message, 'warning', 10000);
+ SafeLogger.log('Context overflow toast shown:', overview);
+ }
+ } catch (error) {
+ SafeLogger.error('Error checking context overflow:', error);
+ }
+ }
/**
* Handle research cancellation
@@ -1119,7 +1152,7 @@
ctx.fillText('R', 16, 16);
// Update favicon
- link.href = canvas.toDataURL('image/png');
+ URLValidator.safeAssign(link, 'href', canvas.toDataURL('image/png'));
} catch (error) {
SafeLogger.error('Error updating favicon:', error);
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 19e808b31f..9087fa3147 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -188,6 +188,9 @@
if (exportBtn) exportBtn.disabled = false;
if (pdfBtn) pdfBtn.disabled = false;
+ // Check for context overflow after loading results
+ checkContextOverflow();
+
} catch (error) {
SafeLogger.error('Error loading research results:', error);
showError(`Error loading research results: ${error.message}`);
@@ -901,6 +904,47 @@
}
}
+ /**
+ * Check for context overflow and display warning if detected
+ */
+ async function checkContextOverflow() {
+ try {
+ const response = await fetch(`/metrics/api/research/${researchId}/context-overflow`);
+ if (!response.ok) {
+ SafeLogger.log('Context overflow API not available');
+ return;
+ }
+
+ const data = await response.json();
+ if (data.status === 'success' && data.data?.overview?.truncation_occurred) {
+ const overview = data.data.overview;
+ const warningBanner = document.getElementById('context-overflow-warning');
+ const warningMessage = document.getElementById('context-overflow-message');
+
+ if (warningBanner && warningMessage) {
+ const tokensLost = overview.tokens_lost || 0;
+ const truncatedCount = overview.truncated_count || 0;
+ const contextLimit = overview.context_limit;
+
+ let message = `Research was truncated ${truncatedCount} time(s) due to context limits.`;
+ if (tokensLost > 0) {
+ message += ` ~${tokensLost.toLocaleString()} tokens lost.`;
+ }
+ if (contextLimit) {
+ message += ` Context limit: ${contextLimit.toLocaleString()} tokens.`;
+ }
+ message += ' Consider increasing context window size for better results.';
+
+ warningMessage.textContent = message;
+ warningBanner.style.display = 'flex';
+ SafeLogger.log('Context overflow warning displayed:', overview);
+ }
+ }
+ } catch (error) {
+ SafeLogger.error('Error checking context overflow:', error);
+ }
+ }
+
/**
* Initialize star rating functionality
*/
diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index 3a233e6e82..e9d9e122a4 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -58,6 +58,14 @@
</div>
</div>
</div>
+ <!-- Context Overflow Warning Banner -->
+ <div id="context-overflow-warning" class="ldr-alert ldr-alert-warning" role="status" style="display: none;">
+ <i class="fas fa-exclamation-triangle"></i>
+ <div>
+ <strong>Context Overflow Detected</strong>
+ <span id="context-overflow-message"></span>
+ </div>
+ </div>
<div class="ldr-results-content" id="results-content">
<!-- Will be populated dynamically -->
<div class="ldr-loading-spinner ldr-centered">
diff --git a/tests/routes/test_settings_routes.py b/tests/routes/test_settings_routes.py
index 7a975656cb..fdde4e9e56 100644
--- a/tests/routes/test_settings_routes.py
+++ b/tests/routes/test_settings_routes.py
@@ -279,6 +279,224 @@ class TestCalculateWarnings:
assert len(warnings) == 0
+ def test_calculate_warnings_context_below_history(self):
+ """Test warning when context is below historical usage."""
+ from local_deep_research.web.routes.settings_routes import (
+ calculate_warnings,
+ )
+
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = (
+ lambda key, default=None: {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 2048,
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
+ "llm.model": "llama3",
+ }.get(key, default)
+ )
+
+ mock_db_session = Mock()
+
+ # First query: recent context limits (10 records at 8192)
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = [
+ (8192,) for _ in range(10)
+ ]
+
+ # Second query: truncation count (none)
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 0
+
+ mock_db_session.query.side_effect = [
+ context_query,
+ truncation_query,
+ ]
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(
+ return_value=mock_db_session
+ )
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ return_value=mock_settings_manager,
+ ):
+ warnings = calculate_warnings()
+
+ assert any(
+ w["type"] == "context_below_history" for w in warnings
+ )
+
+ def test_calculate_warnings_context_below_history_not_enough_samples(self):
+ """Test no history warning when fewer than 5 samples exist."""
+ from local_deep_research.web.routes.settings_routes import (
+ calculate_warnings,
+ )
+
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = (
+ lambda key, default=None: {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 2048,
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
+ "llm.model": "llama3",
+ }.get(key, default)
+ )
+
+ mock_db_session = Mock()
+
+ # First query: only 3 records (below threshold of 5)
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = [
+ (8192,) for _ in range(3)
+ ]
+
+ # Second query: truncation count (none)
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 0
+
+ mock_db_session.query.side_effect = [
+ context_query,
+ truncation_query,
+ ]
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(
+ return_value=mock_db_session
+ )
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ return_value=mock_settings_manager,
+ ):
+ warnings = calculate_warnings()
+
+ assert not any(
+ w["type"] == "context_below_history" for w in warnings
+ )
+
+ def test_calculate_warnings_truncation_history(self):
+ """Test warning when past researches had truncation at same/higher context."""
+ from local_deep_research.web.routes.settings_routes import (
+ calculate_warnings,
+ )
+
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = (
+ lambda key, default=None: {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 4096,
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
+ "llm.model": "llama3",
+ }.get(key, default)
+ )
+
+ mock_db_session = Mock()
+
+ # First query: 10 records at same context (no below-history warning)
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = [
+ (4096,) for _ in range(10)
+ ]
+
+ # Second query: 3 truncations at context_limit >= current
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 3
+
+ mock_db_session.query.side_effect = [
+ context_query,
+ truncation_query,
+ ]
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(
+ return_value=mock_db_session
+ )
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ return_value=mock_settings_manager,
+ ):
+ warnings = calculate_warnings()
+
+ assert any(
+ w["type"] == "context_truncation_history"
+ for w in warnings
+ )
+
+ def test_calculate_warnings_context_warnings_dismissed(self):
+ """Test no history warnings when dismiss_context_reduced is True."""
+ from local_deep_research.web.routes.settings_routes import (
+ calculate_warnings,
+ )
+
+ mock_settings_manager = Mock()
+ mock_settings_manager.get_setting.side_effect = (
+ lambda key, default=None: {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 2048,
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": True,
+ "llm.model": "llama3",
+ }.get(key, default)
+ )
+
+ mock_db_session = Mock()
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(
+ return_value=mock_db_session
+ )
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ return_value=mock_settings_manager,
+ ):
+ warnings = calculate_warnings()
+
+ assert not any(
+ w["type"] == "context_below_history" for w in warnings
+ )
+ assert not any(
+ w["type"] == "context_truncation_history"
+ for w in warnings
+ )
+
class TestGetEngineIconAndCategory:
"""Tests for _get_engine_icon_and_category function."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index bdb0cfc728..690d596f82 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -384,13 +384,13 @@
"value": "UTC",
"visible": true
},
- "app.warnings.dismiss_high_context": {
+ "app.warnings.dismiss_context_reduced": {
"category": "warnings",
- "description": "Dismiss warnings about high context window sizes that may cause memory issues",
+ "description": "Dismiss warnings based on historical context usage and truncation",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Dismiss High Context Warnings",
+ "name": "Dismiss Context Reduced Warnings",
"options": null,
"step": null,
"type": "APP",
@@ -398,13 +398,13 @@
"value": false,
"visible": true
},
- "app.warnings.dismiss_low_context_focused": {
+ "app.warnings.dismiss_high_context": {
"category": "warnings",
- "description": "Dismiss warnings about using focused iteration with low context window sizes",
+ "description": "Dismiss warnings about high context window sizes that may cause memory issues",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Dismiss Low Context + Focused Strategy Warnings",
+ "name": "Dismiss High Context Warnings",
"options": null,
"step": null,
"type": "APP",
@@ -7391,7 +7391,7 @@
},
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters.",
"editable": true,
"max_value": null,
"min_value": null,