~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
Add favorites feature for search engine selector
LearningCircuit8ccd6cbd9a64
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 306f8fcb40..8240e1efa7 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1528,6 +1528,20 @@ def api_get_available_search_engines():username=username, db_session=db_session)+ # Get user's favorites+ favorites_setting = (+ db_session.query(Setting)+ .filter(Setting.key == "search.favorites")+ .first()+ )+ favorites = []+ if (+ favorites_setting+ and favorites_setting.value+ and isinstance(favorites_setting.value, list)+ ):+ favorites = favorites_setting.value+# Extract search engines from configengines_dict = {}engine_options = []@@ -1565,12 +1579,16 @@ def api_get_available_search_engines():base_name = engine_data.get("display_name", engine_id)label = f"{icon} {base_name} ({category})"+ # Check if engine is a favorite+ is_favorite = engine_id in favorites+engines_dict[engine_id] = {"display_name": base_name,"description": engine_data.get("description", ""),"strengths": engine_data.get("strengths", []),"icon": icon,"category": category,+ "is_favorite": is_favorite,}engine_options.append(@@ -1579,15 +1597,28 @@ def api_get_available_search_engines():"label": label,"icon": icon,"category": category,+ "is_favorite": is_favorite,})+ # Sort engine_options: favorites first, then alphabetically by label+ engine_options.sort(+ key=lambda x: (+ not x.get("is_favorite", False),+ x.get("label", "").lower(),+ )+ )+# If no engines found, log the issue but return empty listif not engine_options:logger.warning("No search engines found in configuration")return jsonify(- {"engines": engines_dict, "engine_options": engine_options}+ {+ "engines": engines_dict,+ "engine_options": engine_options,+ "favorites": favorites,+ })except Exception:@@ -1595,6 +1626,163 @@ def api_get_available_search_engines():return jsonify({"error": "Failed to retrieve settings"}), 500+@settings_bp.route("/api/search-favorites", methods=["GET"])+@login_required+def api_get_search_favorites():+ """Get the list of favorite search engines for the current user"""+ try:+ username = session.get("username")+ with get_user_db_session(username) as db_session:+ # Get favorites from settings+ db_setting = (+ db_session.query(Setting)+ .filter(Setting.key == "search.favorites")+ .first()+ )++ if db_setting and db_setting.value:+ favorites = db_setting.value+ if isinstance(favorites, list):+ return jsonify({"favorites": favorites})++ # Return empty list if no favorites set+ return jsonify({"favorites": []})++ except Exception:+ logger.exception("Error getting search favorites")+ return jsonify({"error": "Failed to retrieve favorites"}), 500+++@settings_bp.route("/api/search-favorites", methods=["PUT"])+@login_required+def api_update_search_favorites():+ """Update the list of favorite search engines for the current user"""+ try:+ data = request.get_json()+ if not data:+ return jsonify({"error": "No data provided"}), 400++ favorites = data.get("favorites")+ if favorites is None:+ return jsonify({"error": "No favorites provided"}), 400++ if not isinstance(favorites, list):+ return jsonify({"error": "Favorites must be a list"}), 400++ username = session.get("username")+ with get_user_db_session(username) as db_session:+ # Check if setting exists+ db_setting = (+ db_session.query(Setting)+ .filter(Setting.key == "search.favorites")+ .first()+ )++ if db_setting:+ # Update existing setting+ db_setting.value = favorites+ db_setting.updated_at = datetime.now(UTC)+ else:+ # Create new setting+ db_setting = Setting(+ key="search.favorites",+ value=favorites,+ type=SettingType.SEARCH,+ name="Search Favorites",+ description="List of favorite search engines",+ category="search",+ ui_element="hidden",+ visible=False,+ editable=True,+ )+ db_session.add(db_setting)++ db_session.commit()+ return jsonify(+ {+ "message": "Favorites updated successfully",+ "favorites": favorites,+ }+ )++ except Exception:+ logger.exception("Error updating search favorites")+ return jsonify({"error": "Failed to update favorites"}), 500+++@settings_bp.route("/api/search-favorites/toggle", methods=["POST"])+@login_required+def api_toggle_search_favorite():+ """Toggle a search engine as favorite"""+ try:+ data = request.get_json()+ if not data:+ return jsonify({"error": "No data provided"}), 400++ engine_id = data.get("engine_id")+ if not engine_id:+ return jsonify({"error": "No engine_id provided"}), 400++ username = session.get("username")+ with get_user_db_session(username) as db_session:+ # Get current favorites+ db_setting = (+ db_session.query(Setting)+ .filter(Setting.key == "search.favorites")+ .first()+ )++ if (+ db_setting+ and db_setting.value+ and isinstance(db_setting.value, list)+ ):+ favorites = list(db_setting.value)+ else:+ favorites = []++ # Toggle the engine+ is_favorite = engine_id in favorites+ if is_favorite:+ favorites.remove(engine_id)+ is_favorite = False+ else:+ favorites.append(engine_id)+ is_favorite = True++ # Update or create setting+ if db_setting:+ db_setting.value = favorites+ db_setting.updated_at = datetime.now(UTC)+ else:+ db_setting = Setting(+ key="search.favorites",+ value=favorites,+ type=SettingType.SEARCH,+ name="Search Favorites",+ description="List of favorite search engines",+ category="search",+ ui_element="hidden",+ visible=False,+ editable=True,+ )+ db_session.add(db_setting)++ db_session.commit()+ return jsonify(+ {+ "message": "Favorite toggled successfully",+ "engine_id": engine_id,+ "is_favorite": is_favorite,+ "favorites": favorites,+ }+ )++ except Exception:+ logger.exception("Error toggling search favorite")+ return jsonify({"error": "Failed to toggle favorite"}), 500++# Legacy routes for backward compatibility - these will redirect to the new routes@settings_bp.route("/main", methods=["GET"])@login_requireddiff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.cssindex 9c20637c56..081deda359 100644--- a/src/local_deep_research/web/static/css/custom_dropdown.css+++ b/src/local_deep_research/web/static/css/custom_dropdown.css@@ -103,6 +103,56 @@ body.dropdown-active {padding: 0 2px;}+/* Favorite star styling for dropdown items */+.ldr-dropdown-favorite-star {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 24px;+ height: 24px;+ margin-right: 8px;+ font-size: 1.1rem;+ color: var(--text-muted, #8a8aa0);+ cursor: pointer;+ transition: color 0.2s ease, transform 0.2s ease;+ flex-shrink: 0;+ vertical-align: middle;+}++.ldr-dropdown-favorite-star:hover {+ color: var(--accent-warning, #f6c343);+ transform: scale(1.15);+}++.ldr-dropdown-favorite-star.ldr-is-favorite {+ color: var(--accent-warning, #f6c343);+}++.ldr-dropdown-favorite-star.ldr-is-favorite:hover {+ color: var(--text-muted, #8a8aa0);+}++/* Dropdown item label when star is present */+.ldr-dropdown-item-label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* Make dropdown items flex when containing stars */+.ldr-custom-dropdown-item:has(.ldr-dropdown-favorite-star) {+ display: flex;+ align-items: center;+}++/* Fallback for browsers that don't support :has() */+.ldr-custom-dropdown-item {+ display: flex;+ align-items: center;+}+.ldr-custom-dropdown-no-results {padding: 10px 15px;color: var(--text-secondary, #c0c0cc);diff --git a/src/local_deep_research/web/static/js/components/custom_dropdown.js b/src/local_deep_research/web/static/js/components/custom_dropdown.jsindex b34550ea62..1fc8cb1bb2 100644--- a/src/local_deep_research/web/static/js/components/custom_dropdown.js+++ b/src/local_deep_research/web/static/js/components/custom_dropdown.js@@ -66,10 +66,53 @@const div = document.createElement('div');div.className = 'ldr-custom-dropdown-item';- // Use safe text content instead of innerHTML to prevent XSS- window.safeSetTextContent(div, item.label);+ // Add favorite star if callback is provided+ if (dropdownInfo.onFavoriteToggle) {+ const starSpan = document.createElement('span');+ starSpan.className = 'ldr-dropdown-favorite-star';+ starSpan.setAttribute('data-value', item.value);++ const isFavorite = item.is_favorite === true;+ if (isFavorite) {+ starSpan.classList.add('ldr-is-favorite');+ starSpan.innerHTML = '★';+ starSpan.title = 'Remove from favorites';+ } else {+ starSpan.innerHTML = '☆';+ starSpan.title = 'Add to favorites';+ }++ starSpan.addEventListener('click', (e) => {+ e.preventDefault();+ e.stopPropagation();+ const newIsFavorite = !isFavorite;+ dropdownInfo.onFavoriteToggle(item.value, item, newIsFavorite);++ if (newIsFavorite) {+ starSpan.classList.add('ldr-is-favorite');+ starSpan.innerHTML = '★';+ starSpan.title = 'Remove from favorites';+ } else {+ starSpan.classList.remove('ldr-is-favorite');+ starSpan.innerHTML = '☆';+ starSpan.title = 'Add to favorites';+ }+ });++ div.appendChild(starSpan);+ }++ // Create label content span+ const labelSpan = document.createElement('span');+ labelSpan.className = 'ldr-dropdown-item-label';+ window.safeSetTextContent(labelSpan, item.label);+ div.appendChild(labelSpan);+div.setAttribute('data-value', item.value);- div.addEventListener('click', () => {+ div.addEventListener('click', (e) => {+ if (e.target.classList.contains('ldr-dropdown-favorite-star')) {+ return;+ }// Set display valueinput.value = item.label;// Update hidden input if exists@@ -102,12 +145,13 @@* Setup a custom dropdown component* @param {HTMLElement} input - The input element* @param {HTMLElement} dropdownList - The dropdown list element- * @param {Function} getOptions - Function that returns the current options array [{value: string, label: string}]+ * @param {Function} getOptions - Function that returns the current options array [{value: string, label: string, is_favorite?: boolean}]* @param {Function} onSelect - Callback when an item is selected (value, item) => {}* @param {boolean} allowCustomValues - Whether to allow values not in the options list* @param {string} noResultsText - Text to show when no results are found+ * @param {Function|null} onFavoriteToggle - Optional callback when favorite star is clicked (value, item, isFavorite) => {}*/- function setupCustomDropdown(input, dropdownList, getOptions, onSelect, allowCustomValues = false, noResultsText = 'No results found.') {+ function setupCustomDropdown(input, dropdownList, getOptions, onSelect, allowCustomValues = false, noResultsText = 'No results found.', onFavoriteToggle = null) {let selectedIndex = -1;let isOpen = false;let showAllOptions = false; // Flag to track if we should show all options@@ -267,12 +311,66 @@const div = document.createElement('div');div.className = 'ldr-custom-dropdown-item';+ // Add favorite star if callback is provided+ if (onFavoriteToggle) {+ const starSpan = document.createElement('span');+ starSpan.className = 'ldr-dropdown-favorite-star';+ starSpan.setAttribute('data-value', item.value);++ // Check if item is a favorite+ const isFavorite = item.is_favorite === true;+ if (isFavorite) {+ starSpan.classList.add('ldr-is-favorite');+ starSpan.innerHTML = '★'; // Filled star+ starSpan.title = 'Remove from favorites';+ } else {+ starSpan.innerHTML = '☆'; // Empty star+ starSpan.title = 'Add to favorites';+ }++ // Handle star click+ starSpan.addEventListener('click', (e) => {+ e.preventDefault();+ e.stopPropagation();++ // Toggle favorite state+ const newIsFavorite = !isFavorite;++ // Call the callback+ onFavoriteToggle(item.value, item, newIsFavorite);++ // Update visual state immediately+ if (newIsFavorite) {+ starSpan.classList.add('ldr-is-favorite');+ starSpan.innerHTML = '★';+ starSpan.title = 'Remove from favorites';+ } else {+ starSpan.classList.remove('ldr-is-favorite');+ starSpan.innerHTML = '☆';+ starSpan.title = 'Add to favorites';+ }+ });++ div.appendChild(starSpan);+ }++ // Create label content span+ const labelSpan = document.createElement('span');+ labelSpan.className = 'ldr-dropdown-item-label';// Sanitize highlighted text to prevent XSSconst highlightedText = highlightText(item.label, searchText);// Allow basic HTML tags for highlighting but escape dangerous content- window.safeSetInnerHTML(div, highlightedText, true);+ window.safeSetInnerHTML(labelSpan, highlightedText, true);+ div.appendChild(labelSpan);+div.setAttribute('data-value', item.value);- div.addEventListener('click', (e) => {++ // Handle item click (on the label span or the whole item minus the star)+ const handleItemClick = (e) => {+ // Don't select if clicking on the star+ if (e.target.classList.contains('ldr-dropdown-favorite-star')) {+ return;+ }e.preventDefault();e.stopPropagation();// Set display value@@ -291,7 +389,9 @@setTimeout(() => {justSelected = false;}, 300);- });+ };++ div.addEventListener('click', handleItemClick);if (index === selectedIndex) {div.classList.add('active');@@ -461,7 +561,8 @@onSelect: onSelect,dropdownId: dropdownId,allowCustomValues: allowCustomValues,- noResultsText: noResultsText+ noResultsText: noResultsText,+ onFavoriteToggle: onFavoriteToggle};} else {console.warn('Cannot register dropdown: Missing input ID or dropdown list ID');diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex f737a2154a..92bc0fc0e1 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -206,7 +206,8 @@}},false,- 'No search engines available.'+ 'No search engines available.',+ handleSearchEngineFavoriteToggle);// If we have a last selected search engine, try to select it@@ -375,7 +376,8 @@}},false, // Don't allow custom values- 'No search engines available.'+ 'No search engines available.',+ handleSearchEngineFavoriteToggle);// Initialize search engine refresh button@@ -1620,6 +1622,13 @@return null;}+ function invalidateCacheKey(key) {+ if (memoryCache[key]) {+ delete memoryCache[key];+ console.log(`Cache invalidated for key: ${key}`);+ }+ }+// Load search engine optionsfunction loadSearchEngineOptions(forceRefresh = false) {return new Promise((resolve, reject) => {@@ -1826,6 +1835,65 @@});}+ // Handle toggling a search engine as favorite+ function handleSearchEngineFavoriteToggle(engineId, item, isFavorite) {+ console.log(`Toggling favorite for ${engineId}: ${isFavorite}`);++ // Make API call to toggle favorite+ fetch(URLS.SETTINGS_API.SEARCH_FAVORITES_TOGGLE, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')+ },+ body: JSON.stringify({ engine_id: engineId })+ })+ .then(response => response.json())+ .then(data => {+ console.log('Favorite toggled:', data);++ if (data.error) {+ console.error('Error toggling favorite:', data.error);+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`Error: ${data.error}`, 'error', 3000);+ }+ return;+ }++ // Update the local options with new favorite status+ const updatedFavorites = data.favorites || [];+ searchEngineOptions = searchEngineOptions.map(engine => ({+ ...engine,+ is_favorite: updatedFavorites.includes(engine.value)+ }));++ // Re-sort options: favorites first, then alphabetically+ searchEngineOptions.sort((a, b) => {+ const aFav = a.is_favorite === true;+ const bFav = b.is_favorite === true;+ if (aFav !== bFav) {+ return bFav ? 1 : -1;+ }+ return (a.label || '').localeCompare(b.label || '');+ });++ // Invalidate cache so next dropdown open gets fresh data+ invalidateCacheKey(CACHE_KEYS.SEARCH_ENGINES);++ // Show success message+ const action = data.is_favorite ? 'added to' : 'removed from';+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`Search engine ${action} favorites`, 'success', 2000);+ }+ })+ .catch(error => {+ console.error('Error toggling search engine favorite:', error);+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`Error updating favorites: ${error.message}`, 'error', 3000);+ }+ });+ }+// Save provider setting to databasefunction saveProviderSetting(providerValue) {// Only save to database, not localStoragediff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.jsindex 537915b5f1..224b3eaccc 100644--- a/src/local_deep_research/web/static/js/config/urls.js+++ b/src/local_deep_research/web/static/js/config/urls.js@@ -77,6 +77,8 @@ if (typeof URLS !== 'undefined') {LLM_CONFIG: '/settings/api/llm',SEARCH_TOOL: '/settings/api/search.tool',SEARCH_STRATEGY: '/settings/api/search.search_strategy',+ SEARCH_FAVORITES: '/settings/api/search-favorites',+ SEARCH_FAVORITES_TOGGLE: '/settings/api/search-favorites/toggle',SAVE_ALL_SETTINGS: '/settings/save_all_settings',RESET_TO_DEFAULTS: '/settings/reset_to_defaults',FIX_CORRUPTED_SETTINGS: '/settings/fix_corrupted_settings'diff --git a/tests/web/routes/test_search_favorites.py b/tests/web/routes/test_search_favorites.pynew file mode 100644index 0000000000..212f19e18c--- /dev/null+++ b/tests/web/routes/test_search_favorites.py@@ -0,0 +1,619 @@+"""Tests for search favorites API endpoints in settings_routes.py."""++from unittest.mock import patch, MagicMock+++# Settings routes are registered under /settings prefix+SETTINGS_PREFIX = "/settings"+++class TestGetSearchFavorites:+ """Tests for GET /settings/api/search-favorites endpoint."""++ def test_requires_authentication(self, client):+ """Should require authentication."""+ response = client.get(f"{SETTINGS_PREFIX}/api/search-favorites")+ assert response.status_code in [401, 302]++ def test_returns_empty_list_when_no_favorites(self, authenticated_client):+ """Should return empty list when no favorites are set."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # No favorites setting exists+ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = None+ mock_session.query.return_value = mock_query++ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search-favorites"+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == []++ def test_returns_favorites_list(self, authenticated_client):+ """Should return the list of favorite search engines."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # Mock favorites setting+ mock_setting = MagicMock()+ mock_setting.value = ["searxng", "arxiv", "brave", "serper"]++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search-favorites"+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == ["searxng", "arxiv", "brave", "serper"]++ def test_handles_invalid_favorites_value(self, authenticated_client):+ """Should return empty list when favorites value is not a list."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # Invalid favorites value (not a list)+ mock_setting = MagicMock()+ mock_setting.value = "not_a_list"++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search-favorites"+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == []+++class TestUpdateSearchFavorites:+ """Tests for PUT /settings/api/search-favorites endpoint."""++ def test_requires_authentication(self, client):+ """Should require authentication."""+ response = client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": ["searxng"]},+ )+ assert response.status_code in [401, 302]++ def test_requires_json_body(self, authenticated_client):+ """Should require JSON body."""+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ data="not json",+ content_type="text/plain",+ )+ # Flask may return 400 or 500 for invalid content type+ assert response.status_code in [400, 500]++ def test_requires_favorites_field(self, authenticated_client):+ """Should require favorites field in request."""+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"other_field": "value"},+ )+ assert response.status_code == 400+ data = response.get_json()+ assert "No favorites provided" in data["error"]++ def test_favorites_must_be_list(self, authenticated_client):+ """Should reject non-list favorites value."""+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": "not_a_list"},+ )+ assert response.status_code == 400+ data = response.get_json()+ assert "must be a list" in data["error"]++ def test_creates_new_favorites_setting(self, authenticated_client):+ """Should create new favorites setting if none exists."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # No existing setting+ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = None+ mock_session.query.return_value = mock_query++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": ["searxng", "arxiv"]},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == ["searxng", "arxiv"]+ assert "successfully" in data["message"]++ # Verify new setting was added+ mock_session.add.assert_called_once()+ mock_session.commit.assert_called_once()++ def test_updates_existing_favorites_setting(self, authenticated_client):+ """Should update existing favorites setting."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # Existing setting+ mock_setting = MagicMock()+ mock_setting.value = ["old_favorite"]++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": ["searxng", "brave"]},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == ["searxng", "brave"]++ # Verify setting was updated+ assert mock_setting.value == ["searxng", "brave"]+ mock_session.commit.assert_called_once()++ def test_accepts_empty_favorites_list(self, authenticated_client):+ """Should accept empty favorites list (clear all favorites)."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ mock_setting = MagicMock()+ mock_setting.value = ["searxng"]++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": []},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["favorites"] == []+++class TestToggleSearchFavorite:+ """Tests for POST /settings/api/search-favorites/toggle endpoint."""++ def test_requires_authentication(self, client):+ """Should require authentication."""+ response = client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "searxng"},+ )+ assert response.status_code in [401, 302]++ def test_requires_json_body(self, authenticated_client):+ """Should require JSON body."""+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ data="not json",+ content_type="text/plain",+ )+ # Flask may return 400 or 500 for invalid content type+ assert response.status_code in [400, 500]++ def test_requires_engine_id(self, authenticated_client):+ """Should require engine_id field."""+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"other_field": "value"},+ )+ assert response.status_code == 400+ data = response.get_json()+ assert "No engine_id provided" in data["error"]++ def test_adds_engine_to_favorites(self, authenticated_client):+ """Should add engine to favorites when not already a favorite."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # No existing favorites+ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = None+ mock_session.query.return_value = mock_query++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "searxng"},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["engine_id"] == "searxng"+ assert data["is_favorite"] is True+ assert "searxng" in data["favorites"]++ def test_removes_engine_from_favorites(self, authenticated_client):+ """Should remove engine from favorites when already a favorite."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # Existing favorites including the engine+ mock_setting = MagicMock()+ mock_setting.value = ["searxng", "arxiv", "brave"]++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "arxiv"},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["engine_id"] == "arxiv"+ assert data["is_favorite"] is False+ assert "arxiv" not in data["favorites"]+ assert "searxng" in data["favorites"]+ assert "brave" in data["favorites"]++ def test_toggle_creates_setting_if_not_exists(self, authenticated_client):+ """Should create favorites setting if it doesn't exist."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # No existing setting+ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = None+ mock_session.query.return_value = mock_query++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "brave"},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["is_favorite"] is True+ assert data["favorites"] == ["brave"]++ # Verify new setting was added+ mock_session.add.assert_called_once()+ mock_session.commit.assert_called_once()+++class TestAvailableSearchEnginesWithFavorites:+ """Tests for favorites in GET /settings/api/available-search-engines endpoint."""++ def test_requires_authentication(self, client):+ """Should require authentication."""+ response = client.get(f"{SETTINGS_PREFIX}/api/available-search-engines")+ assert response.status_code in [401, 302]++ def test_response_includes_favorites_field(self, authenticated_client):+ """Should include favorites field in response."""+ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/available-search-engines"+ )++ assert response.status_code == 200+ data = response.get_json()++ # Check response structure includes favorites+ assert "favorites" in data+ assert isinstance(data["favorites"], list)++ def test_engine_options_include_is_favorite_field(+ self, authenticated_client+ ):+ """Should include is_favorite field for each engine option."""+ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/available-search-engines"+ )++ assert response.status_code == 200+ data = response.get_json()++ # Check engine_options have is_favorite field+ assert "engine_options" in data+ if data["engine_options"]:+ for option in data["engine_options"]:+ assert "is_favorite" in option+ assert isinstance(option["is_favorite"], bool)++ def test_favorites_workflow_with_available_engines(+ self, authenticated_client+ ):+ """Test that favoriting an engine shows up in available-search-engines."""+ # First, get the list of available engines+ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/available-search-engines"+ )+ assert response.status_code == 200+ data = response.get_json()++ # Check initial state - no favorites+ assert data["favorites"] == []++ # Get an engine to favorite (if any are available)+ if data["engine_options"]:+ engine_to_favorite = data["engine_options"][0]["value"]++ # Add it as favorite+ toggle_response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": engine_to_favorite},+ )+ assert toggle_response.status_code == 200+ toggle_data = toggle_response.get_json()+ assert toggle_data["is_favorite"] is True++ # Verify it shows up in available-search-engines+ response2 = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/available-search-engines"+ )+ assert response2.status_code == 200+ data2 = response2.get_json()++ # The engine should now be in favorites+ assert engine_to_favorite in data2["favorites"]++ # The engine should be marked as favorite in options+ for option in data2["engine_options"]:+ if option["value"] == engine_to_favorite:+ assert option["is_favorite"] is True+ break+++class TestSearchFavoritesIntegration:+ """Integration tests for search favorites workflow."""++ def test_full_favorites_workflow(self, authenticated_client):+ """Test complete workflow: add, get, remove favorites."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ # Track favorites state+ favorites_state = {"value": []}+ mock_setting = MagicMock()+ mock_setting.value = favorites_state["value"]++ def get_mock_setting():+ mock_setting.value = favorites_state["value"]+ return mock_setting++ mock_query = MagicMock()+ mock_query.filter.return_value.first.side_effect = (+ lambda: get_mock_setting()+ )+ mock_session.query.return_value = mock_query++ # Step 1: Get empty favorites+ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search-favorites"+ )+ assert response.status_code == 200+ assert response.get_json()["favorites"] == []++ # Step 2: Add searxng to favorites+ favorites_state["value"] = [] # Reset for toggle+ mock_query.filter.return_value.first.return_value = (+ None # No setting exists+ )++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "searxng"},+ )+ assert response.status_code == 200+ data = response.get_json()+ assert data["is_favorite"] is True++ # Step 3: Add arxiv to favorites+ favorites_state["value"] = ["searxng"]+ mock_setting.value = ["searxng"]+ mock_query.filter.return_value.first.return_value = mock_setting++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "arxiv"},+ )+ assert response.status_code == 200+ data = response.get_json()+ assert data["is_favorite"] is True+ assert set(data["favorites"]) == {"searxng", "arxiv"}++ # Step 4: Remove searxng from favorites+ favorites_state["value"] = ["searxng", "arxiv"]+ mock_setting.value = ["searxng", "arxiv"]++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "searxng"},+ )+ assert response.status_code == 200+ data = response.get_json()+ assert data["is_favorite"] is False+ assert data["favorites"] == ["arxiv"]++ def test_bulk_update_favorites(self, authenticated_client):+ """Test updating all favorites at once via PUT."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ mock_setting = MagicMock()+ mock_setting.value = ["old1", "old2"]++ mock_query = MagicMock()+ mock_query.filter.return_value.first.return_value = mock_setting+ mock_session.query.return_value = mock_query++ # Bulk update to new favorites+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": ["searxng", "arxiv", "brave", "serper"]},+ )++ assert response.status_code == 200+ data = response.get_json()+ assert set(data["favorites"]) == {+ "searxng",+ "arxiv",+ "brave",+ "serper",+ }+++class TestSearchFavoritesErrorHandling:+ """Tests for error handling in search favorites endpoints."""++ def test_get_favorites_handles_db_error(self, authenticated_client):+ """Should handle database errors gracefully in GET."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session_ctx.return_value.__enter__ = MagicMock(+ side_effect=Exception("Database connection failed")+ )++ response = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search-favorites"+ )++ assert response.status_code == 500+ data = response.get_json()+ assert "error" in data++ def test_put_favorites_handles_db_error(self, authenticated_client):+ """Should handle database errors gracefully in PUT."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session_ctx.return_value.__enter__ = MagicMock(+ side_effect=Exception("Database connection failed")+ )++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search-favorites",+ json={"favorites": ["searxng"]},+ )++ assert response.status_code == 500+ data = response.get_json()+ assert "error" in data++ def test_toggle_favorites_handles_db_error(self, authenticated_client):+ """Should handle database errors gracefully in toggle."""+ with patch(+ "src.local_deep_research.web.routes.settings_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session_ctx.return_value.__enter__ = MagicMock(+ side_effect=Exception("Database connection failed")+ )++ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/search-favorites/toggle",+ json={"engine_id": "searxng"},+ )++ assert response.status_code == 500+ data = response.get_json()+ assert "error" in data