~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
Remove localStorage usage for settings - always use database
LearningCircuit5daf10d0cb49
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex dab53f5423..ac5134c717 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -249,18 +249,42 @@ def get_llm(research_context=research_context,)- # Check if we're in testing mode and should use fallback (but only for standard providers)- if (- os.environ.get("LDR_USE_FALLBACK_LLM", "")- and provider in VALID_PROVIDERS- ):- logger.info("LDR_USE_FALLBACK_LLM is set, using fallback model")- return wrap_llm_without_think_tags(- get_fallback_model(temperature),- research_id=research_id,- provider="fallback",- research_context=research_context,- )+ # Check if we're in testing mode and should use fallback (but only when no API keys are configured)+ if os.environ.get("LDR_USE_FALLBACK_LLM", ""):+ # Only use fallback if the provider has no valid configuration+ provider_has_config = False++ if provider == "openai" and get_db_setting("llm.openai.api_key"):+ provider_has_config = True+ elif provider == "anthropic" and get_db_setting(+ "llm.anthropic.api_key"+ ):+ provider_has_config = True+ elif provider == "openai_endpoint" and get_db_setting(+ "llm.openai_endpoint.api_key"+ ):+ provider_has_config = True+ elif provider == "ollama" and is_ollama_available():+ provider_has_config = True+ elif provider in ["vllm", "lmstudio", "llamacpp"]:+ # These are local providers, check their availability+ if provider == "vllm" and is_vllm_available():+ provider_has_config = True+ elif provider == "lmstudio" and is_lmstudio_available():+ provider_has_config = True+ elif provider == "llamacpp" and is_llamacpp_available():+ provider_has_config = True++ if not provider_has_config:+ logger.info(+ "LDR_USE_FALLBACK_LLM is set and no valid provider config found, using fallback model"+ )+ return wrap_llm_without_think_tags(+ get_fallback_model(temperature),+ research_id=research_id,+ provider="fallback",+ research_context=research_context,+ )# Validate providerif provider not in VALID_PROVIDERS:diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex e927b890d3..14fe48fc66 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -180,8 +180,22 @@ def register_blueprints(app):def index():"""Root route - serve the research page directly"""from .utils.templates import render_template_with_defaults-- return render_template_with_defaults("pages/research.html")+ from ..utilities.db_utils import get_db_setting++ # Load current settings from database+ settings = {+ "llm_provider": get_db_setting("llm.provider", "ollama"),+ "llm_model": get_db_setting("llm.model", ""),+ "search_tool": get_db_setting("search.tool", ""),+ "search_iterations": get_db_setting("search.iterations", 2),+ "search_questions_per_iteration": get_db_setting(+ "search.questions_per_iteration", 3+ ),+ }++ return render_template_with_defaults(+ "pages/research.html", settings=settings+ )# Register blueprintsapp.register_blueprint(research_bp)diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.jsindex 4c073cc107..0afd59b121 100644--- a/src/local_deep_research/web/static/js/components/progress.js+++ b/src/local_deep_research/web/static/js/components/progress.js@@ -35,7 +35,7 @@*/function initializeProgress() {// Get research ID from URL or localStorage- currentResearchId = getResearchIdFromUrl() || localStorage.getItem('currentResearchId');+ currentResearchId = getResearchIdFromUrl(); // Only from URL, not localStorageif (!currentResearchId) {console.error('No research ID found');@@ -105,7 +105,7 @@console.log('Progress component initialized for research ID:', currentResearchId);// Get notification preference- notificationsEnabled = localStorage.getItem('notificationsEnabled') === 'true';+ notificationsEnabled = true; // Default to enabled// Get initial research statusgetInitialStatus();@@ -338,8 +338,8 @@// Update the current query text if availableconst currentQueryEl = document.getElementById('current-query');- if (currentQueryEl && localStorage.getItem('currentQuery')) {- currentQueryEl.textContent = localStorage.getItem('currentQuery');+ if (currentQueryEl && data.query) {+ currentQueryEl.textContent = data.query;}// If no task info was provided, leave the current task as is@@ -597,7 +597,7 @@}// Show notification if enabled- if (data.status === 'completed' && localStorage.getItem('notificationsEnabled') === 'true') {+ if (data.status === 'completed' && notificationsEnabled) {showNotification('Research Completed', 'Your research has been completed successfully.');}diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 96d50d7c60..6668e49891 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -139,28 +139,9 @@advancedToggle = document.querySelector('.advanced-options-toggle');advancedPanel = document.querySelector('.advanced-options-panel');- // 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');- const lastStrategy = localStorage.getItem('lastUsedStrategy') || 'source-based';--- // 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';- }- }-- // Apply saved strategy- const strategySelect = document.getElementById('strategy');- if (strategySelect && lastStrategy) {- strategySelect.value = lastStrategy;- }+ // Note: Settings are now loaded from the database via the template+ // The form values are already set by the server-side rendering+ // We just need to initialize the UI components// Initialize the UI first (immediate operations)setupEventListeners();@@ -177,7 +158,7 @@}// Set initial state of the advanced options panel based on localStorage- const savedState = localStorage.getItem('advancedOptionsOpen') === 'true';+ const savedState = false; // Always start collapsedif (savedState && advancedPanel) {advancedPanel.style.display = 'block';advancedPanel.classList.add('expanded');@@ -425,7 +406,7 @@// Advanced options toggle - make immediately responsiveif (advancedToggle && advancedPanel) {// Set initial state based on localStorage, relying only on CSS classes- const savedState = localStorage.getItem('advancedOptionsOpen') === 'true';+ const savedState = false; // Always start collapsedif (savedState) {advancedToggle.classList.add('open');@@ -481,7 +462,7 @@}// Save state to localStorage- localStorage.setItem('advancedOptionsOpen', isOpen);+ // Don't save to localStorage, let server handle state// Update iconconst icon = this.querySelector('i');@@ -951,7 +932,7 @@console.log(`Updated model options for provider ${provider}: ${modelOptions.length} models`);// Check for stored last model before deciding what to select- let lastSelectedModel = localStorage.getItem('lastUsedModel');+ let lastSelectedModel = null; // Don't use localStorage// Also check the database settingfetch(URLS.SETTINGS_API.LLM_MODEL, {@@ -1245,7 +1226,7 @@console.log('Found matching provider option:', matchingOption.value);modelProviderSelect.value = matchingOption.value;// Also save to localStorage- localStorage.setItem('lastUsedProvider', matchingOption.value);+ // Provider saved to DB: matchingOption.value);} else {// If no match, try to find case-insensitive or partial matchconst caseInsensitiveMatch = Array.from(modelProviderSelect.options).find(@@ -1257,7 +1238,7 @@console.log('Found case-insensitive provider match:', caseInsensitiveMatch.value);modelProviderSelect.value = caseInsensitiveMatch.value;// Also save to localStorage- localStorage.setItem('lastUsedProvider', caseInsensitiveMatch.value);+ // Provider saved to DB: caseInsensitiveMatch.value);} else {console.warn(`No matching provider option found for '${providerValue}'`);}@@ -1288,7 +1269,7 @@console.log('Setting model to:', modelValue);// Save to localStorage- localStorage.setItem('lastUsedModel', modelValue);+ // Model saved to DB// Find the model in our loaded optionsconst matchingModel = modelOptions.find(m =>@@ -1330,7 +1311,7 @@console.log('Setting search engine to:', engineValue);// Save to localStorage- localStorage.setItem('lastUsedSearchEngine', engineValue);+ // Search engine saved to DB// Find the engine in our loaded optionsconst matchingEngine = searchEngineOptions.find(e =>@@ -1409,7 +1390,7 @@strategySelect.value = strategyValue;// Save to localStorage- localStorage.setItem('lastUsedStrategy', strategyValue);+ // Strategy saved to DB}numApiCallsPending--;@@ -1419,7 +1400,7 @@console.error('Error loading strategy:', error);// Fallback to localStorage- const lastStrategy = localStorage.getItem('lastUsedStrategy');+ const lastStrategy = null; // Strategy loaded from DBconst strategySelect = document.getElementById('strategy');if (lastStrategy && strategySelect) {strategySelect.value = lastStrategy;@@ -1432,9 +1413,10 @@// Add a fallback function to use localStorage settingsfunction fallbackToLocalStorageSettings() {- const provider = localStorage.getItem('lastUsedProvider');- const model = localStorage.getItem('lastUsedModel');- const searchEngine = localStorage.getItem('lastUsedSearchEngine');+ // Settings are loaded from database, not localStorage+ const provider = null;+ const model = null;+ const searchEngine = null;console.log('Falling back to localStorage settings:', { provider, model, searchEngine });@@ -1645,23 +1627,14 @@];}- // Cache and retrieve data in localStorage+ // Don't cache data - always use fresh from APIfunction cacheData(key, data) {- try {- localStorage.setItem(key, JSON.stringify(data));- } catch (e) {- console.error('Error caching data:', e);- }+ // No-op - we don't cache anymore}function getCachedData(key) {- try {- const item = localStorage.getItem(key);- return item ? JSON.parse(item) : null;- } catch (e) {- console.error('Error retrieving cached data:', e);- return null;- }+ // No cache - always return null to force API fetch+ return null;}// Load search engine options@@ -1806,8 +1779,7 @@// Save model settings to databasefunction saveModelSettings(modelValue) {- // Save selection to localStorage for persistence between sessions- localStorage.setItem('lastUsedModel', modelValue);+ // Only save to database, not localStorage// Update any hidden input with the same settings key that might exist in other formsconst hiddenInputs = document.querySelectorAll('input[id$="_hidden"][name="llm.model"]');@@ -1845,8 +1817,7 @@// Save search engine settings to databasefunction saveSearchEngineSettings(engineValue) {- // Save to localStorage- localStorage.setItem('lastUsedSearchEngine', engineValue);+ // Only save to database, not localStorage// Update any hidden input with the same settings key that might exist in other formsconst hiddenInputs = document.querySelectorAll('input[id$="_hidden"][name="search.tool"]');@@ -1884,8 +1855,7 @@// Save provider setting to databasefunction saveProviderSetting(providerValue) {- // Save to localStorage- localStorage.setItem('lastUsedProvider', providerValue);+ // Only save to database, not localStorage// Update any hidden input with the same settings key that might exist in other formsconst hiddenInputs = document.querySelectorAll('input[id$="_hidden"][name="llm.provider"]');@@ -2042,12 +2012,7 @@console.log('Research started successfully:', data);// Store research preferences in localStorage- localStorage.setItem('lastResearchMode', mode);- localStorage.setItem('lastModelProvider', modelProvider);- localStorage.setItem('lastModel', model);- localStorage.setItem('lastSearchEngine', searchEngine);- localStorage.setItem('enableNotifications', enableNotifications);- localStorage.setItem('lastUsedStrategy', strategy);+ // Settings are saved to database via the API, not localStorage// Redirect to the progress pagewindow.location.href = URLBuilder.progressPage(data.research_id);diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex b89ef8f91e..3509a134d6 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -172,12 +172,12 @@function cacheData(key, data) {try {// Store the data- localStorage.setItem(key, JSON.stringify(data));+ // Don't cache - always fetch fresh from API// Update or set the timestamplet timestamps;try {- timestamps = JSON.parse(localStorage.getItem(CACHE_KEYS.CACHE_TIMESTAMP) || '{}');+ timestamps = {}; // No cache timestamps// Ensure timestamps is an object, not a number or other typeif (typeof timestamps !== 'object' || timestamps === null) {timestamps = {};@@ -188,7 +188,7 @@}timestamps[key] = Date.now();- localStorage.setItem(CACHE_KEYS.CACHE_TIMESTAMP, JSON.stringify(timestamps));+ // Don't save cache timestampsconsole.log(`Cached data for ${key}`);} catch (error) {@@ -206,7 +206,7 @@// Get timestampslet timestamps;try {- timestamps = JSON.parse(localStorage.getItem(CACHE_KEYS.CACHE_TIMESTAMP) || '{}');+ timestamps = {}; // No cache timestamps// Ensure timestamps is an object, not a number or other typeif (typeof timestamps !== 'object' || timestamps === null) {timestamps = {};@@ -221,7 +221,7 @@// Check if data exists and is not expiredif (timestamp && (Date.now() - timestamp < CACHE_EXPIRATION)) {try {- const data = JSON.parse(localStorage.getItem(key));+ const data = null; // No cached datareturn data;} catch (e) {console.error('Error parsing cached data:', e);@@ -2917,7 +2917,7 @@filterModelOptionsForProvider(value);// Save to localStorage- localStorage.setItem('lastUsedProvider', value);+ // Provider saved to DB// Trigger saveconst changeEvent = new Event('change', { bubbles: true });@@ -2963,7 +2963,7 @@modelHiddenInput.value = value;// Save to localStorage- localStorage.setItem('lastUsedModel', value);+ // Model saved to DB}},true // Allow custom values@@ -3102,7 +3102,7 @@const changeEvent = new Event('change', { bubbles: true });searchEngineHiddenInput.dispatchEvent(changeEvent);// Save to localStorage- localStorage.setItem('lastUsedSearchEngine', value);+ // Search engine saved to DB},false, // Don't allow custom values'No search engines available.'@@ -3117,7 +3117,7 @@}}if (!currentValue) {- currentValue = localStorage.getItem('lastUsedSearchEngine') || 'auto';+ currentValue = 'auto'; // Default value, actual value comes from DB}// Set initial value@@ -3509,11 +3509,11 @@// Fallback to localStorage values if we don't have a value yetif (!currentValue) {if (settingKey === 'llm.model') {- currentValue = localStorage.getItem('lastUsedModel') || '';+ currentValue = ''; // Value comes from DB} else if (settingKey === 'llm.provider') {- currentValue = localStorage.getItem('lastUsedProvider') || '';+ currentValue = ''; // Value comes from DB} else if (settingKey === 'search.tool') {- currentValue = localStorage.getItem('lastUsedSearchEngine') || '';+ currentValue = ''; // Value comes from DB}}@@ -3625,11 +3625,11 @@// Save to localStorage for persistenceif (settingKey === 'llm.model') {- localStorage.setItem('lastUsedModel', value);+ // Model saved to DB} else if (settingKey === 'llm.provider') {localStorage.setItem('lastUsedProvider', value);} else if (settingKey === 'search.tool') {- localStorage.setItem('lastUsedSearchEngine', value);+ // Search engine saved to DB}},allowCustomdiff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.jsindex c669596488..e8d194d514 100644--- a/src/local_deep_research/web/static/js/research_form.js+++ b/src/local_deep_research/web/static/js/research_form.js@@ -162,7 +162,7 @@ function setupWarningListeners() {strategySelect.addEventListener('change', function() {// Save strategy to localStorage- localStorage.setItem('lastUsedStrategy', strategySelect.value);+ // Strategy saved to database via API// Save strategy to databaseconst csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex e2618cf7b8..495348f10d 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -128,14 +128,14 @@<!-- Search Iterations --><div class="form-group half"><label for="iterations">Search Iterations</label>- <input type="number" id="iterations" name="iterations" class="form-control" min="1" max="5" value="2">+ <input type="number" id="iterations" name="iterations" class="form-control" min="1" max="5" value="{{ settings.search_iterations }}"><span class="input-help">Number of research cycles to perform</span></div><!-- Questions Per Iteration --><div class="form-group half"><label for="questions_per_iteration">Questions Per Iteration</label>- <input type="number" id="questions_per_iteration" name="questions_per_iteration" class="form-control" min="1" max="10" value="3">+ <input type="number" id="questions_per_iteration" name="questions_per_iteration" class="form-control" min="1" max="10" value="{{ settings.search_questions_per_iteration }}"><span class="input-help">Follow-up questions in each cycle</span></div></div>