~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: Add API key inputs to research front page for cloud providers
LearningCircuitd96f5cf19e2e
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 9404265376..302ee3f40b 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -19,6 +19,23 @@let lmstudioUrlContainer = null;let contextWindowInput = null;let contextWindowContainer = null;+ // API Key inputs and containers+ let openaiApiKeyInput = null;+ let openaiApiKeyContainer = null;+ let anthropicApiKeyInput = null;+ let anthropicApiKeyContainer = null;+ let googleApiKeyInput = null;+ let googleApiKeyContainer = null;+ let openrouterApiKeyInput = null;+ let openrouterApiKeyContainer = null;+ let xaiApiKeyInput = null;+ let xaiApiKeyContainer = null;+ let ionosApiKeyInput = null;+ let ionosApiKeyContainer = null;+ let openaiEndpointApiKeyInput = null;+ let openaiEndpointApiKeyContainer = null;+ let ollamaApiKeyInput = null;+ let ollamaApiKeyContainer = null;let modelInput = null;let modelDropdown = null;let modelDropdownList = null;@@ -124,6 +141,24 @@contextWindowInput = document.getElementById('context_window');contextWindowContainer = document.getElementById('context_window_container');+ // API Key elements+ openaiApiKeyInput = document.getElementById('openai_api_key');+ openaiApiKeyContainer = document.getElementById('openai_api_key_container');+ anthropicApiKeyInput = document.getElementById('anthropic_api_key');+ anthropicApiKeyContainer = document.getElementById('anthropic_api_key_container');+ googleApiKeyInput = document.getElementById('google_api_key');+ googleApiKeyContainer = document.getElementById('google_api_key_container');+ openrouterApiKeyInput = document.getElementById('openrouter_api_key');+ openrouterApiKeyContainer = document.getElementById('openrouter_api_key_container');+ xaiApiKeyInput = document.getElementById('xai_api_key');+ xaiApiKeyContainer = document.getElementById('xai_api_key_container');+ ionosApiKeyInput = document.getElementById('ionos_api_key');+ ionosApiKeyContainer = document.getElementById('ionos_api_key_container');+ openaiEndpointApiKeyInput = document.getElementById('openai_endpoint_api_key');+ openaiEndpointApiKeyContainer = document.getElementById('openai_endpoint_api_key_container');+ ollamaApiKeyInput = document.getElementById('ollama_api_key');+ ollamaApiKeyContainer = document.getElementById('ollama_api_key_container');+// Custom dropdown elementsmodelInput = document.getElementById('model');modelDropdown = document.getElementById('model-dropdown');@@ -656,6 +691,32 @@contextWindowContainer.style.display = isLocalProvider(provider) ? 'block' : 'none';}+ // Show API key input for cloud providers+ if (openaiApiKeyContainer) {+ openaiApiKeyContainer.style.display = provider === 'OPENAI' ? 'block' : 'none';+ }+ if (anthropicApiKeyContainer) {+ anthropicApiKeyContainer.style.display = provider === 'ANTHROPIC' ? 'block' : 'none';+ }+ if (googleApiKeyContainer) {+ googleApiKeyContainer.style.display = provider === 'GOOGLE' ? 'block' : 'none';+ }+ if (openrouterApiKeyContainer) {+ openrouterApiKeyContainer.style.display = provider === 'OPENROUTER' ? 'block' : 'none';+ }+ if (xaiApiKeyContainer) {+ xaiApiKeyContainer.style.display = provider === 'XAI' ? 'block' : 'none';+ }+ if (ionosApiKeyContainer) {+ ionosApiKeyContainer.style.display = provider === 'IONOS' ? 'block' : 'none';+ }+ if (openaiEndpointApiKeyContainer) {+ openaiEndpointApiKeyContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';+ }+ if (ollamaApiKeyContainer) {+ ollamaApiKeyContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';+ }+// Update model options based on provider// Don't reset model selection - preserve it if valid for new providerupdateModelOptionsForProvider(provider, false);@@ -736,6 +797,48 @@});}+ // API Key change handlers - save to settings manager+ if (openaiApiKeyInput) {+ openaiApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.openai.api_key', this.value);+ });+ }+ if (anthropicApiKeyInput) {+ anthropicApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.anthropic.api_key', this.value);+ });+ }+ if (googleApiKeyInput) {+ googleApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.google.api_key', this.value);+ });+ }+ if (openrouterApiKeyInput) {+ openrouterApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.openrouter.api_key', this.value);+ });+ }+ if (xaiApiKeyInput) {+ xaiApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.xai.api_key', this.value);+ });+ }+ if (ionosApiKeyInput) {+ ionosApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.ionos.api_key', this.value);+ });+ }+ if (openaiEndpointApiKeyInput) {+ openaiEndpointApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.openai_endpoint.api_key', this.value);+ });+ }+ if (ollamaApiKeyInput) {+ ollamaApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.ollama.api_key', this.value);+ });+ }+// Load options data from APIsPromise.all([loadModelOptions(false),@@ -837,6 +940,33 @@contextWindowContainer.style.display = isLocalProvider(selectedProvider) ? 'block' : 'none';}+ // Show API key containers based on initial provider+ const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();+ if (openaiApiKeyContainer) {+ openaiApiKeyContainer.style.display = selectedProvider === 'OPENAI' ? 'block' : 'none';+ }+ if (anthropicApiKeyContainer) {+ anthropicApiKeyContainer.style.display = selectedProvider === 'ANTHROPIC' ? 'block' : 'none';+ }+ if (googleApiKeyContainer) {+ googleApiKeyContainer.style.display = selectedProvider === 'GOOGLE' ? 'block' : 'none';+ }+ if (openrouterApiKeyContainer) {+ openrouterApiKeyContainer.style.display = selectedProvider === 'OPENROUTER' ? 'block' : 'none';+ }+ if (xaiApiKeyContainer) {+ xaiApiKeyContainer.style.display = selectedProvider === 'XAI' ? 'block' : 'none';+ }+ if (ionosApiKeyContainer) {+ ionosApiKeyContainer.style.display = selectedProvider === 'IONOS' ? 'block' : 'none';+ }+ if (openaiEndpointApiKeyContainer) {+ openaiEndpointApiKeyContainer.style.display = selectedProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';+ }+ if (ollamaApiKeyContainer) {+ ollamaApiKeyContainer.style.display = selectedProvider === 'OLLAMA' ? 'block' : 'none';+ }+// Initial update of model optionsconst providerToUpdate = modelProviderSelect.value || initialProvider.toUpperCase();updateModelOptionsForProvider(providerToUpdate);@@ -1412,6 +1542,32 @@if (contextWindowContainer) {contextWindowContainer.style.display = isLocalProvider(providerValue) ? 'block' : 'none';}++ // Display API key containers based on provider+ if (openaiApiKeyContainer) {+ openaiApiKeyContainer.style.display = providerValue === 'OPENAI' ? 'block' : 'none';+ }+ if (anthropicApiKeyContainer) {+ anthropicApiKeyContainer.style.display = providerValue === 'ANTHROPIC' ? 'block' : 'none';+ }+ if (googleApiKeyContainer) {+ googleApiKeyContainer.style.display = providerValue === 'GOOGLE' ? 'block' : 'none';+ }+ if (openrouterApiKeyContainer) {+ openrouterApiKeyContainer.style.display = providerValue === 'OPENROUTER' ? 'block' : 'none';+ }+ if (xaiApiKeyContainer) {+ xaiApiKeyContainer.style.display = providerValue === 'XAI' ? 'block' : 'none';+ }+ if (ionosApiKeyContainer) {+ ionosApiKeyContainer.style.display = providerValue === 'IONOS' ? 'block' : 'none';+ }+ if (openaiEndpointApiKeyContainer) {+ openaiEndpointApiKeyContainer.style.display = providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';+ }+ if (ollamaApiKeyContainer) {+ ollamaApiKeyContainer.style.display = providerValue === 'OLLAMA' ? 'block' : 'none';+ }}// Update the custom endpoint URl if we have one.@@ -1447,6 +1603,55 @@contextWindowInput.disabled = !contextWindowSetting.editable;}+ // Update API key inputs from settings+ const openaiApiKeySetting = data.settings['llm.openai.api_key'];+ if (openaiApiKeySetting && openaiApiKeyInput) {+ openaiApiKeyInput.value = openaiApiKeySetting.value || '';+ openaiApiKeyInput.disabled = !openaiApiKeySetting.editable;+ }++ const anthropicApiKeySetting = data.settings['llm.anthropic.api_key'];+ if (anthropicApiKeySetting && anthropicApiKeyInput) {+ anthropicApiKeyInput.value = anthropicApiKeySetting.value || '';+ anthropicApiKeyInput.disabled = !anthropicApiKeySetting.editable;+ }++ const googleApiKeySetting = data.settings['llm.google.api_key'];+ if (googleApiKeySetting && googleApiKeyInput) {+ googleApiKeyInput.value = googleApiKeySetting.value || '';+ googleApiKeyInput.disabled = !googleApiKeySetting.editable;+ }++ const openrouterApiKeySetting = data.settings['llm.openrouter.api_key'];+ if (openrouterApiKeySetting && openrouterApiKeyInput) {+ openrouterApiKeyInput.value = openrouterApiKeySetting.value || '';+ openrouterApiKeyInput.disabled = !openrouterApiKeySetting.editable;+ }++ const xaiApiKeySetting = data.settings['llm.xai.api_key'];+ if (xaiApiKeySetting && xaiApiKeyInput) {+ xaiApiKeyInput.value = xaiApiKeySetting.value || '';+ xaiApiKeyInput.disabled = !xaiApiKeySetting.editable;+ }++ const ionosApiKeySetting = data.settings['llm.ionos.api_key'];+ if (ionosApiKeySetting && ionosApiKeyInput) {+ ionosApiKeyInput.value = ionosApiKeySetting.value || '';+ ionosApiKeyInput.disabled = !ionosApiKeySetting.editable;+ }++ const openaiEndpointApiKeySetting = data.settings['llm.openai_endpoint.api_key'];+ if (openaiEndpointApiKeySetting && openaiEndpointApiKeyInput) {+ openaiEndpointApiKeyInput.value = openaiEndpointApiKeySetting.value || '';+ openaiEndpointApiKeyInput.disabled = !openaiEndpointApiKeySetting.editable;+ }++ const ollamaApiKeySetting = data.settings['llm.ollama.api_key'];+ if (ollamaApiKeySetting && ollamaApiKeyInput) {+ ollamaApiKeyInput.value = ollamaApiKeySetting.value || '';+ ollamaApiKeyInput.disabled = !ollamaApiKeySetting.editable;+ }+// Load model options based on the current providerconst currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';updateModelOptionsForProvider(currentProvider, false).then(() => {@@ -1632,6 +1837,31 @@if (contextWindowContainer) {contextWindowContainer.style.display = isLocalProvider(provider) ? 'block' : 'none';}+ // Show/hide API key containers based on provider+ if (openaiApiKeyContainer) {+ openaiApiKeyContainer.style.display = provider === 'OPENAI' ? 'block' : 'none';+ }+ if (anthropicApiKeyContainer) {+ anthropicApiKeyContainer.style.display = provider === 'ANTHROPIC' ? 'block' : 'none';+ }+ if (googleApiKeyContainer) {+ googleApiKeyContainer.style.display = provider === 'GOOGLE' ? 'block' : 'none';+ }+ if (openrouterApiKeyContainer) {+ openrouterApiKeyContainer.style.display = provider === 'OPENROUTER' ? 'block' : 'none';+ }+ if (xaiApiKeyContainer) {+ xaiApiKeyContainer.style.display = provider === 'XAI' ? 'block' : 'none';+ }+ if (ionosApiKeyContainer) {+ ionosApiKeyContainer.style.display = provider === 'IONOS' ? 'block' : 'none';+ }+ if (openaiEndpointApiKeyContainer) {+ openaiEndpointApiKeyContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';+ }+ if (ollamaApiKeyContainer) {+ ollamaApiKeyContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';+ }}const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 81334961b7..2585f86043 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -115,6 +115,70 @@<input type="number" id="context_window" name="context_window" class="ldr-form-control" min="512" max="131072" step="512" value="{{ settings.llm_local_context_window_size }}"><span class="ldr-input-help">Context window size in tokens (num_ctx)</span></div>++ <!-- OpenAI API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="openai_api_key_container" style="display: none;">+ <label for="openai_api_key">OpenAI API Key</label>+ <input type="password" id="openai_api_key" name="openai_api_key" class="ldr-form-control"+ placeholder="sk-..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key at platform.openai.com</span>+ </div>++ <!-- Anthropic API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="anthropic_api_key_container" style="display: none;">+ <label for="anthropic_api_key">Anthropic API Key</label>+ <input type="password" id="anthropic_api_key" name="anthropic_api_key" class="ldr-form-control"+ placeholder="sk-ant-..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key at console.anthropic.com</span>+ </div>++ <!-- Google API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="google_api_key_container" style="display: none;">+ <label for="google_api_key">Google API Key</label>+ <input type="password" id="google_api_key" name="google_api_key" class="ldr-form-control"+ placeholder="AIza..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key at aistudio.google.com</span>+ </div>++ <!-- OpenRouter API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="openrouter_api_key_container" style="display: none;">+ <label for="openrouter_api_key">OpenRouter API Key</label>+ <input type="password" id="openrouter_api_key" name="openrouter_api_key" class="ldr-form-control"+ placeholder="sk-or-..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key at openrouter.ai</span>+ </div>++ <!-- xAI API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="xai_api_key_container" style="display: none;">+ <label for="xai_api_key">xAI API Key</label>+ <input type="password" id="xai_api_key" name="xai_api_key" class="ldr-form-control"+ placeholder="xai-..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key at x.ai</span>+ </div>++ <!-- IONOS API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="ionos_api_key_container" style="display: none;">+ <label for="ionos_api_key">IONOS API Key</label>+ <input type="password" id="ionos_api_key" name="ionos_api_key" class="ldr-form-control"+ placeholder="..." autocomplete="new-password">+ <span class="ldr-input-help">Get your key from IONOS AI Model Hub</span>+ </div>++ <!-- OpenAI Endpoint API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="openai_endpoint_api_key_container" style="display: none;">+ <label for="openai_endpoint_api_key">Endpoint API Key</label>+ <input type="password" id="openai_endpoint_api_key" name="openai_endpoint_api_key" class="ldr-form-control"+ placeholder="API key (if required)" autocomplete="new-password">+ <span class="ldr-input-help">API key for your OpenAI-compatible endpoint</span>+ </div>++ <!-- Ollama API Key (hidden by default, optional for authenticated instances) -->+ <div class="ldr-form-group ldr-half" id="ollama_api_key_container" style="display: none;">+ <label for="ollama_api_key">Ollama API Key (Optional)</label>+ <input type="password" id="ollama_api_key" name="ollama_api_key" class="ldr-form-control"+ placeholder="Optional, for authenticated instances" autocomplete="new-password">+ <span class="ldr-input-help">Only needed for authenticated Ollama instances</span>+ </div></div><div class="ldr-form-row">diff --git a/tests/test_api_key_frontend_settings.py b/tests/test_api_key_frontend_settings.pynew file mode 100644index 0000000000..aff059c56e--- /dev/null+++ b/tests/test_api_key_frontend_settings.py@@ -0,0 +1,333 @@+"""Tests for API key frontend settings functionality.++These tests verify that the API key settings used by the research form frontend+are correctly configured and can be saved/retrieved via the settings API.+"""++# Provider to API key setting mapping (must match research.js)+API_KEY_SETTINGS = {+ "OPENAI": "llm.openai.api_key",+ "ANTHROPIC": "llm.anthropic.api_key",+ "GOOGLE": "llm.google.api_key",+ "OPENROUTER": "llm.openrouter.api_key",+ "XAI": "llm.xai.api_key",+ "IONOS": "llm.ionos.api_key",+ "OPENAI_ENDPOINT": "llm.openai_endpoint.api_key",+ "OLLAMA": "llm.ollama.api_key",+}++# Providers that require API keys (cloud providers)+CLOUD_PROVIDERS = [+ "OPENAI",+ "ANTHROPIC",+ "GOOGLE",+ "OPENROUTER",+ "XAI",+ "IONOS",+]++# Providers with optional API keys+OPTIONAL_API_KEY_PROVIDERS = ["OLLAMA", "OPENAI_ENDPOINT"]++# Local providers that don't need API keys+LOCAL_PROVIDERS_NO_KEY = ["LMSTUDIO", "LLAMACPP", "VLLM"]+++class TestAPIKeyProviderMapping:+ """Test that provider implementations define correct API key settings."""++ def test_openai_provider_api_key_setting(self):+ """Test OpenAI provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.openai import (+ OpenAIProvider,+ )++ assert OpenAIProvider.api_key_setting == "llm.openai.api_key"++ def test_anthropic_provider_api_key_setting(self):+ """Test Anthropic provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.anthropic import (+ AnthropicProvider,+ )++ assert AnthropicProvider.api_key_setting == "llm.anthropic.api_key"++ def test_google_provider_api_key_setting(self):+ """Test Google provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.google import (+ GoogleProvider,+ )++ assert GoogleProvider.api_key_setting == "llm.google.api_key"++ def test_openrouter_provider_api_key_setting(self):+ """Test OpenRouter provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.openrouter import (+ OpenRouterProvider,+ )++ assert OpenRouterProvider.api_key_setting == "llm.openrouter.api_key"++ def test_xai_provider_api_key_setting(self):+ """Test xAI provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.xai import (+ XAIProvider,+ )++ assert XAIProvider.api_key_setting == "llm.xai.api_key"++ def test_ionos_provider_api_key_setting(self):+ """Test IONOS provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.ionos import (+ IONOSProvider,+ )++ assert IONOSProvider.api_key_setting == "llm.ionos.api_key"++ def test_openai_endpoint_provider_api_key_setting(self):+ """Test OpenAI Endpoint provider uses correct API key setting."""+ from src.local_deep_research.llm.providers.implementations.custom_openai_endpoint import (+ CustomOpenAIEndpointProvider,+ )++ assert (+ CustomOpenAIEndpointProvider.api_key_setting+ == "llm.openai_endpoint.api_key"+ )++ def test_ollama_provider_api_key_setting(self):+ """Test Ollama provider uses correct API key setting (optional)."""+ from src.local_deep_research.llm.providers.implementations.ollama import (+ OllamaProvider,+ )++ assert OllamaProvider.api_key_setting == "llm.ollama.api_key"++ def test_lmstudio_provider_no_api_key(self):+ """Test LM Studio provider doesn't require API key."""+ from src.local_deep_research.llm.providers.implementations.lmstudio import (+ LMStudioProvider,+ )++ assert LMStudioProvider.api_key_setting is None+++class TestAPIKeySettingsInMemory:+ """Test API key settings with InMemorySettingsManager."""++ def test_set_and_get_api_key(self):+ """Test setting and retrieving API key values."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ manager = InMemorySettingsManager()++ # Set an API key+ test_key = "sk-test-12345"+ result = manager.set_setting("llm.openai.api_key", test_key)+ assert result is True++ # Retrieve the API key+ retrieved = manager.get_setting("llm.openai.api_key")+ assert retrieved == test_key++ def test_api_key_defaults_to_empty(self):+ """Test that API keys default to empty string."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ manager = InMemorySettingsManager()++ for provider, setting_key in API_KEY_SETTINGS.items():+ value = manager.get_setting(setting_key)+ # API keys should default to empty string or None+ assert value in ("", None), (+ f"API key '{setting_key}' should default to empty, got '{value}'"+ )++ def test_multiple_api_keys_independent(self):+ """Test that setting one API key doesn't affect others."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ manager = InMemorySettingsManager()++ # Set OpenAI key+ manager.set_setting("llm.openai.api_key", "openai-key-123")++ # Set Anthropic key+ manager.set_setting("llm.anthropic.api_key", "anthropic-key-456")++ # Verify both are independent+ assert manager.get_setting("llm.openai.api_key") == "openai-key-123"+ assert (+ manager.get_setting("llm.anthropic.api_key") == "anthropic-key-456"+ )+++class TestAPIKeySettingsSnapshot:+ """Test API key settings in settings snapshots."""++ def test_core_api_keys_in_snapshot(self):+ """Test that core API keys are included in settings snapshot."""+ from src.local_deep_research.api.settings_utils import (+ get_default_settings_snapshot,+ )++ snapshot = get_default_settings_snapshot()++ # Core API keys that should always be in snapshot+ core_api_keys = [+ "llm.openai.api_key",+ "llm.anthropic.api_key",+ "llm.openai_endpoint.api_key",+ ]++ for setting_key in core_api_keys:+ assert setting_key in snapshot, (+ f"API key '{setting_key}' not found in settings snapshot"+ )++ def test_create_snapshot_with_api_key(self):+ """Test creating snapshot with API key value."""+ from src.local_deep_research.api.settings_utils import (+ create_settings_snapshot,+ )++ snapshot = create_settings_snapshot(+ provider="openai", api_key="sk-test-snapshot-key"+ )++ # Check that the API key was set+ assert snapshot["llm.openai.api_key"]["value"] == "sk-test-snapshot-key"++ def test_snapshot_api_key_metadata(self):+ """Test that API key settings have proper metadata in snapshot."""+ from src.local_deep_research.api.settings_utils import (+ get_default_settings_snapshot,+ )++ snapshot = get_default_settings_snapshot()++ # Check metadata for core API keys that are in the snapshot+ core_api_keys = [+ "llm.openai.api_key",+ "llm.anthropic.api_key",+ "llm.openai_endpoint.api_key",+ ]++ for setting_key in core_api_keys:+ if setting_key in snapshot:+ setting = snapshot[setting_key]++ # Check required metadata fields+ assert "value" in setting, f"{setting_key} missing 'value'"+ assert "editable" in setting, (+ f"{setting_key} missing 'editable'"+ )++ # API keys should be editable+ assert setting["editable"] is True, (+ f"{setting_key} should be editable"+ )+++class TestAPIKeyEnvironmentOverride:+ """Test that API keys can be overridden by environment variables."""++ def test_openai_api_key_env_override(self, monkeypatch):+ """Test OpenAI API key can be set via environment variable."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ test_key = "sk-env-override-key"+ monkeypatch.setenv("LDR_LLM_OPENAI_API_KEY", test_key)++ manager = InMemorySettingsManager()+ retrieved = manager.get_setting("llm.openai.api_key")++ assert retrieved == test_key++ def test_anthropic_api_key_env_override(self, monkeypatch):+ """Test Anthropic API key can be set via environment variable."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ test_key = "sk-ant-env-override"+ monkeypatch.setenv("LDR_LLM_ANTHROPIC_API_KEY", test_key)++ manager = InMemorySettingsManager()+ retrieved = manager.get_setting("llm.anthropic.api_key")++ assert retrieved == test_key++ def test_openai_endpoint_api_key_env_override(self, monkeypatch):+ """Test OpenAI Endpoint API key can be set via environment variable."""+ from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ )++ test_key = "sk-endpoint-env-override"+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", test_key)++ manager = InMemorySettingsManager()+ retrieved = manager.get_setting("llm.openai_endpoint.api_key")++ assert retrieved == test_key+++class TestFrontendAPIKeyMapping:+ """Test that frontend API key mapping matches backend."""++ def test_frontend_mapping_matches_providers(self):+ """Verify the frontend mapping in this test matches actual providers."""+ from src.local_deep_research.llm.providers.implementations.openai import (+ OpenAIProvider,+ )+ from src.local_deep_research.llm.providers.implementations.anthropic import (+ AnthropicProvider,+ )+ from src.local_deep_research.llm.providers.implementations.google import (+ GoogleProvider,+ )+ from src.local_deep_research.llm.providers.implementations.openrouter import (+ OpenRouterProvider,+ )+ from src.local_deep_research.llm.providers.implementations.xai import (+ XAIProvider,+ )+ from src.local_deep_research.llm.providers.implementations.ionos import (+ IONOSProvider,+ )+ from src.local_deep_research.llm.providers.implementations.custom_openai_endpoint import (+ CustomOpenAIEndpointProvider,+ )+ from src.local_deep_research.llm.providers.implementations.ollama import (+ OllamaProvider,+ )++ # Map provider classes to their expected settings+ provider_classes = {+ "OPENAI": OpenAIProvider,+ "ANTHROPIC": AnthropicProvider,+ "GOOGLE": GoogleProvider,+ "OPENROUTER": OpenRouterProvider,+ "XAI": XAIProvider,+ "IONOS": IONOSProvider,+ "OPENAI_ENDPOINT": CustomOpenAIEndpointProvider,+ "OLLAMA": OllamaProvider,+ }++ for provider_name, expected_setting in API_KEY_SETTINGS.items():+ provider_class = provider_classes.get(provider_name)+ if provider_class:+ actual_setting = provider_class.api_key_setting+ assert actual_setting == expected_setting, (+ f"Frontend mapping for {provider_name} is '{expected_setting}' "+ f"but provider class uses '{actual_setting}'"+ )diff --git a/tests/ui_tests/test_api_key_inputs.js b/tests/ui_tests/test_api_key_inputs.jsnew file mode 100644index 0000000000..d01f2fd889--- /dev/null+++ b/tests/ui_tests/test_api_key_inputs.js@@ -0,0 +1,328 @@+/**+ * API Key Inputs Test+ * Tests the API key input fields on the research form for cloud providers+ * CI-compatible: Works in both local and CI environments+ */++const puppeteer = require('puppeteer');+const AuthHelper = require('./auth_helper');+const { getPuppeteerLaunchOptions } = require('./puppeteer_config');+const fs = require('fs');+const path = require('path');++// API key provider configurations+const API_KEY_PROVIDERS = [+ { provider: 'OPENAI', containerId: 'openai_api_key_container', inputId: 'openai_api_key', settingKey: 'llm.openai.api_key' },+ { provider: 'ANTHROPIC', containerId: 'anthropic_api_key_container', inputId: 'anthropic_api_key', settingKey: 'llm.anthropic.api_key' },+ { provider: 'GOOGLE', containerId: 'google_api_key_container', inputId: 'google_api_key', settingKey: 'llm.google.api_key' },+ { provider: 'OPENROUTER', containerId: 'openrouter_api_key_container', inputId: 'openrouter_api_key', settingKey: 'llm.openrouter.api_key' },+ { provider: 'XAI', containerId: 'xai_api_key_container', inputId: 'xai_api_key', settingKey: 'llm.xai.api_key' },+ { provider: 'IONOS', containerId: 'ionos_api_key_container', inputId: 'ionos_api_key', settingKey: 'llm.ionos.api_key' },+ { provider: 'OPENAI_ENDPOINT', containerId: 'openai_endpoint_api_key_container', inputId: 'openai_endpoint_api_key', settingKey: 'llm.openai_endpoint.api_key' },+ { provider: 'OLLAMA', containerId: 'ollama_api_key_container', inputId: 'ollama_api_key', settingKey: 'llm.ollama.api_key' },+];++// Local providers that should NOT show API key fields (except Ollama which has optional key)+const LOCAL_PROVIDERS_NO_KEY = ['LMSTUDIO', 'LLAMACPP', 'VLLM'];++async function testApiKeyInputs() {+ const isCI = !!process.env.CI;+ console.log(`\n🧪 Running API Key Inputs test (CI mode: ${isCI})\n`);++ // Create screenshots directory if it doesn't exist+ const screenshotsDir = path.join(__dirname, 'screenshots');+ if (!fs.existsSync(screenshotsDir)) {+ fs.mkdirSync(screenshotsDir, { recursive: true });+ }++ const browser = await puppeteer.launch(getPuppeteerLaunchOptions());+ const page = await browser.newPage();+ const baseUrl = 'http://127.0.0.1:5000';++ // Increase default timeout in CI+ if (isCI) {+ page.setDefaultTimeout(60000);+ page.setDefaultNavigationTimeout(60000);+ }++ let testsPassed = 0;+ let testsFailed = 0;++ function logTest(name, passed, message = '') {+ if (passed) {+ console.log(` ✅ ${name}${message ? ': ' + message : ''}`);+ testsPassed++;+ } else {+ console.log(` ❌ ${name}${message ? ': ' + message : ''}`);+ testsFailed++;+ }+ }++ try {+ // Authenticate+ console.log('📋 Setup: Authenticating...');+ const authHelper = new AuthHelper(page, baseUrl);+ const testUser = {+ username: `apikey_test_${Date.now()}`,+ password: 'TestPass123!'+ };++ try {+ await authHelper.register(testUser.username, testUser.password);+ console.log('✅ Test user registered and logged in\n');+ } catch (regError) {+ try {+ await authHelper.ensureAuthenticated();+ console.log('✅ Authenticated via existing mechanism\n');+ } catch (authError) {+ console.log('❌ Cannot authenticate - skipping API key tests');+ await browser.close();+ process.exit(0);+ }+ }++ // Navigate to research page+ console.log('📄 Navigating to research page...');+ await page.goto(`${baseUrl}/`, {+ waitUntil: 'networkidle2',+ timeout: 30000+ });++ const currentUrl = page.url();+ if (currentUrl.includes('/auth/login')) {+ throw new Error('Redirected to login - not authenticated');+ }+ console.log('✅ Research page loaded\n');++ // ===== TEST GROUP 1: API Key HTML Elements Exist =====+ console.log('📋 Test Group 1: API Key HTML Elements Exist');++ for (const config of API_KEY_PROVIDERS) {+ const containerExists = await page.$(`#${config.containerId}`) !== null;+ const inputExists = await page.$(`#${config.inputId}`) !== null;+ logTest(+ `${config.provider} API key elements`,+ containerExists && inputExists,+ containerExists && inputExists ? 'container and input found' : 'missing elements'+ );+ }++ // ===== TEST GROUP 2: API Key Inputs Are Password Type =====+ console.log('\n📋 Test Group 2: API Key Inputs Are Password Type');++ for (const config of API_KEY_PROVIDERS) {+ const inputType = await page.$eval(`#${config.inputId}`, el => el.type).catch(() => null);+ logTest(+ `${config.provider} input is password type`,+ inputType === 'password',+ inputType === 'password' ? 'correctly masked' : `got type: ${inputType}`+ );+ }++ // ===== TEST GROUP 3: All API Key Containers Initially Hidden =====+ console.log('\n📋 Test Group 3: API Key Containers Initially Hidden');++ for (const config of API_KEY_PROVIDERS) {+ const displayStyle = await page.$eval(`#${config.containerId}`, el => {+ return window.getComputedStyle(el).display;+ }).catch(() => 'error');++ // Initially all should be hidden (display: none)+ logTest(+ `${config.provider} container initially hidden`,+ displayStyle === 'none',+ displayStyle === 'none' ? 'correctly hidden' : `display: ${displayStyle}`+ );+ }++ // ===== TEST GROUP 4: Expand Advanced Options =====+ console.log('\n📋 Test Group 4: Expand Advanced Options');++ const advancedToggle = await page.$('.ldr-advanced-options-toggle');+ if (advancedToggle) {+ await advancedToggle.click();+ await page.waitForTimeout(500); // Wait for animation+ logTest('Advanced options expanded', true);+ } else {+ logTest('Advanced options toggle', false, 'toggle not found');+ }++ // ===== TEST GROUP 5: Provider Selection Shows Correct API Key Field =====+ console.log('\n📋 Test Group 5: Provider Selection Shows Correct API Key Field');++ const providerSelect = await page.$('#model_provider');+ if (!providerSelect) {+ logTest('Provider select', false, 'provider dropdown not found');+ } else {+ for (const config of API_KEY_PROVIDERS) {+ // Select the provider+ await page.select('#model_provider', config.provider);+ await page.waitForTimeout(300); // Wait for visibility toggle++ // Check that this provider's API key container is visible+ const isVisible = await page.$eval(`#${config.containerId}`, el => {+ return window.getComputedStyle(el).display !== 'none';+ }).catch(() => false);++ logTest(+ `${config.provider} shows API key field when selected`,+ isVisible,+ isVisible ? 'field visible' : 'field still hidden'+ );++ // Check that other API key containers are hidden+ for (const otherConfig of API_KEY_PROVIDERS) {+ if (otherConfig.provider !== config.provider) {+ const otherHidden = await page.$eval(`#${otherConfig.containerId}`, el => {+ return window.getComputedStyle(el).display === 'none';+ }).catch(() => true);++ if (!otherHidden) {+ logTest(+ `${otherConfig.provider} hidden when ${config.provider} selected`,+ false,+ 'should be hidden but is visible'+ );+ }+ }+ }+ }+ }++ // ===== TEST GROUP 6: Local Providers Don't Show API Key (except Ollama) =====+ console.log('\n📋 Test Group 6: Local Providers Without API Key Fields');++ for (const localProvider of LOCAL_PROVIDERS_NO_KEY) {+ // Try to select the provider (may not exist in dropdown)+ try {+ await page.select('#model_provider', localProvider);+ await page.waitForTimeout(300);++ // Check that no cloud API key containers are visible+ let anyVisible = false;+ for (const config of API_KEY_PROVIDERS) {+ // Skip Ollama since it has optional API key+ if (config.provider === 'OLLAMA') continue;++ const isVisible = await page.$eval(`#${config.containerId}`, el => {+ return window.getComputedStyle(el).display !== 'none';+ }).catch(() => false);++ if (isVisible) {+ anyVisible = true;+ break;+ }+ }++ logTest(+ `${localProvider} hides cloud API key fields`,+ !anyVisible,+ anyVisible ? 'some API key fields visible' : 'all hidden correctly'+ );+ } catch (e) {+ // Provider may not be in the dropdown, that's OK+ console.log(` ⏭️ ${localProvider} provider not in dropdown, skipping`);+ }+ }++ // ===== TEST GROUP 7: API Key Input Accepts Text =====+ console.log('\n📋 Test Group 7: API Key Input Accepts Text');++ // Select OpenAI provider+ await page.select('#model_provider', 'OPENAI');+ await page.waitForTimeout(300);++ const testApiKey = 'sk-test-key-12345';+ await page.type('#openai_api_key', testApiKey);++ const inputValue = await page.$eval('#openai_api_key', el => el.value);+ logTest(+ 'API key input accepts text',+ inputValue === testApiKey,+ inputValue === testApiKey ? 'value stored correctly' : `got: ${inputValue}`+ );++ // ===== TEST GROUP 8: API Key Persists After Provider Switch and Back =====+ console.log('\n📋 Test Group 8: API Key Value Persistence');++ // Switch to another provider+ await page.select('#model_provider', 'ANTHROPIC');+ await page.waitForTimeout(300);++ // Switch back to OpenAI+ await page.select('#model_provider', 'OPENAI');+ await page.waitForTimeout(300);++ const persistedValue = await page.$eval('#openai_api_key', el => el.value);+ logTest(+ 'API key persists after provider switch',+ persistedValue === testApiKey,+ persistedValue === testApiKey ? 'value preserved' : `got: ${persistedValue}`+ );++ // ===== TEST GROUP 9: API Key Save Handler Fires =====+ console.log('\n📋 Test Group 9: API Key Save Handler');++ // Listen for network requests to verify save+ let saveRequestFired = false;+ page.on('request', request => {+ if (request.url().includes('/settings/api/') && request.method() === 'PUT') {+ saveRequestFired = true;+ }+ });++ // Clear and type a new value, then blur to trigger save+ await page.$eval('#openai_api_key', el => el.value = '');+ await page.type('#openai_api_key', 'sk-new-test-key');+ await page.click('#model_provider'); // Click elsewhere to trigger blur/change+ await page.waitForTimeout(500);++ logTest(+ 'API key save request fires on change',+ saveRequestFired,+ saveRequestFired ? 'save request detected' : 'no save request detected'+ );++ // Take a screenshot of the final state+ await page.screenshot({+ path: path.join(screenshotsDir, 'api_key_inputs_final.png'),+ fullPage: true+ });++ } catch (error) {+ console.error(`\n❌ Test error: ${error.message}`);++ // Take error screenshot+ try {+ await page.screenshot({+ path: path.join(screenshotsDir, 'api_key_inputs_error.png'),+ fullPage: true+ });+ } catch (e) {+ // Ignore screenshot errors+ }++ testsFailed++;+ } finally {+ await browser.close();+ }++ // Summary+ console.log('\n' + '='.repeat(50));+ console.log(`📊 Test Summary: ${testsPassed} passed, ${testsFailed} failed`);+ console.log('='.repeat(50));++ if (testsFailed > 0) {+ console.log('\n❌ Some tests failed');+ process.exit(1);+ } else {+ console.log('\n✅ All tests passed!');+ process.exit(0);+ }+}++// Run the tests+testApiKeyInputs().catch(error => {+ console.error('Fatal error:', error);+ process.exit(1);+});