~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
feat(search): group the search-engine selector into ordered bands with headers (#4814)
LearningCircuitee3c82835fb9
diff --git a/changelog.d/4814.feature.md b/changelog.d/4814.feature.mdnew file mode 100644index 0000000000..de5ae0ecae--- /dev/null+++ b/changelog.d/4814.feature.md@@ -0,0 +1 @@+**The search-engine selector is now grouped into labelled bands.** Engines are ordered by a trust/cost gradient with section headers — Favorites, Collections, Academic, Local RAG, Books, Code, News, No API key, API key — instead of one alphabetical list. Starring an engine still pins it to the Favorites band at the top.diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 18aa3d9d68..7dd187df8d 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1651,6 +1651,12 @@ def api_get_available_search_engines(try:# Get search engines using the same approach as search_engines_config.pyfrom ...web_search_engines.search_engines_config import search_config+ from ...web_search_engines.engine_groups import (+ classify_engine_group,+ effective_group,+ group_label,+ group_order,+ )username = session["username"]search_engines = search_config(username=username, db_session=db_session)@@ -1709,6 +1715,15 @@ def api_get_available_search_engines(# Check if engine is a favoriteis_favorite = engine_id in favorites+ # Classify the engine into a selector band. base_group ignores+ # favorite status (used by the frontend to move an engine back+ # to its category when un-starred); the effective band is the+ # Favorites overlay when starred. See engine_groups.py.+ base_group = classify_engine_group(+ engine_id, category, requires_api_key+ )+ shown_group = effective_group(base_group, is_favorite)+engines_dict[engine_id] = {"display_name": base_name,"description": engine_data.get("description", ""),@@ -1727,13 +1742,20 @@ def api_get_available_search_engines("category": category,"requires_api_key": requires_api_key,"is_favorite": is_favorite,+ "group": shown_group,+ "group_label": group_label(shown_group),+ "group_order": group_order(shown_group),+ "base_group": base_group,+ "base_group_label": group_label(base_group),+ "base_group_order": group_order(base_group),})- # Sort engine_options: favorites first, then alphabetically by label+ # Sort engine_options by band order (favorites band first), then+ # alphabetically by label within each band.engine_options.sort(key=lambda x: (- not x.get("is_favorite", False),+ x.get("group_order", 999),x.get("label", "").lower(),))diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.cssindex 83e5dd59b8..b721f0c7ab 100644--- a/src/local_deep_research/web/static/css/custom_dropdown.css+++ b/src/local_deep_research/web/static/css/custom_dropdown.css@@ -135,6 +135,25 @@ body.ldr-dropdown-active {align-items: center;}+/* Band/group header rows (non-selectable section dividers) */+.ldr-custom-dropdown-group-header {+ padding: 6px 15px;+ font-size: 0.72rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--text-muted, #8a8aa0);+ background-color: var(--bg-secondary, #1e1e2d);+ border-top: 1px solid var(--border-color, #343452);+ cursor: default;+ user-select: none;+}++/* The very first header sits at the top of the list, so no divider above it */+.ldr-custom-dropdown-group-header:first-child {+ border-top: none;+}+.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 4815943c37..d823b23cc9 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@@ -16,6 +16,38 @@// Keep a registry of inputs and their associated options functionsconst dropdownRegistry = {};+ /**+ * Create a non-selectable band/group header row for the dropdown.+ * Headers use a distinct class so keyboard navigation (which queries+ * `.ldr-custom-dropdown-item`) skips them automatically.+ * @param {string} label - The band header text+ * @returns {HTMLElement} The header div element+ */+ function createGroupHeaderElement(label) {+ const header = document.createElement('div');+ header.className = 'ldr-custom-dropdown-group-header';+ header.setAttribute('role', 'presentation');+ header.setAttribute('aria-hidden', 'true');+ window.safeSetTextContent(header, label);+ return header;+ }++ /**+ * Insert a group header before `item` when its band differs from the one+ * last rendered. Grouping is opt-in per item: options without a+ * `group_label` (e.g. model dropdowns) never get headers.+ * @param {HTMLElement} dropdownList - The list container+ * @param {Object} item - The current option (may carry `group_label`)+ * @param {{last: ?string}} state - Mutable tracker of the current band+ */+ function maybeAppendGroupHeader(dropdownList, item, state) {+ const label = item && item.group_label;+ if (label && label !== state.last) {+ dropdownList.appendChild(createGroupHeaderElement(label));+ state.last = label;+ }+ }+/*** Create a favorite star element with proper accessibility attributes* @param {Object} item - The item object with value and is_favorite properties@@ -118,7 +150,12 @@return;}+ const groupState = { last: null };filteredData.forEach((item, index) => {+ // Insert a band header when the group changes (no-op for+ // options without a group_label).+ maybeAppendGroupHeader(dropdownList, item, groupState);+const div = document.createElement('div');div.className = 'ldr-custom-dropdown-item';@@ -357,7 +394,12 @@// Get dropdown ID for generating unique option IDsconst dropdownId = dropdownList.id.replace('-list', '');+ const groupState = { last: null };filteredData.forEach((item, index) => {+ // Insert a band header when the group changes (no-op for+ // options without a group_label).+ maybeAppendGroupHeader(dropdownList, item, groupState);+const div = document.createElement('div');div.className = 'ldr-custom-dropdown-item';diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex a4e8cdff08..ed3046d5ed 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -2099,12 +2099,19 @@if (data && data.engine_options) {SafeLogger.log('Processing engine_options:', data.engine_options.length + ' options');- // Map the engine options to our dropdown format+ // Map the engine options to our dropdown format. The+ // group_* fields drive the band headers/ordering; the+ // base_group_* fields let a favorite toggle move an+ // engine back to its category band without re-fetching.formattedEngines = data.engine_options.map(engine => ({value: engine.value || engine.id || '',label: engine.label || engine.name || engine.value || '',type: engine.type || 'search',- is_favorite: engine.is_favorite || false+ is_favorite: engine.is_favorite || false,+ group_label: engine.group_label,+ group_order: engine.group_order,+ base_group_label: engine.base_group_label,+ base_group_order: engine.base_group_order}));}// Also try adding engines from engines object if it exists@@ -2286,23 +2293,32 @@return;}- // Update the local options with new favorite status+ // Update the local options with new favorite status. A starred+ // engine moves to the Favorites band; un-starring returns it to its+ // category band (base_group_*). Favorites is the top band, mirroring+ // engine_groups.SEARCH_ENGINE_GROUPS[0] on the server.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 || '');+ const FAVORITES_BAND = { label: 'Favorites', order: 0 };+ searchEngineOptions = searchEngineOptions.map(engine => {+ const isFav = updatedFavorites.includes(engine.value);+ return {+ ...engine,+ is_favorite: isFav,+ group_label: isFav ? FAVORITES_BAND.label : engine.base_group_label,+ group_order: isFav ? FAVORITES_BAND.order : engine.base_group_order+ };});+ // Re-sort by band order (favorites first), then alphabetically+ // within each band. group_order can be 0, so don't treat it as falsy.+ const bandOrder = (engine) => {+ return typeof engine.group_order === 'number' ? engine.group_order : 999;+ };+ searchEngineOptions.sort((a, b) =>+ (bandOrder(a) - bandOrder(b)) ||+ (a.label || '').localeCompare(b.label || '')+ );+// Invalidate cache so next dropdown open gets fresh datainvalidateCacheKey(CACHE_KEYS.SEARCH_ENGINES);diff --git a/src/local_deep_research/web_search_engines/engine_groups.py b/src/local_deep_research/web_search_engines/engine_groups.pynew file mode 100644index 0000000000..783e2f4725--- /dev/null+++ b/src/local_deep_research/web_search_engines/engine_groups.py@@ -0,0 +1,103 @@+"""Grouping and ordering of search engines in the selector UI.++Single source of truth for which band a search engine falls into and the order+the bands appear in. The available-search-engines API attaches each engine's+band to the response and the frontend renders one header per band, so the+bucketing logic lives here only and is never duplicated in JavaScript.+"""++from dataclasses import dataclass+++@dataclass(frozen=True)+class SearchEngineGroup:+ """A band in the search-engine selector dropdown."""++ key: str # stable identifier, e.g. "academic"+ label: str # header text shown in the dropdown+ icon: str # emoji associated with the band+++# Bands in display order, top to bottom; the list index IS the sort order+# (lower sorts higher). "favorites" is an overlay band: a starred engine is+# shown here regardless of its category — see effective_group().+SEARCH_ENGINE_GROUPS: tuple[SearchEngineGroup, ...] = (+ SearchEngineGroup("favorites", "Favorites", "⭐"),+ SearchEngineGroup("collections", "Collections", "📁"),+ SearchEngineGroup("academic", "Academic", "🔬"),+ SearchEngineGroup("local_rag", "Local RAG", "📂"),+ SearchEngineGroup("books", "Books", "📚"),+ SearchEngineGroup("code", "Code", "💻"),+ SearchEngineGroup("news", "News", "📰"),+ SearchEngineGroup("no_api_key", "No API key", "🌐"),+ SearchEngineGroup("api_key", "API key", "🔑"),+)++# Not a secret — the band's identifier string; matches SEARCH_ENGINE_GROUPS[0].+FAVORITES_GROUP_KEY = "favorites" # gitleaks:allow++_GROUP_BY_KEY: dict[str, SearchEngineGroup] = {+ group.key: group for group in SEARCH_ENGINE_GROUPS+}+_GROUP_ORDER: dict[str, int] = {+ group.key: index for index, group in enumerate(SEARCH_ENGINE_GROUPS)+}++# Maps the category label produced by+# settings_routes._get_engine_icon_and_category() to a band. Any category not+# listed here (e.g. "Web Search", "Search") falls through to the API-key split.+# Keep these strings in sync with that function.+_CATEGORY_TO_GROUP: dict[str, str] = {+ "Scientific": "academic",+ "Local RAG": "local_rag",+ "Books": "books",+ "Code": "code",+ "News": "news",+}+++def is_collection_engine(engine_id: str) -> bool:+ """True for the document-collection pseudo-engines: the aggregate+ "Search All Collections" entry (``library``) and the per-collection+ ``collection_<id>`` entries."""+ return engine_id == "library" or engine_id.startswith("collection_")+++def classify_engine_group(+ engine_id: str, category: str, requires_api_key: bool+) -> str:+ """Return the base band key for an engine, ignoring favorite status.++ Document collections come first, then engines with a distinct category+ (academic / local / books / code / news); everything else (generic web+ search) is split only by whether it needs an API key.+ """+ if is_collection_engine(engine_id):+ return "collections"+ category_group = _CATEGORY_TO_GROUP.get(category)+ if category_group is not None:+ return category_group+ return "api_key" if requires_api_key else "no_api_key"+++def effective_group(base_group_key: str, is_favorite: bool) -> str:+ """The band an engine is actually shown in: the Favorites overlay wins over+ the engine's base category so a starred engine floats to the top band."""+ return FAVORITES_GROUP_KEY if is_favorite else base_group_key+++def group_order(group_key: str) -> int:+ """Sort index for a band (lower sorts higher); unknown keys sort last."""+ return _GROUP_ORDER.get(group_key, len(SEARCH_ENGINE_GROUPS))+++def group_label(group_key: str) -> str:+ """Header text for a band; falls back to the key if unknown."""+ group = _GROUP_BY_KEY.get(group_key)+ return group.label if group is not None else group_key+++def group_icon(group_key: str) -> str:+ """Emoji for a band; empty string if unknown."""+ group = _GROUP_BY_KEY.get(group_key)+ return group.icon if group is not None else ""diff --git a/tests/js/components/custom-dropdown.test.js b/tests/js/components/custom-dropdown.test.jsindex e19cca0ee0..09af7859d3 100644--- a/tests/js/components/custom-dropdown.test.js+++ b/tests/js/components/custom-dropdown.test.js@@ -224,6 +224,113 @@ describe('setupCustomDropdown', () => {dd.destroy();});});++ describe('group headers', () => {+ const grouped = [+ { value: 'fav1', label: 'Pinned One', group_label: 'Favorites' },+ { value: 'arxiv', label: 'ArXiv', group_label: 'Academic' },+ { value: 'pubmed', label: 'PubMed', group_label: 'Academic' },+ { value: 'tavily', label: 'Tavily', group_label: 'API key' },+ ];++ it('renders one non-selectable header per band, in order', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.click();+ const headers = dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header');+ expect(Array.from(headers).map(h => h.textContent)).toEqual([+ 'Favorites', 'Academic', 'API key',+ ]);+ headers.forEach(h =>+ expect(h.classList.contains('ldr-custom-dropdown-item')).toBe(false)+ );+ dd.destroy();+ });++ it('keeps the selectable option count equal to items (headers excluded)', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.click();+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');+ expect(items.length).toBe(4);+ dd.destroy();+ });++ it('shows a band header once even when it has multiple items', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.click();+ const academic = Array.from(+ dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header')+ ).filter(h => h.textContent === 'Academic');+ expect(academic.length).toBe(1);+ dd.destroy();+ });++ it('hides a band header when filtering removes all its items', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.value = 'arxiv';+ input.dispatchEvent(new Event('input'));+ const headerTexts = Array.from(+ dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header')+ ).map(h => h.textContent);+ expect(headerTexts).toEqual(['Academic']);+ dd.destroy();+ });++ it('renders no headers when options have no group_label', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);+ input.click();+ const headers = dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header');+ expect(headers.length).toBe(0);+ dd.destroy();+ });++ it('marks headers as presentational so assistive tech skips them', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.click();+ const header = dropdownList.querySelector('.ldr-custom-dropdown-group-header');+ expect(header.getAttribute('role')).toBe('presentation');+ expect(header.getAttribute('aria-hidden')).toBe('true');+ dd.destroy();+ });++ it('keyboard navigation lands on an item, never a header', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ // First ArrowDown must select the first ITEM (fav1), not the+ // 'Favorites' header that precedes it.+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));+ const active = dropdownList.querySelector('.active');+ expect(active.classList.contains('ldr-custom-dropdown-item')).toBe(true);+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ expect(onSelect).toHaveBeenCalledWith('fav1', expect.objectContaining({ value: 'fav1' }));+ dd.destroy();+ });++ it('renders both favorite stars and band headers when both apply', () => {+ const onFavoriteToggle = vi.fn();+ const dd = setupCustomDropdown(+ input, dropdownList, () => grouped, onSelect, false, 'No results found.', onFavoriteToggle+ );+ input.click();+ expect(dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header').length).toBe(3);+ expect(dropdownList.querySelectorAll('.ldr-dropdown-favorite-star').length).toBe(4);+ dd.destroy();+ });++ it('updateDropdownOptions re-renders band headers for the open list', () => {+ const dd = setupCustomDropdown(input, dropdownList, () => grouped, onSelect);+ input.click();+ const newOptions = [+ { value: 'wiki', label: 'Wikipedia', group_label: 'No API key' },+ { value: 'serper', label: 'Serper', group_label: 'API key' },+ ];+ updateDropdownOptions(input, newOptions);+ const headerTexts = Array.from(+ dropdownList.querySelectorAll('.ldr-custom-dropdown-group-header')+ ).map(h => h.textContent);+ expect(headerTexts).toEqual(['No API key', 'API key']);+ expect(dropdownList.querySelectorAll('.ldr-custom-dropdown-item').length).toBe(2);+ dd.destroy();+ });+ });});describe('updateDropdownOptions', () => {diff --git a/tests/web_search_engines/test_engine_groups.py b/tests/web_search_engines/test_engine_groups.pynew file mode 100644index 0000000000..2b53082cfd--- /dev/null+++ b/tests/web_search_engines/test_engine_groups.py@@ -0,0 +1,154 @@+"""Tests for the search-engine selector grouping/ordering logic."""++from local_deep_research.web_search_engines.engine_groups import (+ FAVORITES_GROUP_KEY,+ SEARCH_ENGINE_GROUPS,+ classify_engine_group,+ effective_group,+ group_icon,+ group_label,+ group_order,+ is_collection_engine,+)+++class TestIsCollectionEngine:+ def test_library_aggregate_is_collection(self):+ assert is_collection_engine("library") is True++ def test_per_collection_pseudo_engine(self):+ assert is_collection_engine("collection_42") is True++ def test_regular_engine_is_not_collection(self):+ assert is_collection_engine("arxiv") is False+ assert is_collection_engine("tavily") is False+++class TestClassifyEngineGroup:+ def test_collections_win_over_category(self):+ # A collection is still "collections" even though it is Local RAG.+ assert (+ classify_engine_group("collection_1", "Local RAG", False)+ == "collections"+ )+ assert (+ classify_engine_group("library", "Local RAG", False)+ == "collections"+ )++ def test_academic(self):+ # Free and keyed academic engines both land in academic.+ assert classify_engine_group("arxiv", "Scientific", False) == "academic"+ assert (+ classify_engine_group("nasa_ads", "Scientific", True) == "academic"+ )++ def test_local_rag_non_collection(self):+ assert (+ classify_engine_group("elasticsearch", "Local RAG", False)+ == "local_rag"+ )++ def test_books_code_news_have_own_bands_regardless_of_key(self):+ assert classify_engine_group("gutenberg", "Books", False) == "books"+ # github is Code AND requires a key -> still the Code band, not api_key.+ assert classify_engine_group("github", "Code", True) == "code"+ assert classify_engine_group("wikinews", "News", False) == "news"++ def test_generic_web_split_by_api_key(self):+ assert classify_engine_group("ddg", "Web Search", False) == "no_api_key"+ assert classify_engine_group("tavily", "Web Search", True) == "api_key"+ # The default "Search" category also splits by key.+ assert (+ classify_engine_group("wikipedia", "Search", False) == "no_api_key"+ )+++class TestEffectiveGroup:+ def test_favorite_overrides_category(self):+ assert effective_group("academic", True) == FAVORITES_GROUP_KEY++ def test_non_favorite_keeps_base(self):+ assert effective_group("academic", False) == "academic"+++class TestGroupOrdering:+ def test_favorites_sorts_first(self):+ assert group_order("favorites") == 0++ def test_full_band_order_is_as_specified(self):+ expected = [+ "favorites",+ "collections",+ "academic",+ "local_rag",+ "books",+ "code",+ "news",+ "no_api_key",+ "api_key",+ ]+ assert [g.key for g in SEARCH_ENGINE_GROUPS] == expected+ # group_order is strictly increasing in that sequence.+ orders = [group_order(key) for key in expected]+ assert orders == sorted(orders)+ assert orders == list(range(len(expected)))++ def test_unknown_group_sorts_last(self):+ assert group_order("nope") == len(SEARCH_ENGINE_GROUPS)+++class TestGroupLabelAndIcon:+ def test_known_labels(self):+ assert group_label("no_api_key") == "No API key"+ assert group_label("api_key") == "API key"+ assert group_label("favorites") == "Favorites"++ def test_unknown_label_falls_back_to_key(self):+ assert group_label("mystery") == "mystery"++ def test_icons(self):+ assert group_icon("favorites") == "⭐"+ assert group_icon("mystery") == ""+++class TestEndToEndOrdering:+ """A representative engine set sorts into the intended band order."""++ def test_engines_sort_into_bands(self):+ # (engine_id, category, requires_api_key, is_favorite)+ engines = [+ ("tavily", "Web Search", True, False), # api_key+ ("arxiv", "Scientific", False, False), # academic+ ("collection_7", "Local RAG", False, False), # collections+ ("ddg", "Web Search", False, False), # no_api_key+ ("github", "Code", True, False), # code+ ("elasticsearch", "Local RAG", False, False), # local_rag+ ("brave", "Web Search", True, True), # favorite (overlay)+ ("gutenberg", "Books", False, False), # books+ ("wikinews", "News", False, False), # news+ ]+ options = []+ for engine_id, category, key, fav in engines:+ base = classify_engine_group(engine_id, category, key)+ shown = effective_group(base, fav)+ options.append(+ {+ "value": engine_id,+ "label": engine_id,+ "group_order": group_order(shown),+ }+ )+ options.sort(key=lambda x: (x["group_order"], x["label"].lower()))+ ordered_ids = [o["value"] for o in options]+ assert ordered_ids == [+ "brave", # favorites+ "collection_7", # collections+ "arxiv", # academic+ "elasticsearch", # local_rag+ "gutenberg", # books+ "github", # code+ "wikinews", # news+ "ddg", # no_api_key+ "tavily", # api_key+ ]