~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(web): preserve unavailable saved search providers (#7595)
LearningCircuitc0eb0dbbf071
diff --git a/changelog.d/7570.bugfix.md b/changelog.d/7570.bugfix.mdnew file mode 100644index 0000000000..9aa7d95b7f--- /dev/null+++ b/changelog.d/7570.bugfix.md@@ -0,0 +1 @@+Keep unavailable saved search engines visible on the research form and require an explicit provider selection before starting research.diff --git a/docs/search-engines.md b/docs/search-engines.mdindex 1e379fa807..488eb86dc2 100644--- a/docs/search-engines.md+++ b/docs/search-engines.md@@ -134,8 +134,8 @@ follow the configured egress policy.Wayback is excluded from the primary search picker and topic/auto search.Saved `search.tool=wayback` values are not rewritten: choose a configured search-provider in Settings for topic queries. The research form selects an available-provider when the saved choice is absent from its picker; check that selection+provider in Settings for topic queries. The research form keeps an unlisted saved+choice visible with a notice and requires you to choose a configured providerbefore starting research. Existing Wayback settings remain available, and the legacy`WaybackSearchEngine` class and engine factory registration still supportprogrammatic URL or domain lookups, optionally with a path. Itsdiff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex e13badc8f2..d12f722573 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -117,6 +117,9 @@const modelSelectedIndex = -1;let searchEngineOptions = [];let selectedSearchEngineValue = '';+ let unavailableSearchEngineValue = '';+ let hasExplicitSearchEngineSelection = false;+ let initialSearchEngineOptionsPending = true;const searchEngineSelectedIndex = -1;// Generation token + AbortController for the egress-scope@@ -394,7 +397,20 @@// Then load data asynchronously (don't block UI)Promise.all([loadModelOptions(false),- loadSearchEngineOptions(false)+ loadSearchEngineOptions(false).then(engines => {+ // Reconcile even cached/error-fallback results before a+ // research submit can use the server-rendered hidden value.+ // Model/settings loading may still be pending at this point.+ reconcileSearchEngineSelection(engines);+ initialSearchEngineOptionsPending = false;+ const loadingAlert = document.querySelector('#research-alert [data-search-engine-loading]');+ if (loadingAlert) {+ const container = loadingAlert.parentNode;+ loadingAlert.remove();+ if (!container.firstChild) container.style.display = 'none';+ }+ return engines;+ })]).then(([_modelData, searchEngineData]) => {// After loading model data, update the UI with the loaded dataconst currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';@@ -412,6 +428,9 @@searchEngineDropdownList,() => (searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }]),(value, item) => {+ if (searchEngineOptions.some(engine => engine.value === value && !engine.disabled)) {+ hasExplicitSearchEngineSelection = true;+ }selectedSearchEngineValue = value;// Update the input field@@ -420,6 +439,7 @@} else {searchEngineInput.value = value;}+ reconcileSearchEngineSelection(searchEngineOptions);// custom_dropdown dispatches the hidden input's// change event immediately after this callback;@@ -439,24 +459,7 @@// If we have a last selected search engine, try to select it if allowedconst lastSearchEngine = searchEngineInput?.getAttribute('data-initial-value') ||localStorage.getItem('selected_search_engine');- if (lastSearchEngine) {- const matchingEngine = searchEngineOptions.find(engine =>- (engine.value === lastSearchEngine || engine.id === lastSearchEngine) && !engine.disabled);-- if (matchingEngine) {- searchEngineInput.value = matchingEngine.label;- selectedSearchEngineValue = matchingEngine.value;-- const hiddenInput = document.getElementById('search_engine_hidden');- if (hiddenInput) {- hiddenInput.value = matchingEngine.value;- }- } else {- reconcileSearchEngineSelection(searchEngineOptions);- }- } else {- reconcileSearchEngineSelection(searchEngineOptions);- }+ reconcileSearchEngineSelection(searchEngineOptions, lastSearchEngine || '');}}@@ -587,6 +590,9 @@},(value, item) => {SafeLogger.log('Search engine selected:', value, item);+ if (searchEngineOptions.some(engine => engine.value === value && !engine.disabled)) {+ hasExplicitSearchEngineSelection = true;+ }selectedSearchEngineValue = value;// Update the input field with the selected search engine's label or value@@ -602,6 +608,7 @@if (seHidden) {seHidden.value = value;}+ reconcileSearchEngineSelection(searchEngineOptions);// The dropdown dispatches change on the hidden input after// this callback; let that listener own the write so a@@ -679,27 +686,10 @@}}- // Set initial search engine value if available and allowed+ // Reconcile the saved value even when it is absent from the options.if (searchEngineInput) {const initialSearchEngine = searchEngineInput.getAttribute('data-initial-value');- if (initialSearchEngine) {- const matchingEngine = searchEngineOptions.find(e =>- (e.value === initialSearchEngine || e.id === initialSearchEngine) && !e.disabled- );-- if (matchingEngine) {- searchEngineInput.value = matchingEngine.label;- selectedSearchEngineValue = matchingEngine.value;- const hiddenInput = document.getElementById('search_engine_hidden');- if (hiddenInput) {- hiddenInput.value = selectedSearchEngineValue;- }- } else {- reconcileSearchEngineSelection(searchEngineOptions);- }- } else {- reconcileSearchEngineSelection(searchEngineOptions);- }+ reconcileSearchEngineSelection(searchEngineOptions, initialSearchEngine || '');}}@@ -1999,33 +1989,13 @@}});- // Update search engine if we have a valid allowed value+ // Settings are authoritative, including a saved engine that+ // is no longer offered for topic searches (such as Wayback).const searchEngineSetting = data.settings["search.tool"];if (searchEngineSetting && searchEngineSetting.value && searchEngineInput) {const engineValue = searchEngineSetting.value;SafeLogger.log('Setting search engine to:', engineValue);-- // Find the engine in our loaded options (must not be disabled)- const matchingEngine = searchEngineOptions.find(e =>- (e.value === engineValue || e.id === engineValue) && !e.disabled- );-- if (matchingEngine) {- SafeLogger.log('Found matching search engine in options:', matchingEngine);-- // Set the input field value- searchEngineInput.value = matchingEngine.label || engineValue;- selectedSearchEngineValue = engineValue;-- // Also update hidden input if it exists- const hiddenInput = document.getElementById('search_engine_hidden');- if (hiddenInput) {- hiddenInput.value = engineValue;- }- } else {- reconcileSearchEngineSelection(searchEngineOptions);- }-+ reconcileSearchEngineSelection(searchEngineOptions, engineValue);searchEngineInput.disabled = !searchEngineSetting.editable;}@@ -2858,35 +2828,76 @@return null;}- // Reconcile the current search-engine selection against the latest- // option list. Called after every options refresh (initial load,- // scope change, strategy change, refresh button) so the dropdown- // never carries a selection that the new options have hidden.- //- // Rules:- // 1. If the current selection is still in the new options AND- // not disabled, keep it (the user's last pick is preserved).- // 2. Otherwise, fall back to a pre-configured favorite:- // SearXNG first, then "Search All Collections" (library).- // 3. If neither is available, fall back to the first non-disabled- // option so the form is never submitted with a value the- // backend would refuse.- // 4. If nothing is selectable, clear the selection.- //- // This is a UI-only change — the user's saved search.tool in the- // settings DB is not touched, so a returning user still sees their- // saved primary on the next page load.- function reconcileSearchEngineSelection(options) {+ // Reuse the custom-model notice style for a saved engine that is no+ // longer configured. Keep this separate from transient submit alerts so+ // typing, an unsuccessful submit, or refreshing cannot dismiss it.+ function showSavedSearchEngineWarning(value = '') {+ unavailableSearchEngineValue = value;+ const input = searchEngineInput || document.getElementById('search_engine');+ let warning = document.getElementById('saved-search-engine-warning');+ if (!warning && value && input) {+ warning = document.createElement('div');+ warning.id = 'saved-search-engine-warning';+ warning.className = 'ldr-model-warning';+ warning.setAttribute('role', 'status');+ warning.textContent = 'The saved search engine is unavailable. Choose a configured search provider before starting research.';+ const parent = input.closest('.ldr-form-group, .form-group') || input.parentNode;+ if (parent) parent.appendChild(warning);+ }+ if (warning) {+ warning.style.display = value ? 'block' : 'none';+ if (input) {+ const descriptions = (input.getAttribute('aria-describedby') || '')+ .split(/\s+/).filter(id => id && id !== warning.id);+ if (value) descriptions.push(warning.id);+ if (descriptions.length) {+ input.setAttribute('aria-describedby', descriptions.join(' '));+ } else {+ input.removeAttribute('aria-describedby');+ }+ }+ }+ if (value && advancedPanel && !advancedPanel.classList.contains('ldr-expanded')) {+ applyAdvancedOptionsState(true);+ }+ }++ // Preserve enabled selections and keep unlisted saved choices visible+ // with a notice until the user chooses a configured provider. A choice+ // removed or disabled by a policy/strategy refresh still uses the existing+ // preferred-default / first-enabled fallback. No settings are saved here.+ function reconcileSearchEngineSelection(options, savedValue = '') {const list = Array.isArray(options) ? options : searchEngineOptions;if (!Array.isArray(list)) return;const input = searchEngineInput || document.getElementById('search_engine');const hidden = document.getElementById('search_engine_hidden');- const current = selectedSearchEngineValue || (hidden ? hidden.value : '') || (input ? input.getAttribute('data-initial-value') : '');+ // Initial options and settings can finish after the user has picked+ // a configured engine. Neither a stale template nor a late settings+ // GET may restore the old saved value over that explicit choice.+ const initial = !hasExplicitSearchEngineSelection && input+ ? input.getAttribute('data-initial-value') : '';+ const saved = hasExplicitSearchEngineSelection ? '' : savedValue;+ const current = saved || selectedSearchEngineValue || (hidden ? hidden.value : '') || initial;const currentOpt = current- ? list.find((o) => o && o.value === current)+ ? list.find((o) => o && (o.value === current || o.id === current)): null;+ const preserveSaved = saved || unavailableSearchEngineValue === current ||+ (!selectedSearchEngineValue && initial === current);+ if (current && !currentOpt && preserveSaved) {+ selectedSearchEngineValue = current;+ if (input) {+ input.value = current === 'wayback'+ ? 'Wayback (saved; choose a configured search provider for topics)'+ : `${current} (saved; unavailable)`;+ }+ if (hidden) hidden.value = current;+ showSavedSearchEngineWarning(current);+ return;+ }++ showSavedSearchEngineWarning();if (currentOpt && !currentOpt.disabled) {// The previously selected value is still visible/enabled;// keep it (rule 1). Keep inputs in sync.@@ -3569,6 +3580,21 @@}return;}++ if (initialSearchEngineOptionsPending) {+ showAlert('Search providers are still loading. Please wait before starting research.', 'info');+ const loadingAlert = document.querySelector('#research-alert .alert[data-submit-alert="true"]');+ if (loadingAlert) loadingAlert.setAttribute('data-search-engine-loading', 'true');+ return;+ }++ // A saved-but-unlisted engine must never be silently replaced or+ // submitted. Filtering the dropdown is not a provider selection.+ if (unavailableSearchEngineValue) {+ showSavedSearchEngineWarning(unavailableSearchEngineValue);+ if (searchEngineInput) searchEngineInput.focus();+ return;+ }}// Clear any previous validation errorsdiff --git a/tests/js/components/research-saved-search-engine.test.js b/tests/js/components/research-saved-search-engine.test.jsnew file mode 100644index 0000000000..64cc032c36--- /dev/null+++ b/tests/js/components/research-saved-search-engine.test.js@@ -0,0 +1,441 @@+/**+ * Saved search engines must survive the research page's real initialization,+ * refresh, dropdown selection, and submission paths without a silent swap.+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import '@js/config/urls.js';+import '@js/utils/alert-helpers.js';+import '@js/security/xss-protection.js';+import '@js/utils/form-validation.js';+import '@js/components/custom_dropdown.js';+import '@js/services/api.js';++const SOURCE = readFileSync(resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js/components/research.js',+), 'utf8');+const ENGINES_URL = '/settings/api/available-search-engines';+const START_URL = '/api/start_research';+const protectedChatRequest = window.api.fetchWithCsrfRecovery;+const HINT = 'Wayback (saved; choose a configured search provider for topics)';+const ENGINES = [+ { value: 'brave', label: 'Brave' },+ { value: 'library', label: 'Search All Collections' },+ { value: 'searxng', label: 'SearXNG' },+];++let fetchMock;+let engines;+const documentListeners = [];++function response(body) {+ return Promise.resolve({ ok: true, status: 200, json: async () => body });+}++async function settle() {+ // Drain the full bootstrap/settings/save/refresh promise chains.+ await new Promise(done => setTimeout(done, 0));+}++function deferred() {+ let finish;+ const promise = new Promise(done => { finish = done; });+ return { promise, resolve: finish };+}++function settingsResponse(saved) {+ return response({ settings: {+ 'search.tool': { value: saved, editable: true },+ 'llm.model': { value: 'test-model', editable: true },+ } });+}++function modelsResponse() {+ return response({+ provider_options: [{ value: 'OLLAMA', label: 'Ollama', is_cloud: false }],+ providers: { ollama_models: [{ value: 'test-model', label: 'Test model' }] },+ });+}++async function mount({ initial = 'wayback', saved = initial, options = ENGINES, settingsRequest = null, modelsRequest = null, enginesRequest = null } = {}) {+ engines = options;+ document.body.innerHTML = `+ <form id="research-form">+ <div id="research-alert" role="alert" style="display:none"></div>+ <textarea id="query">A research topic</textarea>+ <label class="ldr-mode-option" data-mode="quick">+ <input name="research_mode" type="radio" value="quick" checked>+ </label>+ <label class="ldr-mode-option" data-mode="chat">+ <input name="research_mode" type="radio" value="chat">+ </label>+ <button type="button" class="ldr-advanced-options-toggle">+ <i></i><span class="sr-only"></span>+ </button>+ <div class="ldr-advanced-options-panel">+ <select id="model_provider"><option value="OLLAMA">Ollama</option></select>+ <div class="ldr-form-group">+ <input id="model" data-initial-value="test-model">+ <input id="model_hidden" name="llm.model" value="test-model">+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>+ </div>+ <div class="ldr-form-group">+ <div class="form-group">+ <div class="ldr-custom-dropdown-with-refresh">+ <div class="ldr-custom-dropdown" id="search-engine-dropdown">+ <input id="search_engine" aria-describedby="engine-help" role="combobox">+ <input id="search_engine_hidden" name="search_engine" type="hidden">+ <div id="search-engine-dropdown-list" role="listbox"></div>+ </div>+ <button type="button" id="search_engine-refresh"><i></i></button>+ </div>+ <span id="engine-help">Choose a search engine</span>+ </div>+ </div>+ </div>+ <button id="start-research-btn" type="submit"><span></span></button>+ </form>+ `;+ const input = document.getElementById('search_engine');+ input.setAttribute('data-initial-value', initial);+ const hidden = document.getElementById('search_engine_hidden');+ hidden.value = initial;+ const hiddenWrites = [];+ const valueProperty = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');+ Object.defineProperty(hidden, 'value', {+ get() { return valueProperty.get.call(this); },+ set(value) {+ hiddenWrites.push(value);+ valueProperty.set.call(this, value);+ },+ });+ localStorage.setItem('advancedMenuOpen', 'false');+ window.api = {+ getCsrfToken: () => 'test-csrf',+ fetchWithCsrfRecovery: protectedChatRequest,+ };++ fetchMock = vi.fn((url, init = {}) => {+ if (String(url).startsWith(ENGINES_URL)) {+ return enginesRequest || response({ engine_options: engines });+ }+ if (String(url).startsWith('/settings/api/available-models')) {+ return modelsRequest || modelsResponse();+ }+ if (url === '/settings/api' && (!init.method || init.method === 'GET')) {+ return settingsRequest || settingsResponse(saved);+ }+ // A completed failure keeps the test on this page, without navigation.+ if (url === START_URL || url === '/api/chat/sessions') {+ return response({ success: false, message: 'Test response' });+ }+ return response({ status: 'ok' });+ });+ vi.stubGlobal('fetch', fetchMock);++ // Run the entire shipped IIFE in a fresh closure for every case. Capture+ // only its DOMContentLoaded registration so old bootstraps cannot rerun.+ let initialize;+ const addEventListener = document.addEventListener.bind(document);+ vi.spyOn(document, 'addEventListener').mockImplementation((type, listener, config) => {+ if (type === 'DOMContentLoaded') {+ initialize = listener;+ } else {+ documentListeners.push([type, listener, config]);+ addEventListener(type, listener, config);+ }+ });+ new Function(SOURCE)(); // eslint-disable-line no-new-func+ initialize();+ await settle();+ if (!modelsRequest && !enginesRequest) {+ expect(fetchMock.mock.calls.some(([url]) => url === '/settings/api')).toBe(true);+ expect(document.getElementById('model_hidden').value).toBe('test-model');+ }+ return { hiddenWrites };+}++function submit() {+ document.getElementById('research-form').dispatchEvent(+ new Event('submit', { bubbles: true, cancelable: true }),+ );+}++function startCalls() {+ return fetchMock.mock.calls.filter(([url]) => url === START_URL);+}++function hiddenValue() {+ return document.getElementById('search_engine_hidden').value;+}++function warning() {+ return document.getElementById('saved-search-engine-warning');+}++async function refresh() {+ document.getElementById('search_engine-refresh').click();+ await settle();+}++function selectEngine(value) {+ document.getElementById('search_engine').click();+ const option = document.querySelector(`#search-engine-dropdown-list [data-value="${value}"]`);+ expect(option).not.toBeNull();+ option.click();+}++beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+});++afterEach(async () => {+ await settle();+ for (const args of documentListeners.splice(0)) document.removeEventListener(...args);+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ document.body.replaceChildren();+ delete window.api;+});++it('keeps saved Wayback visible with a persistent actionable notice through initialization and refresh', async () => {+ const { hiddenWrites } = await mount();+ expect(document.getElementById('search_engine').value).toBe(HINT);+ expect(hiddenValue()).toBe('wayback');+ expect(warning()?.textContent).toMatch(/choose a configured search provider/i);+ expect(warning()?.style.display).toBe('block');+ expect(document.querySelector('.ldr-advanced-options-panel').classList.contains('ldr-expanded')).toBe(true);+ expect(document.getElementById('search_engine').getAttribute('aria-describedby')).toContain('engine-help');+ expect(document.getElementById('search_engine').getAttribute('aria-describedby')).toContain(warning().id);+ expect(hiddenWrites.length).toBeGreaterThan(0);+ expect(new Set(hiddenWrites)).toEqual(new Set(['wayback']));+ expect(fetchMock.mock.calls.filter(([url, init]) => url === '/settings/api/search.tool' && init?.method === 'PUT')).toEqual([]);++ await refresh();+ expect(hiddenValue()).toBe('wayback');+ expect(document.getElementById('search_engine').value).toBe(HINT);+ expect(warning().style.display).toBe('block');+ expect(document.querySelectorAll('#saved-search-engine-warning')).toHaveLength(1);+ expect(new Set(hiddenWrites)).toEqual(new Set(['wayback']));+});++it('uses an unavailable saved value from the settings API even when template values were configured', async () => {+ await mount({ initial: 'searxng', saved: 'wayback' });+ expect(hiddenValue()).toBe('wayback');+ expect(document.getElementById('search_engine').value).toBe(HINT);+ expect(warning()?.style.display).toBe('block');+});++it('preserves an explicit configured selection when a pending initial settings GET returns saved Wayback', async () => {+ const settings = deferred();+ await mount({ settingsRequest: settings.promise });+ selectEngine('brave');+ expect(hiddenValue()).toBe('brave');+ expect(warning().style.display).toBe('none');++ settings.resolve(settingsResponse('wayback'));+ await settle();+ expect(hiddenValue()).toBe('brave');+ expect(document.getElementById('search_engine').value).toBe('Brave');+ expect(warning().style.display).toBe('none');+ await refresh();+ expect(hiddenValue()).toBe('brave');+ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+ expect(JSON.parse(startCalls()[0][1].body).search_engine).toBe('brave');+});++it('uses configured API settings over stale template Wayback when the user has not selected an engine', async () => {+ const settings = deferred();+ await mount({ settingsRequest: settings.promise });+ expect(hiddenValue()).toBe('wayback');+ expect(warning().style.display).toBe('block');++ settings.resolve(settingsResponse('brave'));+ await settle();+ expect(hiddenValue()).toBe('brave');+ expect(document.getElementById('search_engine').value).toBe('Brave');+ expect(warning().style.display).toBe('none');+ expect(fetchMock.mock.calls.filter(([url, init]) => url === '/settings/api/search.tool' && init?.method === 'PUT')).toEqual([]);+});++it.each(['wayback', ''])('preserves a configured selection made before model/template hydration with saved API value %j', async saved => {+ const models = deferred();+ await mount({ saved, modelsRequest: models.promise });+ expect(fetchMock.mock.calls.some(([url]) => url === '/settings/api')).toBe(false);+ expect(hiddenValue()).toBe('wayback');+ selectEngine('brave');+ expect(hiddenValue()).toBe('brave');++ models.resolve(modelsResponse());+ await settle();+ expect(fetchMock.mock.calls.some(([url]) => url === '/settings/api')).toBe(true);+ expect(hiddenValue()).toBe('brave');+ expect(document.getElementById('search_engine').value).toBe('Brave');+ expect(warning().style.display).toBe('none');+ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+ expect(JSON.parse(startCalls()[0][1].body).search_engine).toBe('brave');+});++it.each(['wayback', 'brave', ''])('blocks research until the initial engine catalog is reconciled for saved value %j', async initial => {+ const catalog = deferred();+ await mount({ initial, enginesRequest: catalog.promise });+ submit();+ await settle();+ expect(startCalls()).toEqual([]);+ expect(document.getElementById('research-alert').textContent).toMatch(/search providers are still loading/i);+ expect(document.getElementById('start-research-btn').disabled).toBe(false);++ catalog.resolve(response({ engine_options: ENGINES }));+ await settle();+ expect(document.getElementById('research-alert').textContent.trim()).toBe('');+ if (initial === 'wayback') {+ expect(hiddenValue()).toBe('wayback');+ submit();+ expect(startCalls()).toEqual([]);+ selectEngine('brave');+ } else {+ expect(hiddenValue()).toBe(initial || 'searxng');+ }+ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+ expect(JSON.parse(startCalls()[0][1].body).search_engine).toBe(initial === 'wayback' ? 'brave' : initial || 'searxng');+});++it('clears the loading message after a failed catalog load while retaining the saved-unavailable submit guard', async () => {+ const catalog = deferred();+ await mount({ enginesRequest: catalog.promise });+ submit();+ expect(startCalls()).toEqual([]);+ catalog.resolve({ ok: false, status: 503 });+ await settle();+ expect(document.getElementById('research-alert').textContent.trim()).toBe('');+ expect(hiddenValue()).toBe('wayback');+ expect(warning()?.style.display).toBe('block');+ submit();+ expect(startCalls()).toEqual([]);+});++it('allows chat while the initial engine catalog is still loading', async () => {+ const catalog = deferred();+ await mount({ enginesRequest: catalog.promise });+ document.querySelector('input[value="chat"]').checked = true;+ submit();+ await settle();+ expect(fetchMock.mock.calls.filter(([url]) => url === '/api/chat/sessions')).toHaveLength(1);+ expect(startCalls()).toEqual([]);+ catalog.resolve(response({ engine_options: ENGINES }));+ await settle();+});++it('blocks research until a configured engine is explicitly selected, then clears the warning and submits that engine', async () => {+ await mount();+ submit();+ await settle();+ expect(startCalls()).toEqual([]);+ expect(document.getElementById('search_engine')).toBe(document.activeElement);+ expect(document.getElementById('start-research-btn').disabled).toBe(false);+ expect(warning()?.textContent).toMatch(/choose a configured search provider/i);++ // Typing is a filter, not a configured selection.+ document.getElementById('search_engine').value = 'SearXNG';+ document.getElementById('search_engine').dispatchEvent(new Event('input'));+ submit();+ expect(startCalls()).toEqual([]);+ expect(hiddenValue()).toBe('wayback');++ selectEngine('searxng');+ expect(warning().style.display).toBe('none');+ expect(document.getElementById('research-alert').textContent.trim()).toBe('');+ await settle();+ await refresh();+ expect(hiddenValue()).toBe('searxng');+ expect(warning().style.display).toBe('none');+ expect(document.getElementById('search_engine').getAttribute('aria-describedby')).not.toContain(warning().id);++ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+ expect(JSON.parse(startCalls()[0][1].body).search_engine).toBe('searxng');+});++it('clears the notice when a refresh makes the saved engine configured', async () => {+ await mount({ initial: 'temporarily-missing' });+ expect(hiddenValue()).toBe('temporarily-missing');+ expect(warning()?.style.display).toBe('block');+ engines = [...ENGINES, { value: 'temporarily-missing', label: 'Configured engine' }];+ await refresh();+ expect(hiddenValue()).toBe('temporarily-missing');+ expect(document.getElementById('search_engine').value).toBe('Configured engine');+ expect(warning().style.display).toBe('none');+ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+});++it('keeps a configured saved choice instead of the preferred default', async () => {+ await mount({ initial: 'brave' });+ expect(hiddenValue()).toBe('brave');+ expect(document.getElementById('search_engine').value).toBe('Brave');+ expect(warning()).toBeNull();+ submit();+ await settle();+ expect(startCalls()).toHaveLength(1);+ expect(JSON.parse(startCalls()[0][1].body).search_engine).toBe('brave');+});++it('still chooses the normal preferred default when no choice was saved', async () => {+ await mount({ initial: '', saved: '' });+ expect(hiddenValue()).toBe('searxng');+ expect(document.getElementById('search_engine').value).toBe('SearXNG');+ expect(warning()).toBeNull();+});++it('retains existing fallback behavior for an engine listed but disabled by egress policy', async () => {+ await mount({+ initial: 'brave',+ options: ENGINES.map(engine => (engine.value === 'brave'+ ? { ...engine, egress: { allowed: false, reason: 'scope_mismatch_private_only' } }+ : engine)),+ });+ expect(hiddenValue()).toBe('searxng');+ expect(warning()).toBeNull();+});++it('does not dismiss the saved-engine notice when a disabled option is clicked', async () => {+ await mount({ options: ENGINES.map(engine => ({+ ...engine,+ egress: { allowed: false, reason: 'scope_mismatch_private_only' },+ })) });+ selectEngine('searxng');+ expect(hiddenValue()).toBe('wayback');+ expect(warning()?.style.display).toBe('block');+ submit();+ expect(startCalls()).toEqual([]);+});++it('retains the existing clear-selection behavior when the saved configured engine and all alternatives are disabled', async () => {+ await mount({ initial: 'brave', options: ENGINES.map(engine => ({+ ...engine,+ egress: { allowed: false, reason: 'scope_mismatch_private_only' },+ })) });+ expect(hiddenValue()).toBe('');+ expect(document.getElementById('search_engine').value).toBe('');+ expect(warning()).toBeNull();+});++it('does not block chat, which does not submit a search engine', async () => {+ await mount();+ document.querySelector('input[value="chat"]').checked = true;+ submit();+ await settle();+ expect(fetchMock.mock.calls.filter(([url]) => url === '/api/chat/sessions')).toHaveLength(1);+ expect(startCalls()).toEqual([]);+});