~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: dropdown on settings fix wip
hashedviking466a446a4767
diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.cssindex bca3c17218..26cee33e17 100644--- a/src/local_deep_research/web/static/css/custom_dropdown.css+++ b/src/local_deep_research/web/static/css/custom_dropdown.css@@ -6,6 +6,7 @@.custom-dropdown {position: relative;width: 100%;+ z-index: 5; /* Base z-index for the dropdown container */}.custom-dropdown-input {@@ -17,6 +18,8 @@color: var(--text-primary, #f5f5f5);font-size: 0.9rem;cursor: pointer;+ position: relative;+ z-index: 6; /* Higher than container for stacking context */}.custom-dropdown-input:focus {@@ -30,15 +33,59 @@width: 100%;max-height: 250px;overflow-y: auto;- z-index: 100;+ z-index: 9999; /* High z-index for default state */background-color: var(--bg-tertiary, #2a2a3a);border: 1px solid var(--border-color, #343452);border-radius: 6px;margin-top: 5px;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);display: none;}+/* Styles for when the dropdown is fixed */+.custom-dropdown-list.dropdown-fixed {+ position: fixed !important;+ z-index: 99999 !important; /* Extremely high z-index */+ margin-top: 0 !important; /* Reset margin as top/left are calculated */+ max-height: 40vh !important; /* Cap at 40% of viewport height */+ overflow-y: auto !important;+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.5) !important; /* Stronger shadow */+ visibility: visible !important;+ opacity: 1 !important;+ clip: auto !important;+ clip-path: none !important;+ transform: none !important;+ pointer-events: auto !important;++ /* Ensure contrast with background */+ background-color: var(--bg-tertiary, #2a2a3a) !important;+ color: var(--text-primary, #f5f5f5) !important;+ border: 2px solid var(--accent-primary, #6e4ff6) !important; /* More visible border */++ /* Width, top, left are set by JS */+}++/* Explicitly override any ancestor overflow properties - more targeted to avoid side effects */+body * {+ overflow: visible !important;+}++/* Immediately revert the blanket override for essential elements */+html, body {+ overflow: auto !important;+}+.custom-dropdown-list,+.custom-dropdown-list.dropdown-fixed {+ overflow-y: auto !important;+}++/* Add a special class to the body when a dropdown is active */+body.dropdown-active {+ /* Apply a higher z-index to ensure body doesn't create a stacking context that traps our dropdown */+ z-index: auto !important;+ position: relative !important;+}+.custom-dropdown-item {padding: 10px 15px;cursor: pointer;@@ -74,6 +121,7 @@/* Custom dropdown with refresh button */.custom-dropdown-with-refresh {display: flex;+ align-items: center; /* Center items vertically */gap: 8px;width: 100%;}@@ -94,6 +142,7 @@color: var(--text-secondary, #c0c0cc);cursor: pointer;transition: all 0.2s;+ flex-shrink: 0; /* Prevent button from shrinking */}.custom-dropdown-refresh-btn:hover {@@ -106,8 +155,25 @@pointer-events: none;}+/* Remove the inner dropdown loader - we'll use JS to only show it in the button */+.dropdown-loading-indicator {+ display: none;+}++/* Only show loader inside button when needed */.custom-dropdown-refresh-btn.loading i {- animation: spin 1s linear infinite;+ display: none;+}++.custom-dropdown-refresh-btn.loading:before {+ content: "";+ width: 16px;+ height: 16px;+ border: 2px solid rgba(255, 255, 255, 0.1);+ border-radius: 50%;+ border-top-color: var(--accent-primary, #6e4ff6);+ animation: spin 0.8s linear infinite;+ display: block;}@keyframes spin {@@ -116,28 +182,97 @@}/* Advanced Options Panel Styles */+.advanced-options-toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 1.5rem;+ padding: 0.8rem 1rem;+ background-color: var(--bg-tertiary, rgba(40, 45, 60, 0.7));+ border-radius: 6px;+ cursor: pointer;+ transition: background-color 0.2s;+ border: 1px solid var(--border-color, rgba(255, 255, 255, 0.1));+}++.advanced-options-toggle:hover {+ background-color: rgba(50, 55, 70, 0.8);+}++.advanced-options-toggle.open {+ margin-bottom: 0.5rem;+}++.toggle-text {+ font-weight: 600;+ color: var(--text-primary, #e1e2e4);+}+.advanced-options-panel {+ position: relative;+ z-index: 1; /* Lower than dropdowns */+ transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out, margin 0.3s ease-in-out;max-height: 0;- overflow: hidden;- transition: max-height 0.3s ease-out, opacity 0.3s ease;+ overflow: hidden; /* Keep hidden when collapsed */opacity: 0;+ margin-top: 0;+ margin-bottom: 0;+ display: block !important; /* Always display but use max-height/opacity for animation */}.advanced-options-panel.expanded {- max-height: 500px; /* Set a large enough value to accommodate content */+ max-height: 1000px; /* Large enough to fit all content */opacity: 1;+ margin-bottom: 1.5rem;+ margin-top: 0.5rem;+ overflow: visible; /* Allow dropdowns to overflow when expanded */}-/* Only add these styles if they don't conflict with styles.css */-.advanced-options-toggle {- cursor: pointer;+/* Make dropdowns in advanced panel appear more quickly when expanded */+.advanced-options-panel.expanded .form-group {+ animation: fadeIn 0.3s ease forwards;+}++/* Stagger animation for form groups */+.advanced-options-panel.expanded .form-row:nth-child(1) .form-group {+ animation-delay: 0.05s;+}++.advanced-options-panel.expanded .form-row:nth-child(2) .form-group {+ animation-delay: 0.1s;+}++.advanced-options-panel.expanded .form-row:nth-child(3) .form-group {+ animation-delay: 0.15s;+}++@keyframes fadeIn {+ from { opacity: 0; /* transform: translateY(-5px); REMOVED */ }+ to { opacity: 1; /* transform: translateY(0); REMOVED */ }}.advanced-options-toggle i {transition: transform 0.3s ease;}-.advanced-options-toggle.expanded i,.advanced-options-toggle.open i {transform: rotate(180deg);}++/* Loading state for dropdowns */+.custom-dropdown.loading input,+.form-group.loading input {+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%236e4ff6' d='M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8z' opacity='0.3'/%3E%3Cpath fill='%236e4ff6' d='M20 12h2A10 10 0 0 0 12 2v2a8 8 0 0 1 8 8z'%3E%3CanimateTransform attributeName='transform' dur='1s' from='0 12 12' repeatCount='indefinite' to='360 12 12' type='rotate'/%3E%3C/path%3E%3C/svg%3E");+ background-position: right 10px center;+ background-repeat: no-repeat;+ background-size: 16px 16px;+}++/* Add special handling for dropdowns in the advanced panel */+/* .advanced-options-panel .custom-dropdown {+ z-index: 100;+} */++.advanced-options-panel .custom-dropdown-list {+ z-index: 10000; /* Even higher z-index for dropdowns in the advanced panel */+}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 5330f9be0a..2ca12d0c32 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@@ -10,6 +10,85 @@// Make the setupCustomDropdown function available globallywindow.setupCustomDropdown = setupCustomDropdown;+ // Also export the updateDropdownOptions function+ window.updateDropdownOptions = updateDropdownOptions;++ // Keep a registry of inputs and their associated options functions+ const dropdownRegistry = {};++ /**+ * Update the options for an existing dropdown without destroying it+ * @param {HTMLElement} input - The input element+ * @param {Array} newOptions - New options array to use [{value: string, label: string}]+ */+ function updateDropdownOptions(input, newOptions) {+ if (!input || !input.id) {+ console.warn('Cannot update dropdown: Invalid input element');+ return;+ }++ // Check if dropdown is registered+ if (!dropdownRegistry[input.id]) {+ console.warn(`Dropdown ${input.id} not found in registry, unable to update options`);+ return;+ }++ const dropdownInfo = dropdownRegistry[input.id];++ // Update the options getter function to return new options+ dropdownInfo.getOptions = () => newOptions;++ // If dropdown is currently open, update its content+ const dropdownList = document.getElementById(`${dropdownInfo.dropdownId}-list`);+ if (dropdownList && window.getComputedStyle(dropdownList).display !== 'none') {+ console.log(`Dropdown ${input.id} is open, updating content in place`);++ // Save scroll position+ const scrollPos = dropdownList.scrollTop;++ // Update dropdown content+ const filteredData = dropdownInfo.getOptions();+ dropdownList.innerHTML = '';++ if (filteredData.length === 0) {+ dropdownList.innerHTML = `<div class="custom-dropdown-no-results">${dropdownInfo.noResultsText}</div>`;+ return;+ }++ filteredData.forEach((item, index) => {+ const div = document.createElement('div');+ div.className = 'custom-dropdown-item';+ div.innerHTML = item.label;+ div.setAttribute('data-value', item.value);+ div.addEventListener('click', () => {+ // Set display value+ input.value = item.label;+ // Update hidden input if exists+ const hiddenInput = document.getElementById(`${input.id}_hidden`);+ if (hiddenInput) {+ hiddenInput.value = item.value;+ hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));+ }+ // Call original onSelect callback+ if (dropdownInfo.onSelect) {+ dropdownInfo.onSelect(item.value, item);+ }+ // Hide dropdown+ dropdownList.style.display = 'none';+ });++ dropdownList.appendChild(div);+ });++ // Restore scroll position+ dropdownList.scrollTop = scrollPos;+ } else {+ console.log(`Dropdown ${input.id} is closed, options will update when opened`);+ }++ return true;+ }+/*** Setup a custom dropdown component* @param {HTMLElement} input - The input element@@ -56,14 +135,89 @@// Function to show the dropdownfunction showDropdown() {+ const inputRect = input.getBoundingClientRect();++ // Debug logging+ console.log('Dropdown positioning:', {+ inputLeft: inputRect.left,+ inputBottom: inputRect.bottom,+ scrollY: window.scrollY,+ inputWidth: inputRect.width,+ windowWidth: window.innerWidth,+ windowHeight: window.innerHeight+ });++ // Store original parent for when we close+ if (!dropdownList._originalParent) {+ dropdownList._originalParent = dropdownList.parentNode;+ }++ // Remove from current parent+ if (dropdownList.parentNode) {+ dropdownList.parentNode.removeChild(dropdownList);+ }++ // Append directly to body+ document.body.appendChild(dropdownList);++ // Make dropdown visibledropdownList.style.display = 'block';++ // Add fixed class+ dropdownList.classList.add('dropdown-fixed');++ // Add dropdown-active class to body+ document.body.classList.add('dropdown-active');++ // Add a small offset (6px) to ensure it's visibly separated from the input+ const verticalOffset = 6;++ // Calculate position relative to viewport+ const left = Math.min(inputRect.left, window.innerWidth - inputRect.width - 10);+ const top = inputRect.bottom + window.scrollY + verticalOffset;++ // Apply the calculated position+ dropdownList.style.left = `${left}px`;+ dropdownList.style.top = `${top}px`;+ dropdownList.style.width = `${inputRect.width}px`;++ // Force DOM reflow to ensure styles are applied+ dropdownList.getBoundingClientRect();++ // Additional styling to ensure visibility+ dropdownList.style.visibility = 'visible';+ dropdownList.style.opacity = '1';++ // Ensure dropdown is visible by bringing it to front+ dropdownList.style.zIndex = '999999';+input.setAttribute('aria-expanded', 'true');isOpen = true;}// Function to hide the dropdownfunction hideDropdown() {+ // Get current parent+ const currentParent = dropdownList.parentNode;++ // Hide firstdropdownList.style.display = 'none';+ dropdownList.classList.remove('dropdown-fixed'); // Remove fixed class++ // Remove dropdown-active class from body+ document.body.classList.remove('dropdown-active');++ // Reset position styles+ dropdownList.style.left = '';+ dropdownList.style.top = '';+ dropdownList.style.width = '';++ // Move back to original parent if it exists and we're not already there+ if (dropdownList._originalParent && currentParent !== dropdownList._originalParent) {+ currentParent.removeChild(dropdownList);+ dropdownList._originalParent.appendChild(dropdownList);+ }+input.setAttribute('aria-expanded', 'false');selectedIndex = -1;isOpen = false;@@ -123,12 +277,10 @@// Click event - show all options when clicking in the inputinput.addEventListener('click', (e) => {- if (!isOpen) {- showAllOptions = true; // Show all options on click- showDropdown();- updateDropdown();- }- e.stopPropagation(); // Prevent immediate closing by document click handler+ e.stopPropagation();+ showAllOptions = true;+ showDropdown();+ updateDropdown();});// Focus event - show dropdown when input is focused@@ -219,34 +371,54 @@e.stopPropagation();});+ // Register this dropdown for future updates+ if (input && input.id && dropdownList && dropdownList.id) {+ const dropdownId = dropdownList.id.replace('-list', '');+ console.log(`Registering dropdown: ${input.id} with list ${dropdownId}`);++ dropdownRegistry[input.id] = {+ getOptions: getOptions,+ onSelect: onSelect,+ dropdownId: dropdownId,+ allowCustomValues: allowCustomValues,+ noResultsText: noResultsText+ };+ } else {+ console.warn('Cannot register dropdown: Missing input ID or dropdown list ID');+ }+// Initial statehideDropdown();// Return functions that might be needed externallyreturn {- updateOptions: updateDropdown,- show: () => {- showAllOptions = true;- showDropdown();- updateDropdown();- },- hide: hideDropdown,- setValue: (value, fireEvent = true) => {+ updateDropdown,+ showDropdown,+ hideDropdown,+ setValue: (value, triggerChange = true) => {const options = getOptions();- const item = options.find(o => o.value === value);- if (item) {- input.value = item.label;- // Update hidden input- updateHiddenField(value);- if (fireEvent) {- onSelect(value, item);- }- } else if (allowCustomValues) {+ const matchedOption = options.find(opt => opt.value === value);++ if (matchedOption) {+ input.value = matchedOption.label;+ } else if (allowCustomValues && value) {input.value = value;- // Update hidden input with custom value+ } else {+ input.value = '';+ }++ if (triggerChange) {updateHiddenField(value);- if (fireEvent) {- onSelect(value, null);+ // Also call onSelect if triggerChange is true+ if (matchedOption) {+ onSelect(value, matchedOption);+ } else {+ onSelect(value, { value, label: value });+ }+ } else {+ // Even if we don't trigger events, we should update the hidden field+ if (hiddenInput) {+ hiddenInput.value = value;}}}diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 472300ec91..eac0722bfd 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -47,6 +47,9 @@let selectedSearchEngineValue = '';let searchEngineSelectedIndex = -1;+ // Track initialization to prevent unwanted saves during initial setup+ let isInitializing = true;+// Model provider options from READMEconst MODEL_PROVIDERS = [{ value: 'OLLAMA', label: 'Ollama (Local)' },@@ -82,6 +85,9 @@* Initialize the research component*/function initializeResearch() {+ // Set initializing flag+ isInitializing = true;+// Get DOM elementsform = document.getElementById('research-form');queryInput = document.getElementById('query');@@ -109,30 +115,116 @@advancedToggle = document.querySelector('.advanced-options-toggle');advancedPanel = document.querySelector('.advanced-options-panel');- // Load model data first+ // First, try to load settings from localStorage for immediate display+ const lastProvider = localStorage.getItem('lastUsedProvider');+ const lastModel = localStorage.getItem('lastUsedModel');+ const lastSearchEngine = localStorage.getItem('lastUsedSearchEngine');++ console.log('Local storage values:', { provider: lastProvider, model: lastModel, searchEngine: lastSearchEngine });++ // Apply local storage values if available+ if (lastProvider && modelProviderSelect) {+ console.log('Setting provider from localStorage:', lastProvider);+ modelProviderSelect.value = lastProvider;+ // Show/hide endpoint container as needed+ if (endpointContainer) {+ endpointContainer.style.display = lastProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';+ }+ }++ // Initialize the UI first (immediate operations)+ setupEventListeners();+ populateModelProviders();+ initializeDropdowns();++ // Set initial state of the advanced options panel based on localStorage+ const savedState = localStorage.getItem('advancedOptionsOpen') === 'true';+ if (savedState && advancedPanel) {+ advancedPanel.style.display = 'block';+ advancedPanel.classList.add('expanded');+ if (advancedToggle) {+ advancedToggle.classList.add('open');+ const icon = advancedToggle.querySelector('i');+ if (icon) icon.className = 'fas fa-chevron-up';+ }+ }++ // Then load data asynchronously (don't block UI)Promise.all([loadModelOptions(false),loadSearchEngineOptions(false)- ]).then(() => {- // After loading model data, set up event listeners- setupEventListeners();+ ]).then(([modelData, searchEngineData]) => {+ console.log('Data loaded successfully');- // Populate model provider options- populateModelProviders();+ // After loading model data, update the UI with the loaded data+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : (lastProvider || 'OLLAMA');+ updateModelOptionsForProvider(currentProvider, false);- // Initialize dropdowns- initializeDropdowns();+ // Update search engine options+ if (searchEngineData && Array.isArray(searchEngineData)) {+ searchEngineOptions = searchEngineData;+ console.log('Loaded search engines:', searchEngineData.length);++ // Force search engine dropdown to update with new data+ if (searchEngineDropdownList && window.setupCustomDropdown) {+ // Recreate the dropdown with the new data+ const searchDropdownInstance = window.setupCustomDropdown(+ searchEngineInput,+ searchEngineDropdownList,+ () => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }],+ (value, item) => {+ console.log('Search engine selected:', value, item);+ selectedSearchEngineValue = value;++ // Update the input field+ if (item) {+ searchEngineInput.value = item.label;+ } else {+ searchEngineInput.value = value;+ }++ // Only save if not initializing+ if (!isInitializing) {+ saveSearchEngineSettings(value);+ }+ },+ false,+ 'No search engines available.'+ );++ // If we have a last selected search engine, try to select it+ if (lastSearchEngine) {+ console.log('Trying to select last search engine:', lastSearchEngine);+ // Find the matching engine+ const matchingEngine = searchEngineOptions.find(engine =>+ engine.value === lastSearchEngine || engine.id === lastSearchEngine);++ if (matchingEngine) {+ console.log('Found matching search engine:', matchingEngine);+ searchEngineInput.value = matchingEngine.label;+ selectedSearchEngineValue = matchingEngine.value;++ // Update hidden input if exists+ const hiddenInput = document.getElementById('search_engine_hidden');+ if (hiddenInput) {+ hiddenInput.value = matchingEngine.value;+ }+ }+ }+ }+ }- // Load settings AFTER everything is initialized- loadSettings();+ // Finally, load settings after data is available+ loadSettings();}).catch(error => {- console.error('Failed to initialize research component:', error);+ console.error('Failed to load options:', error);- // Continue with basic initialization even if loading data fails- setupEventListeners();- populateModelProviders();- initializeDropdowns();+ // Still load settings even if data loading failsloadSettings();++ if (window.ui && window.ui.showAlert) {+ window.ui.showAlert('Some options could not be loaded. Using defaults instead.', 'warning');+ }});}@@ -153,7 +245,7 @@console.log('Initializing dropdowns with setupCustomDropdown');// Set up model dropdown- if (modelInput && modelDropdownList) {+ if (modelInput && modelDropdownList) {// Clear any existing dropdown setupmodelDropdownList.innerHTML = '';@@ -178,22 +270,27 @@const isCustomValue = !item;showCustomModelWarning(isCustomValue);- // Save selected model to settings- saveModelSettings(value);+ // Save selected model to settings - only if not initializing+ if (!isInitializing) {+ saveModelSettings(value);+ }},true, // Allow custom values'No models available. Type to enter a custom model name.');// Initialize model refresh button- if (modelRefreshBtn) {+ if (modelRefreshBtn) {modelRefreshBtn.addEventListener('click', function() {const icon = modelRefreshBtn.querySelector('i');- if (icon) icon.className = 'fas fa-spinner fa-spin';++ // Add loading class to button+ modelRefreshBtn.classList.add('loading');// Force refresh of model optionsloadModelOptions(true).then(() => {- if (icon) icon.className = 'fas fa-sync-alt';+ // Remove loading class+ modelRefreshBtn.classList.remove('loading');// Ensure the current provider's models are loadedconst currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';@@ -204,7 +301,10 @@modelInput.dispatchEvent(event);}).catch(error => {console.error('Error refreshing models:', error);- if (icon) icon.className = 'fas fa-sync-alt';++ // Remove loading class+ modelRefreshBtn.classList.remove('loading');+if (window.ui && window.ui.showAlert) {window.ui.showAlert('Failed to refresh models: ' + error.message, 'error');}@@ -218,11 +318,20 @@// Clear any existing dropdown setupsearchEngineDropdownList.innerHTML = '';+ // Add loading state to search engine input+ if (searchEngineInput.parentNode) {+ searchEngineInput.parentNode.classList.add('loading');+ }+const searchDropdownInstance = window.setupCustomDropdown(- searchEngineInput,- searchEngineDropdownList,- () => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }],- (value, item) => {+ searchEngineInput,+ searchEngineDropdownList,+ () => {+ // Log available search engines for debugging+ console.log('Getting search engine options:', searchEngineOptions);+ return searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: '', label: 'No search engines available' }];+ },+ (value, item) => {console.log('Search engine selected:', value, item);selectedSearchEngineValue = value;@@ -233,29 +342,37 @@searchEngineInput.value = value;}- // Save search engine selection to settings- saveSearchEngineSettings(value);+ // Save search engine selection to settings - only if not initializing+ if (!isInitializing) {+ saveSearchEngineSettings(value);+ }},false, // Don't allow custom values- 'No search engines available.'- );+ 'No search engines available.'+ );// Initialize search engine refresh button- if (searchEngineRefreshBtn) {- searchEngineRefreshBtn.addEventListener('click', function() {+ if (searchEngineRefreshBtn) {+ searchEngineRefreshBtn.addEventListener('click', function() {const icon = searchEngineRefreshBtn.querySelector('i');- if (icon) icon.className = 'fas fa-spinner fa-spin';++ // Add loading class to button+ searchEngineRefreshBtn.classList.add('loading');// Force refresh of search engine optionsloadSearchEngineOptions(true).then(() => {- if (icon) icon.className = 'fas fa-sync-alt';+ // Remove loading class+ searchEngineRefreshBtn.classList.remove('loading');// Force dropdown updateconst event = new Event('click', { bubbles: true });searchEngineInput.dispatchEvent(event);}).catch(error => {console.error('Error refreshing search engines:', error);- if (icon) icon.className = 'fas fa-sync-alt';++ // Remove loading class+ searchEngineRefreshBtn.classList.remove('loading');+if (window.ui && window.ui.showAlert) {window.ui.showAlert('Failed to refresh search engines: ' + error.message, 'error');}@@ -279,9 +396,7 @@if (savedState) {advancedToggle.classList.add('open', 'expanded');- advancedPanel.classList.add('expanded');- // Let CSS handle the display property based on the 'expanded' class- // advancedPanel.style.display = 'block'; // REMOVED+ advancedToggle.classList.toggle('expanded', true);// Update icon immediatelyconst icon = advancedToggle.querySelector('i');@@ -290,9 +405,7 @@}} else {advancedToggle.classList.remove('open', 'expanded');- advancedPanel.classList.remove('expanded');- // Let CSS handle the display property based on the absence of 'expanded' class- // advancedPanel.style.display = 'none'; // REMOVED+ advancedToggle.classList.toggle('expanded', false);// Ensure icon is correctconst icon = advancedToggle.querySelector('i');if (icon) {@@ -720,8 +833,10 @@hiddenInput.value = selectedModelValue;}- // Save to settings- saveModelSettings(selectedModelValue);+ // Only save to settings if we're not initializing+ if (!isInitializing) {+ saveModelSettings(selectedModelValue);+ }return;}}@@ -748,8 +863,10 @@hiddenInput.value = selectedModelValue;}- // Save to settings- saveModelSettings(selectedModelValue);+ // Only save to settings if we're not initializing+ if (!isInitializing) {+ saveModelSettings(selectedModelValue);+ }return;}}@@ -765,8 +882,10 @@hiddenInput.value = selectedModelValue;}- // Save to settings- saveModelSettings(selectedModelValue);+ // Only save to settings if we're not initializing+ if (!isInitializing) {+ saveModelSettings(selectedModelValue);+ }}}@@ -841,7 +960,7 @@return {success: false,error: "Ollama service is not running.",- solution: "Please start Ollama and try again."+ solution: "Please start Ollama and try again. If you've recently updated, you may need to run database migration with 'python -m src.local_deep_research.migrate_db'."};}@@ -923,6 +1042,7 @@// Find the provider and model settingsconst providerSetting = data.settings.find(s => s.key === 'llm.provider');const modelSetting = data.settings.find(s => s.key === 'llm.model');+ const searchEngineSetting = data.settings.find(s => s.key === 'search.tool');// Update provider dropdown if we have a valid providerif (providerSetting && providerSetting.value && modelProviderSelect) {@@ -935,7 +1055,10 @@);if (matchingOption) {+ console.log('Found matching provider option:', matchingOption.value);modelProviderSelect.value = matchingOption.value;+ // Also save to localStorage+ localStorage.setItem('lastUsedProvider', matchingOption.value);} else {// If no match, try to find case-insensitive or partial matchconst caseInsensitiveMatch = Array.from(modelProviderSelect.options).find(@@ -944,7 +1067,10 @@);if (caseInsensitiveMatch) {+ console.log('Found case-insensitive provider match:', caseInsensitiveMatch.value);modelProviderSelect.value = caseInsensitiveMatch.value;+ // Also save to localStorage+ localStorage.setItem('lastUsedProvider', caseInsensitiveMatch.value);} else {console.warn(`No matching provider option found for '${providerValue}'`);}@@ -965,79 +1091,146 @@const modelValue = modelSetting.value;console.log('Setting model to:', modelValue);+ // Save to localStorage+ localStorage.setItem('lastUsedModel', modelValue);+// Find the model in our loaded optionsconst matchingModel = modelOptions.find(m =>m.value === modelValue || m.id === modelValue);if (matchingModel) {- // Use the setValue method of our dropdown- const modelDropdownList = document.getElementById('model-dropdown-list');- if (window.setupCustomDropdown && modelInput && modelDropdownList) {- // Initialize the dropdown- const dropdown = window.setupCustomDropdown(- modelInput,- modelDropdownList,- () => modelOptions,- (value, item) => {- selectedModelValue = value;- saveModelSettings(value);- },- true- );-- // Set the model value- if (dropdown && dropdown.setValue) {- dropdown.setValue(modelValue);- } else {- // Fallback if custom dropdown is not properly initialized- modelInput.value = matchingModel.label || modelValue;- selectedModelValue = modelValue;- }- } else {- // Direct update if dropdown not available- modelInput.value = matchingModel.label || modelValue;- selectedModelValue = modelValue;+ console.log('Found matching model in options:', matchingModel);++ // Set the input field value+ modelInput.value = matchingModel.label || modelValue;+ selectedModelValue = modelValue;++ // Also update hidden input if it exists+ const hiddenInput = document.getElementById('model_hidden');+ if (hiddenInput) {+ hiddenInput.value = modelValue;}} else {// If no matching model found, just set the raw valueconsole.warn(`No matching model found for '${modelValue}'`);modelInput.value = modelValue;selectedModelValue = modelValue;++ // Also update hidden input if it exists+ const hiddenInput = document.getElementById('model_hidden');+ if (hiddenInput) {+ hiddenInput.value = modelValue;+ }}}});++ // Update search engine if we have a valid value+ if (searchEngineSetting && searchEngineSetting.value && searchEngineInput) {+ const engineValue = searchEngineSetting.value;+ console.log('Setting search engine to:', engineValue);++ // Save to localStorage+ localStorage.setItem('lastUsedSearchEngine', engineValue);++ // Find the engine in our loaded options+ const matchingEngine = searchEngineOptions.find(e =>+ e.value === engineValue || e.id === engineValue+ );++ if (matchingEngine) {+ console.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 {+ // If no matching engine found, just set the raw value+ console.warn(`No matching search engine found for '${engineValue}'`);+ searchEngineInput.value = engineValue;+ selectedSearchEngineValue = engineValue;++ // Also update hidden input if it exists+ const hiddenInput = document.getElementById('search_engine_hidden');+ if (hiddenInput) {+ hiddenInput.value = engineValue;+ }+ }+ }}++ // Now that settings are loaded, we're no longer initializing+ isInitializing = false;}).catch(error => {console.error('Error loading settings:', error);// Fallback to localStorage if database fetch fails- const provider = localStorage.getItem('lastUsedProvider');- const model = localStorage.getItem('lastUsedModel');+ fallbackToLocalStorageSettings();- if (provider && modelProviderSelect) {- modelProviderSelect.value = provider;- // Show/hide custom endpoint input if needed- if (endpointContainer) {- endpointContainer.style.display =- provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';- }+ // Even if there's an error, we're done initializing+ isInitializing = false;+ });+ }++ // Add a fallback function to use localStorage settings+ function fallbackToLocalStorageSettings() {+ const provider = localStorage.getItem('lastUsedProvider');+ const model = localStorage.getItem('lastUsedModel');+ const searchEngine = localStorage.getItem('lastUsedSearchEngine');++ console.log('Falling back to localStorage settings:', { provider, model, searchEngine });++ if (provider && modelProviderSelect) {+ modelProviderSelect.value = provider;+ // Show/hide custom endpoint input if needed+ if (endpointContainer) {+ endpointContainer.style.display =+ provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ }- const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';- updateModelOptionsForProvider(currentProvider, !model);+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';+ updateModelOptionsForProvider(currentProvider, !model);- if (model && modelInput) {- const matchingModel = modelOptions.find(m => m.value === model);- if (matchingModel) {- modelInput.value = matchingModel.label;- } else {- modelInput.value = model;- }- selectedModelValue = model;+ if (model && modelInput) {+ const matchingModel = modelOptions.find(m => m.value === model);+ if (matchingModel) {+ modelInput.value = matchingModel.label;+ } else {+ modelInput.value = model;}- });+ selectedModelValue = model;++ // Update hidden input if it exists+ const hiddenInput = document.getElementById('model_hidden');+ if (hiddenInput) {+ hiddenInput.value = model;+ }+ }++ if (searchEngine && searchEngineInput) {+ const matchingEngine = searchEngineOptions.find(e => e.value === searchEngine);+ if (matchingEngine) {+ searchEngineInput.value = matchingEngine.label;+ } else {+ searchEngineInput.value = searchEngine;+ }+ selectedSearchEngineValue = searchEngine;++ // Update hidden input if it exists+ const hiddenInput = document.getElementById('search_engine_hidden');+ if (hiddenInput) {+ hiddenInput.value = searchEngine;+ }+ }}/**@@ -1058,6 +1251,11 @@}}+ // Add loading class to parent+ if (modelInput && modelInput.parentNode) {+ modelInput.parentNode.classList.add('loading');+ }+// Fetch from API if cache is invalid or refresh is forcedfetch('/research/settings/api/available-models').then(response => {@@ -1067,6 +1265,11 @@return response.json();}).then(data => {+ // Remove loading class+ if (modelInput && modelInput.parentNode) {+ modelInput.parentNode.classList.remove('loading');+ }+if (data && data.providers) {console.log('Got model data from API:', data);@@ -1089,6 +1292,11 @@.catch(error => {console.error('Error loading models:', error);+ // Remove loading class on error+ if (modelInput && modelInput.parentNode) {+ modelInput.parentNode.classList.remove('loading');+ }+// Use cached data if available, even if expiredconst cachedData = getCachedData(CACHE_KEYS.MODELS);if (cachedData) {@@ -1198,8 +1406,140 @@// Load search engine optionsfunction loadSearchEngineOptions(forceRefresh = false) {return new Promise((resolve, reject) => {- // Implementation would be similar to loadModelOptions- resolve([]);+ // Check cache first if not forcing refresh+ if (!forceRefresh) {+ const cachedData = getCachedData(CACHE_KEYS.SEARCH_ENGINES);+ const cacheTimestamp = getCachedData(CACHE_KEYS.CACHE_TIMESTAMP);++ // Use cache if it exists and isn't expired+ if (cachedData && cacheTimestamp && (Date.now() - cacheTimestamp < CACHE_EXPIRATION)) {+ console.log('Using cached search engine data');+ searchEngineOptions = cachedData; // Ensure the global variable is updated+ resolve(cachedData);+ return;+ }+ }++ // Add loading class to parent+ if (searchEngineInput && searchEngineInput.parentNode) {+ searchEngineInput.parentNode.classList.add('loading');+ }++ console.log('Fetching search engines from API...');++ // Fetch from API+ fetch('/research/settings/api/available-search-engines')+ .then(response => {+ if (!response.ok) {+ throw new Error(`API error: ${response.status}`);+ }+ return response.json();+ })+ .then(data => {+ // Remove loading class+ if (searchEngineInput && searchEngineInput.parentNode) {+ searchEngineInput.parentNode.classList.remove('loading');+ }++ // Log the entire response to debug+ console.log('Search engine API response:', data);++ // Extract engines from the data based on the actual response format+ let formattedEngines = [];++ // Handle the case where API returns {engine_options, engines}+ if (data && data.engine_options) {+ console.log('Processing engine_options:', data.engine_options.length + ' options');++ // Map the engine options to our dropdown format+ formattedEngines = data.engine_options.map(engine => ({+ value: engine.value || engine.id || '',+ label: engine.label || engine.name || engine.value || '',+ type: engine.type || 'search'+ }));+ }+ // Also try adding engines from engines object if it exists+ if (data && data.engines) {+ console.log('Processing engines object:', Object.keys(data.engines).length + ' engine types');++ // Handle each type of engine in the engines object+ Object.keys(data.engines).forEach(engineType => {+ const enginesOfType = data.engines[engineType];+ if (Array.isArray(enginesOfType)) {+ console.log(`Processing ${engineType} engines:`, enginesOfType.length + ' engines');++ // Map each engine to our dropdown format+ const typeEngines = enginesOfType.map(engine => ({+ value: engine.value || engine.id || '',+ label: engine.label || engine.name || engine.value || '',+ type: engineType+ }));++ // Add to our formatted engines array+ formattedEngines = [...formattedEngines, ...typeEngines];+ }+ });+ }+ // Handle classic format with search_engines array+ else if (data && data.search_engines) {+ console.log('Processing search_engines array:', data.search_engines.length + ' engines');+ formattedEngines = data.search_engines.map(engine => ({+ value: engine.id || engine.value || '',+ label: engine.name || engine.label || '',+ type: engine.type || 'search'+ }));+ }+ // Handle direct array format+ else if (data && Array.isArray(data)) {+ console.log('Processing direct array:', data.length + ' engines');+ formattedEngines = data.map(engine => ({+ value: engine.id || engine.value || '',+ label: engine.name || engine.label || '',+ type: engine.type || 'search'+ }));+ }++ console.log('Final formatted search engines:', formattedEngines);++ if (formattedEngines.length > 0) {+ // Cache the data+ cacheData(CACHE_KEYS.SEARCH_ENGINES, formattedEngines);++ // Update global searchEngineOptions+ searchEngineOptions = formattedEngines;++ resolve(formattedEngines);+ } else {+ throw new Error('No valid search engines found in API response');+ }+ })+ .catch(error => {+ console.error('Error loading search engines:', error);++ // Remove loading class on error+ if (searchEngineInput && searchEngineInput.parentNode) {+ searchEngineInput.parentNode.classList.remove('loading');+ }++ // Use cached data if available, even if expired+ const cachedData = getCachedData(CACHE_KEYS.SEARCH_ENGINES);+ if (cachedData) {+ console.log('Using expired cached search engine data due to API error');+ searchEngineOptions = cachedData;+ resolve(cachedData);+ } else {+ // Use fallback data if no cache available+ console.log('Using fallback search engine data');+ const fallbackEngines = [+ { value: 'google', label: 'Google Search' },+ { value: 'duckduckgo', label: 'DuckDuckGo' },+ { value: 'bing', label: 'Bing Search' }+ ];+ searchEngineOptions = fallbackEngines;+ cacheData(CACHE_KEYS.SEARCH_ENGINES, fallbackEngines);+ resolve(fallbackEngines);+ }+ });});}diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 8439c3bdcc..7021ea27f1 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -84,23 +84,82 @@}/**- * Set up refresh button handlers+ * Set up refresh buttons for model and search engine dropdowns*/function setupRefreshButtons() {- // Look for any refresh buttons for model dropdowns- const modelRefreshBtn = document.getElementById('llm-model-refresh');+ console.log('Setting up refresh buttons...');++ // Handle model refresh button+ const modelRefreshBtn = document.getElementById('llm.model-refresh');if (modelRefreshBtn) {+ console.log('Found and set up model refresh button:', modelRefreshBtn.id);modelRefreshBtn.addEventListener('click', function() {- fetchModelProviders(true);+ const icon = modelRefreshBtn.querySelector('i');+ if (icon) icon.className = 'fas fa-spinner fa-spin';+ modelRefreshBtn.classList.add('loading');++ // Reset the initialization flag to allow reinitializing the dropdown+ window.modelDropdownsInitialized = false;++ // Force refresh models and reinitialize+ fetchModelProviders(true)+ .then(() => {+ if (icon) icon.className = 'fas fa-sync-alt';+ modelRefreshBtn.classList.remove('loading');++ // Re-initialize model dropdowns with the new data+ initializeModelDropdowns();++ // Show success message+ showAlert('Model list refreshed', 'success');+ })+ .catch(error => {+ console.error('Error refreshing models:', error);+ if (icon) icon.className = 'fas fa-sync-alt';+ modelRefreshBtn.classList.remove('loading');+ showAlert('Failed to refresh models', 'error');+ });});+ } else {+ console.log('Could not find model refresh button');}- // Look for any refresh buttons for search engine dropdowns- const searchEngineRefreshBtn = document.getElementById('search-tool-refresh');+ // Handle search engine refresh button+ const searchEngineRefreshBtn = document.getElementById('search.tool-refresh');if (searchEngineRefreshBtn) {+ console.log('Found and set up search engine refresh button:', searchEngineRefreshBtn.id);searchEngineRefreshBtn.addEventListener('click', function() {- fetchSearchEngines(true);+ const icon = searchEngineRefreshBtn.querySelector('i');+ if (icon) icon.className = 'fas fa-spinner fa-spin';+ searchEngineRefreshBtn.classList.add('loading');++ // Reset the initialization flag to allow reinitializing the dropdown+ window.searchEngineDropdownInitialized = false;++ // Force refresh search engines and reinitialize+ fetchSearchEngines(true)+ .then(() => {+ if (icon) icon.className = 'fas fa-sync-alt';+ searchEngineRefreshBtn.classList.remove('loading');++ // Re-initialize search engine dropdowns with the new data+ initializeSearchEngineDropdowns();++ // Show success message+ showAlert('Search engine list refreshed', 'success');+ })+ .catch(error => {+ console.error('Error refreshing search engines:', error);+ if (icon) icon.className = 'fas fa-sync-alt';+ searchEngineRefreshBtn.classList.remove('loading');+ showAlert('Failed to refresh search engines', 'error');+ });});+ } else {+ console.log('Could not find search engine refresh button');++ // Try to create refresh button if it doesn't exist for search engine+ createRefreshButton('search.tool', fetchSearchEngines);}}@@ -295,153 +354,100 @@* @param {string} [customEventType] - Optional event type parameter*/function handleInputChange(e, customEventType) {- console.log('[handleInputChange] Triggered for:', e.target.id, 'Event type:', customEventType || e.type); // LOG 1+ // --- MODIFICATION START: Simplified handleInputChange ---const input = e.target;const eventType = customEventType || e.type;+ const key = input.dataset.key || input.name; // Get key using data-key first- // Skip if disabled or not data-key attribute- if (input.disabled || !input.getAttribute('data-key')) {- return;- }-- // Get the key and value- const key = input.getAttribute('data-key') || input.getAttribute('name');+ if (!key || input.disabled) return;- // Skip if no key found- if (!key) { return; }-- // Get value based on input typelet value;+ let shouldSaveImmediately = false;- // Handle checkbox first as it needs immediate save- if (input.type === 'checkbox') {+ // Handle hidden inputs for custom dropdowns+ if (input.type === 'hidden' && input.id.endsWith('_hidden')) {+ value = input.value;+ shouldSaveImmediately = true; // Save immediately on hidden input change+ console.log(`[Hidden Input Change] Key: ${key}, Value: ${value}`);+ }+ // Handle checkboxes+ else if (input.type === 'checkbox') {value = input.checked;- // For checkboxes, we need to save immediately on change- const formData = {};- formData[key] = value;- submitSettingsData(formData, input);- return;- } else if (input.type === 'number') {- value = parseFloat(input.value);- // Validate number against min/max if set- const min = input.getAttribute('min');- const max = input.getAttribute('max');-- if (min !== null && value < parseFloat(min)) {- markInvalidInput(input, `Value must be at least ${min}`);- return;+ shouldSaveImmediately = true; // Checkboxes save immediately+ }+ // Handle standard selects+ else if (input.tagName.toLowerCase() === 'select') {+ value = input.value;+ // Save on change or blur if changed+ if (eventType === 'change' || eventType === 'blur') {+ shouldSaveImmediately = true;}- if (max !== null && value > parseFloat(max)) {- markInvalidInput(input, `Value must be at most ${max}`);- return;+ }+ // Handle range/slider (save on change/input or blur)+ else if (input.type === 'range') {+ value = input.value;+ if (eventType === 'change' || eventType === 'input' || eventType === 'blur') {+ shouldSaveImmediately = true;}- } else {+ }+ // Handle other inputs (text, number, textarea) - Save on Enter or Blur+ else {value = input.value;-- // If this is a raw JSON editor, validate the JSON- if (input.classList.contains('json-editor')) {- try {- value = JSON.parse(input.value);- } catch (e) {- markInvalidInput(input, `Invalid JSON: ${e.message}`);+ // Basic validation for number+ if (input.type === 'number') {+ try {+ const numValue = parseFloat(value);+ const min = input.min ? parseFloat(input.min) : null;+ const max = input.max ? parseFloat(input.max) : null;+ if ((min !== null && numValue < min) || (max !== null && numValue > max)) {+ markInvalidInput(input, `Value must be between ${min ?? '-∞'} and ${max ?? '∞'}`);+ return; // Don't save invalid number+ }+ value = numValue; // Use parsed number+ } catch {+ markInvalidInput(input, 'Invalid number');return;- }+ }}-- // If this is part of an expanded JSON control, don't handle it here- if (input.classList.contains('json-property-control')) {- // This will be handled by updateJsonFromControls- return;+ // Save on Enter or Blur+ if ((eventType === 'keydown' && e.key === 'Enter' && !e.shiftKey) || eventType === 'blur') {+ shouldSaveImmediately = true;+ if (eventType === 'keydown') e.preventDefault(); // Prevent form submission on enter}}- // Clear any previous error styling- input.classList.remove('invalid-input');- const errorMessage = input.parentNode.querySelector('.input-error-message');- if (errorMessage) {- errorMessage.remove();- }-- // Get the original value to compare- const settingObj = allSettings.find(s => s.key === key);- // *** FIX: Read from originalSettings cache, not allSettings ***- const originalValue = originalSettings.hasOwnProperty(key) ? originalSettings[key] : null;+ // Clear previous errors+ markInvalidInput(input, null);- // Check if value actually changed before saving+ // Compare with original value+ const originalValue = originalSettings.hasOwnProperty(key) ? originalSettings[key] : undefined;const hasChanged = !areValuesEqual(value, originalValue);- // Don't mark as modified or save if nothing changed- if (!hasChanged) {- // If this is a blur event and we have no changes, just return- if (eventType === 'blur') {- return;- }- } else {- // Only mark as modified if there's an actual change- const item = input.closest('.settings-item');- if (item) {- item.classList.add('settings-modified');- }- }-- // *** FIX: Explicitly trigger save for 'change' event if changed ***- if (hasChanged && eventType === 'change') {- console.log(`Change detected for ${key}, submitting data.`);- // Schedule the save instead of calling directly, allow function to continue- const formData = {};- formData[key] = value;- scheduleSave(formData, input); // Use scheduleSave for consistency- // Do not return here, let logic continue (e.g., for potential blur event later)- }+ console.log(`[Input Change] Key: ${key}, Value: ${value}, Event: ${eventType}, Changed: ${hasChanged}, Save Immediately: ${shouldSaveImmediately}`);- // Handle Enter key press - submit just this field immediately- if (eventType === 'keydown' && e.key === 'Enter' && !e.shiftKey) {- // Prevent default behavior (form submission)- e.preventDefault();-- // Only if this is not a textarea or it is with Enter key and not Shift+Enter- if (input.tagName.toLowerCase() !== 'textarea' || (e.key === 'Enter' && !e.shiftKey)) {- // Only save if there's an actual change- if (hasChanged) {- // Create formData with just this field- const formData = {};- formData[key] = value;-- // Mark this input as being processed by Enter key to prevent double save- input.setAttribute('data-enter-pressed', 'true');+ if (hasChanged) {+ // Mark parent item as modified+ const item = input.closest('.settings-item');+ if (item) item.classList.add('settings-modified');- // Submit immediately- submitSettingsData(formData, input);- }+ // Save if needed+ if (shouldSaveImmediately) {+ const formData = { [key]: value };+ submitSettingsData(formData, input); // Direct submit might be better than debouncing here- // Blur the input without triggering another save- setTimeout(() => {- // Remove the focus without triggering blur events+ // If saved on Enter, blur the input+ if (eventType === 'keydown' && e.key === 'Enter') {input.blur();- }, 10);- return;- }- }-- // For blur events, save immediately if value changed- if (eventType === 'blur') {- // Check if this was triggered right after an Enter key press- if (input.getAttribute('data-enter-pressed') === 'true') {- // Reset the flag and don't save again- input.removeAttribute('data-enter-pressed');- return;+ }}-- if (hasChanged) {- const formData = {};- formData[key] = value;- submitSettingsData(formData, input);+ } else {+ // If blur event and no changes, remove modified indicator maybe?+ if (eventType === 'blur') {+ const item = input.closest('.settings-item');+ if (item) item.classList.remove('settings-modified');}- return;}-- // For 'input' events, we don't schedule a save - we'll save on blur or Enter- // This way, we avoid saving while the user is still typing+ // --- MODIFICATION END ---}/**@@ -1106,8 +1112,8 @@// Priority settings that should appear at the top of each tabconst prioritySettings = {'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port'],- 'llm': ['provider', 'model', 'temperature', 'max_tokens'],- 'search': ['search_engine', 'tool', 'iterations', 'questions_per_iteration', 'research_iterations', 'max_results', 'region'],+ 'llm': ['provider', 'model', 'temperature', 'max_tokens', 'api_key', 'openai_endpoint_url', 'lmstudio_url', 'llamacpp_model_path'],+ 'search': ['tool', 'search_engine', 'iterations', 'questions_per_iteration', 'research_iterations', 'max_results', 'region'],'report': ['enable_fact_checking', 'knowledge_accumulation', 'output_dir', 'detailed_citations']};@@ -1198,65 +1204,80 @@grouped[prefix][category].push(setting);});- // Second pass: sort settings within each category by priority+ // Second pass: sort settings within each category by priority and sort categoriesfor (const prefix in grouped) {- // Sort the categories themselves to ensure important ones come first- const sortedCategories = {};- const categoryOrder = ['General', 'Interface', 'Connection', 'Model', 'API', 'Parameters'];-// Get existing categories for this prefixconst categories = Object.keys(grouped[prefix]);- // Sort categories- categories.sort((a, b) => {- // Check if either category contains a priority word- const aIndex = categoryOrder.findIndex(word => a.includes(word));- const bIndex = categoryOrder.findIndex(word => b.includes(word));+ // --- MODIFICATION START: Prioritize categories containing specific dropdowns ---+ // Identify high-priority categories+ const highPriorityCategories = [];+ const otherCategories = [];+ const priorityKeysForPrefix = prioritySettings[prefix] || [];+ const highestPriorityKeys = ['provider', 'model', 'tool']; // Keys whose *containing category* should be first- // If both have priority words, sort by priority- if (aIndex !== -1 && bIndex !== -1) {- return aIndex - bIndex;+ categories.forEach(category => {+ const containsHighestPriority = grouped[prefix][category].some(setting => {+ const subKey = setting.key.split('.')[1];+ // Ensure the setting key itself is also in the general priority list for the prefix+ return highestPriorityKeys.includes(subKey) && priorityKeysForPrefix.includes(subKey);+ });+ if (containsHighestPriority) {+ highPriorityCategories.push(category);+ } else {+ otherCategories.push(category);}+ });- // If only one has a priority word, it comes first+ // Sort the high-priority categories (e.g., alphabetically or by specific order if needed)+ highPriorityCategories.sort((a, b) => {+ // Simple sort for now, could be more specific if needed+ // Example: ensure "Provider" comes before "Model" if both are high priority+ const order = ['Provider', 'Model', 'Tool'];+ const aIndex = order.findIndex(word => a.includes(word));+ const bIndex = order.findIndex(word => b.includes(word));+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;if (aIndex !== -1) return -1;if (bIndex !== -1) return 1;+ return a.localeCompare(b);+ });- // Otherwise, alphabetical+ // Sort other categories based on existing logic (e.g., using categoryOrder)+ const categoryOrder = ['General', 'Interface', 'Connection', 'API', 'Parameters']; // Adjusted order slightly+ otherCategories.sort((a, b) => {+ const aIndex = categoryOrder.findIndex(word => a.includes(word));+ const bIndex = categoryOrder.findIndex(word => b.includes(word));+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;+ if (aIndex !== -1) return -1;+ if (bIndex !== -1) return 1;return a.localeCompare(b);});- // Create new object with sorted categories- categories.forEach(category => {- sortedCategories[category] = grouped[prefix][category];+ // Combine sorted categories+ const sortedCategoryNames = [...highPriorityCategories, ...otherCategories];++ // Create new object with sorted categories and sorted settings within each+ const sortedPrefixedCategories = {};+ sortedCategoryNames.forEach(category => {+ sortedPrefixedCategories[category] = grouped[prefix][category];- // Sort settings within this category by priority- sortedCategories[category].sort((a, b) => {+ // Sort settings within this category (existing logic seems okay)+ sortedPrefixedCategories[category].sort((a, b) => {const aKey = a.key.split('.')[1];const bKey = b.key.split('.')[1];-- // Get priority list for this prefixconst priorities = prioritySettings[prefix] || [];-- // If both are in priorities, sort by priority orderconst aIndex = priorities.indexOf(aKey);const bIndex = priorities.indexOf(bKey);-- if (aIndex !== -1 && bIndex !== -1) {- return aIndex - bIndex;- }-- // If only one is in priorities, it comes first+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;if (aIndex !== -1) return -1;if (bIndex !== -1) return 1;-- // Otherwise sort alphabeticallyreturn aKey.localeCompare(bKey);});});// Replace original categories with sorted ones- grouped[prefix] = sortedCategories;+ grouped[prefix] = sortedPrefixedCategories;+ // --- MODIFICATION END ---}return grouped;@@ -1270,6 +1291,10 @@// Only run this for the main settings dashboardif (!settingsContent) return;+ // Reset dropdown initialization state when switching tabs+ window.modelDropdownsInitialized = false;+ window.searchEngineDropdownInitialized = false;+// Filter settings by tablet filteredSettings = allSettings;@@ -1284,7 +1309,7 @@let html = '';// Define the order for the types in "all" tab- const typeOrder = ['app', 'llm', 'search', 'report'];+ const typeOrder = ['llm', 'search', 'report', 'app'];const prefixTypes = Object.keys(groupedSettings);// Sort prefixes by the defined order for the "all" tab@@ -2552,53 +2577,109 @@}/**- * Fetch available model providers from API- * @param {boolean} forceRefresh - Force refresh even if cached data exists+ * Fetch model providers from API+ * @param {boolean} forceRefresh - Whether to force refresh the data+ * @returns {Promise} - A promise that resolves with the model providers*/function fetchModelProviders(forceRefresh = false) {- return new Promise((resolve, reject) => {- const cachedData = getCachedData('deepResearch.modelProviders');- if (!forceRefresh && cachedData) {- resolve(cachedData);- return;- }+ // Use a debounce mechanism to prevent multiple calls in quick succession+ if (window.modelProvidersRequestInProgress && !forceRefresh) {+ console.log('Model providers request already in progress, using existing promise');+ return window.modelProvidersRequestInProgress;+ }- fetch('/research/settings/api/available-models')- .then(response => {- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);- }- return response.json();- })- .then(data => {- if (data && data.providers) {- cacheData('deepResearch.modelProviders', data);- resolve(data);- } else {- reject(new Error('Invalid data format'));- }- })- .catch(error => {- console.error('Error fetching model providers:', error);- // Return a default if we have cached data at least- if (cachedData) {- resolve(cachedData);- } else {- // Provide a fallback with common providers- const fallbackData = {- providers: [- { id: 'OLLAMA', name: 'Ollama (Local)', available: false },- { id: 'OPENAI', name: 'OpenAI API', available: true },- { id: 'ANTHROPIC', name: 'Anthropic API', available: true },- { id: 'OPENAI_ENDPOINT', name: 'OpenAI-compatible Endpoint', available: true }- ],- models: []- };- cacheData('deepResearch.modelProviders', fallbackData);- resolve(fallbackData);- }- });- });+ const cachedData = getCachedData('deepResearch.modelProviders');+ const cacheTimestamp = getCachedData('deepResearch.cacheTimestamp');++ // If not forcing refresh and we have valid cached data, use it+ if (!forceRefresh && cachedData && cacheTimestamp && (Date.now() - cacheTimestamp < 3600000)) { // 1 hour cache+ console.log('Using cached model providers');+ return Promise.resolve(cachedData);+ }++ console.log('Fetching model providers from API');++ // Create a promise and store it+ window.modelProvidersRequestInProgress = fetch('/research/settings/api/available-models')+ .then(response => {+ if (!response.ok) {+ throw new Error(`API returned status: ${response.status}`);+ }+ return response.json();+ })+ .then(data => {+ console.log('Got model data from API:', data);+ // Cache the data for future use+ cacheData('deepResearch.modelProviders', data);+ cacheData('deepResearch.cacheTimestamp', Date.now());++ // Process the data+ const processedData = processModelData(data);+ // Clear the request flag+ window.modelProvidersRequestInProgress = null;+ return processedData;+ })+ .catch(error => {+ console.error('Error fetching model providers:', error);+ // Clear the request flag on error+ window.modelProvidersRequestInProgress = null;+ throw error;+ });++ return window.modelProvidersRequestInProgress;+ }++ /**+ * Fetch search engines from API+ * @param {boolean} forceRefresh - Whether to force refresh the data+ * @returns {Promise} - A promise that resolves with the search engines+ */+ function fetchSearchEngines(forceRefresh = false) {+ // Use a debounce mechanism to prevent multiple calls in quick succession+ if (window.searchEnginesRequestInProgress && !forceRefresh) {+ console.log('Search engines request already in progress, using existing promise');+ return window.searchEnginesRequestInProgress;+ }++ const cachedData = getCachedData('deepResearch.searchEngines');+ const cacheTimestamp = getCachedData('deepResearch.cacheTimestamp');++ // Use cached data if available and not forcing refresh+ if (!forceRefresh && cachedData && cacheTimestamp && (Date.now() - cacheTimestamp < 3600000)) { // 1 hour cache+ console.log('Using cached search engines data');+ return Promise.resolve(cachedData);+ }++ console.log('Fetching search engines from API');++ // Create a promise and store it+ window.searchEnginesRequestInProgress = fetch('/research/settings/api/available-search-engines')+ .then(response => {+ if (!response.ok) {+ throw new Error(`API returned status: ${response.status}`);+ }+ return response.json();+ })+ .then(data => {+ console.log('Received search engine data:', data);+ // Cache the data+ cacheData('deepResearch.searchEngines', data);+ cacheData('deepResearch.cacheTimestamp', Date.now());++ // Process the data+ const processedData = processSearchEngineData(data);+ // Clear the request flag+ window.searchEnginesRequestInProgress = null;+ return processedData;+ })+ .catch(error => {+ console.error('Error fetching search engines:', error);+ // Clear the request flag on error+ window.searchEnginesRequestInProgress = null;+ throw error;+ });++ return window.searchEnginesRequestInProgress;}/**@@ -2638,58 +2719,8 @@console.log('Final modelOptions:', modelOptions);- // Initialize model dropdowns if on the LLM tab- if (activeTab === 'llm' || activeTab === 'all') {- initializeModelDropdowns();- }- }-- /**- * Fetch available search engines from API- * @param {boolean} forceRefresh - Force refresh even if cached data exists- */- function fetchSearchEngines(forceRefresh = false) {- // Show loading state for any search engine refresh buttons- const searchEngineRefreshBtn = document.getElementById('search-tool-refresh');- if (searchEngineRefreshBtn) {- searchEngineRefreshBtn.classList.add('loading');- searchEngineRefreshBtn.querySelector('i').className = 'fas fa-spinner';- }-- // Try to get from cache first if not forcing refresh- if (!forceRefresh) {- const cachedEngines = getCachedData(CACHE_KEYS.SEARCH_ENGINES);- if (cachedEngines) {- console.log('Using cached search engine data');- processSearchEngineData(cachedEngines);- return;- }- }-- fetch('/research/settings/api/available-search-engines')- .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))- .then(data => {- // Cache the data- cacheData(CACHE_KEYS.SEARCH_ENGINES, data);-- // Process the data- processSearchEngineData(data);-- // Reset the refresh button- if (searchEngineRefreshBtn) {- searchEngineRefreshBtn.classList.remove('loading');- searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';- }- })- .catch(error => {- console.error('Error loading search engines:', error);-- // Reset the refresh button- if (searchEngineRefreshBtn) {- searchEngineRefreshBtn.classList.remove('loading');- searchEngineRefreshBtn.querySelector('i').className = 'fas fa-sync-alt';- }- });+ // Always initialize model dropdowns when receiving new data+ initializeModelDropdowns();}/**@@ -2697,13 +2728,15 @@* @param {Object} data - The search engine data*/function processSearchEngineData(data) {+ console.log('Processing search engine data:', data);if (data.engine_options && data.engine_options.length > 0) {searchEngineOptions = data.engine_options;+ console.log('Updated search engine options:', searchEngineOptions);- // Initialize search engine dropdowns if on the right tab- if (activeTab === 'search' || activeTab === 'all') {- initializeSearchEngineDropdowns();- }+ // Always initialize search engine dropdowns when receiving new data+ initializeSearchEngineDropdowns();+ } else {+ console.warn('No engine options found in search engine data');}}@@ -2718,24 +2751,33 @@const settingsModelInput = document.getElementById('llm.model');const providerHiddenInput = document.getElementById('llm.provider_hidden');const modelHiddenInput = document.getElementById('llm.model_hidden');- const providerDropdownList = document.getElementById('setting-llm-provider-dropdown-list'); // Correct ID based on template generation- const modelDropdownList = document.getElementById('setting-llm-model-dropdown-list'); // Correct ID based on template generation+ const providerDropdownList = document.getElementById('setting-llm-provider-dropdown-list');+ const modelDropdownList = document.getElementById('setting-llm-model-dropdown-list');++ // Skip if already initialized (avoid redundant calls)+ if (window.modelDropdownsInitialized) {+ console.log('Model dropdowns already initialized, skipping');+ return;+ }console.log('Found model elements:', {settingsProviderInput: !!settingsProviderInput,settingsModelInput: !!settingsModelInput,providerHiddenInput: !!providerHiddenInput,modelHiddenInput: !!modelHiddenInput,- providerDropdownList: !!providerDropdownList, // Log provider list+ providerDropdownList: !!providerDropdownList,modelDropdownList: !!modelDropdownList});// Check if elements exist before proceedingif (!settingsProviderInput || !providerDropdownList || !providerHiddenInput) {console.warn('LLM Provider input, dropdown list, or hidden input element not found. Skipping provider initialization.');+ return; // Don't proceed if required elements are missing}+if (!settingsModelInput || !modelDropdownList || !modelHiddenInput) {console.warn('LLM Model input, dropdown list, or hidden input element not found. Skipping model initialization.');+ return; // Don't proceed if required elements are missing}// Ensure custom dropdown script is loaded@@ -2744,6 +2786,9 @@return; // Exit if custom dropdown script is not available}+ // Mark as initialized to prevent redundant calls+ window.modelDropdownsInitialized = true;+// Get current settings from database or localStoragelet currentProvider = '';let currentModel = '';@@ -2965,9 +3010,15 @@function initializeSearchEngineDropdowns() {console.log('Initializing search engine dropdown');// Check for the search engine input field- const searchEngineInput = document.getElementById('search.tool'); // Correct ID based on setting key- const searchEngineHiddenInput = document.getElementById('search.tool_hidden'); // Correct hidden ID- const dropdownList = document.getElementById('setting-search-tool-dropdown-list'); // Corrected ID+ const searchEngineInput = document.getElementById('search.tool');+ const searchEngineHiddenInput = document.getElementById('search.tool_hidden');+ const dropdownList = document.getElementById('setting-search-tool-dropdown-list');++ // Skip if already initialized (avoid redundant calls)+ if (window.searchEngineDropdownInitialized) {+ console.log('Search engine dropdown already initialized, skipping');+ return;+ }console.log('Found search engine elements:', {searchEngineInput: !!searchEngineInput,@@ -2975,56 +3026,58 @@dropdownList: !!dropdownList});+ if (!searchEngineInput || !dropdownList || !searchEngineHiddenInput) {+ console.warn('Search engine input, hidden input, or dropdown list not found. Skipping initialization.');+ return; // Exit early if required elements are missing+ }- if (searchEngineInput && dropdownList && searchEngineHiddenInput) {- // Set up the dropdown- if (window.setupCustomDropdown) {- const dropdown = window.setupCustomDropdown(- searchEngineInput,- dropdownList,- () => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: 'auto', label: 'Auto (Default)' }],- (value, item) => {- console.log('Search engine selected:', value);- // Update the hidden input value- searchEngineHiddenInput.value = value;- // Trigger a change event on the hidden input to save- const changeEvent = new Event('change', { bubbles: true });- searchEngineHiddenInput.dispatchEvent(changeEvent);- // Save to localStorage- localStorage.setItem('lastUsedSearchEngine', value);- },- false, // Don't allow custom values- 'No search engines available.'- );-- // Get current value- let currentValue = '';- if (typeof allSettings !== 'undefined' && Array.isArray(allSettings)) {- const currentSetting = allSettings.find(s => s.key === 'search.tool');- if (currentSetting) {- currentValue = currentSetting.value || '';- }- }- if (!currentValue) {- currentValue = localStorage.getItem('lastUsedSearchEngine') || 'auto';- }+ // Mark as initialized to prevent redundant calls+ window.searchEngineDropdownInitialized = true;+ // Set up the dropdown+ if (window.setupCustomDropdown) {+ const dropdown = window.setupCustomDropdown(+ searchEngineInput,+ dropdownList,+ () => searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: 'auto', label: 'Auto (Default)' }],+ (value, item) => {+ console.log('Search engine selected:', value);+ // Update the hidden input value+ searchEngineHiddenInput.value = value;+ // Trigger a change event on the hidden input to save+ const changeEvent = new Event('change', { bubbles: true });+ searchEngineHiddenInput.dispatchEvent(changeEvent);+ // Save to localStorage+ localStorage.setItem('lastUsedSearchEngine', value);+ },+ false, // Don't allow custom values+ 'No search engines available.'+ );- // Set initial value- if (currentValue && dropdown.setValue) {- console.log('Setting initial search engine value:', currentValue);- dropdown.setValue(currentValue, false);- searchEngineHiddenInput.value = currentValue;+ // Get current value+ let currentValue = '';+ if (typeof allSettings !== 'undefined' && Array.isArray(allSettings)) {+ const currentSetting = allSettings.find(s => s.key === 'search.tool');+ if (currentSetting) {+ currentValue = currentSetting.value || '';}+ }+ if (!currentValue) {+ currentValue = localStorage.getItem('lastUsedSearchEngine') || 'auto';+ }- // --- ADD CHANGE LISTENER TO HIDDEN INPUT ---- searchEngineHiddenInput.removeEventListener('change', handleInputChange); // Remove old listener first- searchEngineHiddenInput.addEventListener('change', handleInputChange);- console.log('Added change listener to hidden search engine input:', searchEngineHiddenInput.id);- // --- END OF ADDED LISTENER ---+ // Set initial value+ if (currentValue && dropdown.setValue) {+ console.log('Setting initial search engine value:', currentValue);+ dropdown.setValue(currentValue, false);+ searchEngineHiddenInput.value = currentValue;}- } else {- console.warn('Search engine input, hidden input, or dropdown list not found. Skipping initialization.');++ // --- ADD CHANGE LISTENER TO HIDDEN INPUT ---+ searchEngineHiddenInput.removeEventListener('change', handleInputChange); // Remove old listener first+ searchEngineHiddenInput.addEventListener('change', handleInputChange);+ console.log('Added change listener to hidden search engine input:', searchEngineHiddenInput.id);+ // --- END OF ADDED LISTENER ---}}@@ -3186,43 +3239,17 @@// Initialize JSON handlinginitJsonFormatting();- // Initialize expanded JSON controls- initExpandedJsonControls();-- // Initialize auto-save handlers- initAutoSaveHandlers();-- // Set up custom dropdowns immediately (don't wait for settings to load)- setupCustomDropdowns();-- // Set up event listeners for the settings dashboard- if (settingsForm) {- settingsForm.addEventListener('submit', handleSettingsSubmit);- }-- // Now explicitly fix checkbox handling by modifying the checkbox event handler in initAutoSaveHandlers- document.addEventListener('click', function(e) {- // Check if this is a click inside a boolean property item- const boolItem = e.target.closest('.boolean-property');- if (boolItem) {- const checkboxId = boolItem.dataset.checkboxid;- if (checkboxId) {- const checkbox = document.getElementById(checkboxId);- // Only toggle if the click wasn't directly on the checkbox- if (checkbox && !checkbox.disabled && e.target !== checkbox) {- directToggleCheckbox(checkboxId);- e.preventDefault();- e.stopPropagation();- }- }- }- });-- // Add click handler for the logo to navigate home- const logoLink = document.getElementById('logo-link');- if (logoLink) {- logoLink.addEventListener('click', () => {- window.location.href = '/research/';+ // Load settings from API if on settings dashboard+ if (settingsContent) {+ // First fetch the model and search engine data to have it ready+ // when needed, but don't wait for it to complete+ Promise.all([fetchModelProviders(), fetchSearchEngines()]).then(() => {+ // Then load settings+ loadSettings();+ }).catch(err => {+ console.error("Error fetching providers/engines initially", err);+ // Still try to load settings even if fetching options fails+ loadSettings();});}@@ -3240,13 +3267,22 @@activeTab = tab.dataset.tab;renderSettingsByTab(activeTab);- // Initialize auto-save handlers after rendering- setTimeout(initAutoSaveHandlers, 300);-- // Initialize custom dropdowns after rendering- if (activeTab === 'llm' || activeTab === 'all') {- setTimeout(initializeModelDropdowns, 300);- }+ // Set a small timeout to ensure DOM is ready before initializing+ setTimeout(() => {+ // Initialize dropdowns after rendering content+ // Moved dropdown init inside loadSettings success callback+ // if (activeTab === 'llm' || activeTab === 'all') {+ // initializeModelDropdowns();+ // }+ // if (activeTab === 'search' || activeTab === 'all') {+ // initializeSearchEngineDropdowns();+ // }++ // Re-initialize auto-save handlers after tab switch and render+ initAutoSaveHandlers();+ // Setup refresh buttons after dropdowns might have been created+ setupRefreshButtons();+ }, 100); // Reduced timeout slightly});});}@@ -3262,15 +3298,15 @@resetToDefaultsButton.addEventListener('click', handleResetToDefaults);}- // Add a fix corrupted settings button- const fixCorruptedButton = document.createElement('button');- fixCorruptedButton.setAttribute('type', 'button');- fixCorruptedButton.setAttribute('id', 'fix-corrupted-button');- fixCorruptedButton.className = 'btn btn-info';- fixCorruptedButton.innerHTML = '<i class="fas fa-wrench"></i> Fix Corrupted Settings';- fixCorruptedButton.addEventListener('click', handleFixCorruptedSettings);+ // Add a fix corrupted settings button+ const fixCorruptedButton = document.createElement('button');+ fixCorruptedButton.setAttribute('type', 'button');+ fixCorruptedButton.setAttribute('id', 'fix-corrupted-button');+ fixCorruptedButton.className = 'btn btn-info';+ fixCorruptedButton.innerHTML = '<i class="fas fa-wrench"></i> Fix Corrupted Settings';+ fixCorruptedButton.addEventListener('click', handleFixCorruptedSettings);- // Insert it after the reset to defaults button+ // Insert it after the reset to defaults buttonif (resetToDefaultsButton) {resetToDefaultsButton.insertAdjacentElement('afterend', fixCorruptedButton);}@@ -3280,32 +3316,38 @@rawConfigToggle.addEventListener('click', toggleRawConfig);}- // Load settings from API if on settings dashboard- if (settingsContent) {- loadSettings();-- // Fetch model providers and search engines- fetchModelProviders();- fetchSearchEngines();- }-// Initialize specific settings page form handlersinitSpecificSettingsForm();- // Also add refresh button handlers- setupRefreshButtons();+ // Handle form submission+ if (settingsForm) {+ settingsForm.addEventListener('submit', handleSettingsSubmit);+ }- // Initialize dropdown menus- initializeModelDropdowns();- initializeSearchEngineDropdowns();+ // Add click handler for the logo to navigate home+ const logoLink = document.getElementById('logo-link');+ if (logoLink) {+ logoLink.addEventListener('click', () => {+ window.location.href = '/research/';+ });+ }++ // --- MODIFICATION START: Call initAutoSaveHandlers at the end of initializeSettings ---+ // Initialize auto-save handlers after all other setup+ initAutoSaveHandlers();+ // --- MODIFICATION END ---}// Initialize on DOM content loaded+ // --- MODIFICATION START: Ensure initialization order ---+ // Ensure initialization happens after DOM content is loadedif (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', initializeSettings);+ document.addEventListener('DOMContentLoaded', initializeSettings);} else {+ // DOM is already loaded, run initializeinitializeSettings();}+ // --- MODIFICATION END ---// Expose the setupCustomDropdowns function for other modules to usewindow.setupSettingsDropdowns = initializeModelDropdowns;@@ -3502,14 +3544,18 @@() => optionsSource,(value, item) => {console.log(`Dropdown ${settingKey} selected:`, value);+ // --- MODIFICATION START: Removed hiddenInput retrieval, already have it ---+ const hiddenInput = document.getElementById(`${dropdownInput.id}_hidden`);+ // --- MODIFICATION END ---- // When a value is selected, update the hidden input+ // --- MODIFICATION START: Update hidden input and trigger change ---if (hiddenInput) {hiddenInput.value = value;// Trigger change event to save the settingconst changeEvent = new Event('change', { bubbles: true });hiddenInput.dispatchEvent(changeEvent);}+ // --- MODIFICATION END ---// For provider changes, update model optionsif (settingKey === 'llm.provider' && typeof filterModelOptionsForProvider === 'function') {@@ -3532,18 +3578,27 @@if (currentValue && dropdown.setValue) {console.log(`Setting initial value for ${settingKey}:`, currentValue);dropdown.setValue(currentValue, false); // Don't fire event on init- // Also set the hidden input+ // --- MODIFICATION START: Set hidden input initial value ---+ if (hiddenInput) {hiddenInput.value = currentValue;+ console.log('Set initial hidden input value for', settingKey, 'to', currentValue);}+ // --- MODIFICATION END ---+ }- // --- ADD CHANGE LISTENER TO HIDDEN INPUT ---- // Ensure the listener is added *after* the dropdown is initialized- hiddenInput.removeEventListener('change', handleInputChange); // Remove old listener first- hiddenInput.addEventListener('change', handleInputChange);- console.log('Added change listener to hidden input:', hiddenInput.id);- // --- END OF ADDED LISTENER ---+ // --- MODIFICATION START: Add listener to hidden input in initAutoSaveHandlers ---+ // The listener is added globally in initAutoSaveHandlers now.+ // Ensure initAutoSaveHandlers is called *after* setupCustomDropdowns.+ // --- MODIFICATION END ---}});++ // --- MODIFICATION START: Call initAutoSaveHandlers after setup ---+ // Ensure initAutoSaveHandlers is called after dropdowns are set up+ // It might be better to call initAutoSaveHandlers once after all rendering and setup is done.+ // Let's move the call within initializeSettings() to ensure order.+ initAutoSaveHandlers();+ // --- MODIFICATION END ---}/**@@ -3564,6 +3619,10 @@return;}+ // Check if dropdown is currently open+ const isDropdownOpen = window.getComputedStyle(modelDropdownList).display !== 'none';+ console.log('Dropdown is currently:', isDropdownOpen ? 'open' : 'closed');+// Filter the models based on providerconst filteredModels = modelOptions.filter(model => {if (!model || typeof model !== 'object') return false;@@ -3589,9 +3648,42 @@console.log(`Filtered models for ${providerUpper}:`, filteredModels.length, 'models');- // Re-initialize the dropdown with filtered models+ // Try to update the dropdown options without reinitializing if possible+ if (window.updateDropdownOptions && typeof window.updateDropdownOptions === 'function') {+ console.log('Using updateDropdownOptions to preserve dropdown state');+ window.updateDropdownOptions(modelInput, filteredModels);++ // Try to maintain the current selection if applicable+ const currentModel = modelHiddenInput ? modelHiddenInput.value : null;+ if (currentModel) {+ // Check if current model is valid for this provider+ const isValid = filteredModels.some(m => m.value === currentModel);+ if (!isValid && filteredModels.length > 0) {+ // Select first available model if current is not valid+ const firstModel = filteredModels[0].value;+ console.log(`Current model ${currentModel} invalid for provider ${providerUpper}. Setting to first available: ${firstModel}`);+ modelHiddenInput.value = firstModel;+ modelInput.value = filteredModels[0].label || firstModel;+ }+ }++ // If dropdown was open, ensure it stays open+ if (isDropdownOpen) {+ setTimeout(() => {+ if (modelDropdownList.style.display === 'none') {+ console.log('Reopening dropdown that was closed during update');+ modelDropdownList.style.display = 'block';+ }+ }, 50);+ }++ return;+ }++ // Backup method - reinitialize the dropdown but try to preserve open stateif (window.setupCustomDropdown) {console.log('Reinitializing model dropdown with filtered models');+// Store the returned control objectconst modelDropdownControl = window.setupCustomDropdown(modelInput,@@ -3636,6 +3728,14 @@}}}++ // If dropdown was open, force it to reopen+ if (isDropdownOpen) {+ setTimeout(() => {+ console.log('Reopening dropdown that was closed during reinitialization');+ modelDropdownList.style.display = 'block';+ }, 100);+ }}// Also update any provider-dependent UI@@ -3830,4 +3930,101 @@});});}++ /**+ * Create a refresh button for a dropdown input+ * @param {string} inputId - The ID of the input to create a refresh button for+ * @param {Function} fetchFunc - The function to call when the button is clicked+ */+ function createRefreshButton(inputId, fetchFunc) {+ console.log('Creating refresh button for', inputId);+ // Check if the input exists+ const input = document.getElementById(inputId);+ if (!input) {+ console.warn(`Cannot create refresh button for non-existent input: ${inputId}`);+ return null;+ }++ // Find the parent container+ const container = input.closest('.form-group');+ if (!container) {+ console.warn(`Cannot find container for input: ${inputId}`);+ return null;+ }++ // Create a new button+ const refreshBtn = document.createElement('button');+ refreshBtn.type = 'button';+ refreshBtn.id = inputId + '-refresh';+ refreshBtn.className = 'custom-dropdown-refresh-btn';+ refreshBtn.setAttribute('aria-label', 'Refresh options');+ refreshBtn.style.display = 'flex';+ refreshBtn.style.alignItems = 'center';+ refreshBtn.style.justifyContent = 'center';+ refreshBtn.style.width = '38px';+ refreshBtn.style.height = '38px';+ refreshBtn.style.backgroundColor = 'var(--bg-tertiary, #2a2a3a)';+ refreshBtn.style.border = '1px solid var(--border-color, #343452)';+ refreshBtn.style.borderRadius = '6px';+ refreshBtn.style.cursor = 'pointer';+ refreshBtn.style.marginLeft = '8px';++ // Add icon to the button+ const icon = document.createElement('i');+ icon.className = 'fas fa-sync-alt';+ refreshBtn.appendChild(icon);++ // Add event listener to the button+ refreshBtn.addEventListener('click', function(e) {+ e.preventDefault();+ e.stopPropagation();++ console.log('Refresh button clicked for', inputId);+ icon.className = 'fas fa-spinner fa-spin';++ // Reset initialization flags+ if (inputId.includes('llm') || inputId.includes('model')) {+ window.modelDropdownsInitialized = false;+ } else if (inputId.includes('search') || inputId.includes('tool')) {+ window.searchEngineDropdownInitialized = false;+ }++ // Call the function directly as a parameter+ fetchFunc(true).then(() => {+ icon.className = 'fas fa-sync-alt';++ // Re-initialize appropriate dropdowns+ if (inputId.includes('llm') || inputId.includes('model')) {+ initializeModelDropdowns();+ } else if (inputId.includes('search') || inputId.includes('tool')) {+ initializeSearchEngineDropdowns();+ }++ showAlert(`Options refreshed`, 'success');+ }).catch(error => {+ console.error('Error refreshing options:', error);+ icon.className = 'fas fa-sync-alt';+ showAlert('Failed to refresh options', 'error');+ });+ });++ // Find the input wrapper or create one+ let inputWrapper = input.parentElement;+ if (inputWrapper.classList.contains('custom-dropdown-input')) {+ inputWrapper = inputWrapper.parentElement;+ }++ if (inputWrapper) {+ // Add the button after the input+ inputWrapper.style.display = 'flex';+ inputWrapper.style.alignItems = 'center';+ inputWrapper.style.gap = '8px';+ inputWrapper.appendChild(refreshBtn);+ console.log('Created new refresh button for:', inputId);+ return refreshBtn;+ }++ console.warn(`Could not find a suitable place to add refresh button for ${inputId}`);+ return null;+ }})();diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.htmlindex 139c049975..8027854ff2 100644--- a/src/local_deep_research/web/templates/components/settings_form.html+++ b/src/local_deep_research/web/templates/components/settings_form.html@@ -185,8 +185,8 @@label=None,help_text=setting.description if setting.description else None,allow_custom=setting.key == "llm.model",- show_refresh=setting.key == "llm.model",- refresh_aria_label="Refresh model list",+ show_refresh=True,+ refresh_aria_label="Refresh model list" if setting.key == "llm.model" else "Refresh search engine list",data_setting_key=setting.key) }}