~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
refactor: extract coerce_setting_for_write() helper + fix api_update_setting type coercion (#2332)
LearningCircuit448eb6a1c970
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex aa1de62b9f..67893fc1dd 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -38,7 +38,6 @@ This dual-mode approach ensures the app works for all users while providingoptimal experience when JavaScript is available."""-import jsonimport platformimport subprocessfrom typing import Any, Optional, Tuple@@ -287,6 +286,35 @@ def validate_setting(return True, None+def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:+ """Coerce an incoming value to the correct type before writing to the DB.++ All web routes that save settings should use this function to ensure+ consistent type conversion.++ No JSON pre-parsing (``json.loads``) is needed here because:+ - ``get_typed_setting_value`` already parses JSON strings internally+ via ``_parse_json_value`` (for ``ui_element="json"``) and+ ``_parse_multiselect`` (for ``ui_element="multiselect"``).+ - For JSON API endpoints, ``request.get_json()`` already delivers+ dicts/lists as native Python objects.+ - For ``ui_element="text"``, pre-parsing would corrupt data: a JSON+ string like ``'{"k": "v"}'`` would become a dict, then ``str()``+ would produce ``"{'k': 'v'}"`` (Python repr, not valid JSON).+ """+ # check_env=False: we are persisting a user-supplied value, not reading+ # from an environment variable override. check_env=True (the default)+ # would silently replace the user's value with an env var, which is+ # incorrect on the write path.+ return get_typed_setting_value(+ key=key,+ value=value,+ ui_element=ui_element,+ default=None,+ check_env=False,+ )++@settings_bp.route("/", methods=["GET"])@login_requireddef settings_page():@@ -442,30 +470,22 @@ def save_all_settings():logger.warning(f"Corrected corrupted value for {key}: {value}")-- # Handle JSON string values (already parsed by JavaScript)- if isinstance(value, (dict, list)):- # Keep as is, already parsed- pass- # Handle string values that might be JSON- elif isinstance(value, str) and (- value.startswith("{") or value.startswith("[")- ):- try:- # Try to parse the string as JSON- value = json.loads(value)- except json.JSONDecodeError:- # If it fails to parse, keep as string- pass+ # NOTE: No JSON pre-parsing is done here. After the+ # corruption replacement above, values are Python dicts+ # (e.g. {}), hardcoded strings, or None — none are JSON+ # strings that need parsing. Type conversion below via+ # coerce_setting_for_write() handles everything; that+ # function delegates to get_typed_setting_value() which+ # already parses JSON internally for "json" and+ # "multiselect" ui_elements.if current_setting:- # Convert value to appropriate type using SettingsManager's logic- converted_value = get_typed_setting_value(+ # Coerce to correct Python type (e.g. str "5" → int 5+ # for number settings, str "true" → bool for checkboxes).+ converted_value = coerce_setting_for_write(key=current_setting.key,value=value,ui_element=current_setting.ui_element,- default=None,- check_env=False,)# Validate the setting@@ -746,14 +766,12 @@ def save_settings():# Get the setting from pre-fetched dictdb_setting = all_db_settings.get(key)- # Convert value to appropriate type using SettingsManager's logic+ # Coerce form POST string to correct Python type.if db_setting:- value = get_typed_setting_value(+ value = coerce_setting_for_write(key=db_setting.key,value=value,ui_element=db_setting.ui_element,- default=None,- check_env=False,)# Save the setting@@ -922,6 +940,16 @@ def api_update_setting(key):{"error": f"Setting {key} is not editable"}), 403+ # Coerce to correct Python type before saving.+ # Without this, values from JSON API requests are stored+ # as-is (e.g. string "5" instead of int 5 for number+ # settings, string "true" instead of bool for checkboxes).+ value = coerce_setting_for_write(+ key=db_setting.key,+ value=value,+ ui_element=db_setting.ui_element,+ )+# Update setting# Pass the db_session to avoid session lookup issuessuccess = set_setting(key, value, db_session=db_session)diff --git a/tests/web/routes/test_settings_routes.py b/tests/web/routes/test_settings_routes.pyindex ed8d5ce4a6..97cc087bfa 100644--- a/tests/web/routes/test_settings_routes.py+++ b/tests/web/routes/test_settings_routes.py@@ -917,3 +917,130 @@ class TestNonEditableSettingsProtection:f"{SETTINGS_PREFIX}/api/app.allow_registrations")assert get_response.status_code == 200+++class TestCoerceSettingForWrite:+ """Unit tests for coerce_setting_for_write() helper."""++ def test_passes_check_env_false(self):+ """Verify check_env=False is always passed to get_typed_setting_value."""+ with patch(+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value",+ return_value=42,+ ) as mock_gtsv:+ from local_deep_research.web.routes.settings_routes import (+ coerce_setting_for_write,+ )++ result = coerce_setting_for_write("some.key", "42", "number")++ mock_gtsv.assert_called_once_with(+ key="some.key",+ value="42",+ ui_element="number",+ default=None,+ check_env=False,+ )+ assert result == 42++ def test_passes_default_none(self):+ """Verify default=None is always passed to get_typed_setting_value."""+ with patch(+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value",+ return_value=True,+ ) as mock_gtsv:+ from local_deep_research.web.routes.settings_routes import (+ coerce_setting_for_write,+ )++ result = coerce_setting_for_write("app.flag", "true", "checkbox")++ assert mock_gtsv.call_args.kwargs["default"] is None+ assert mock_gtsv.call_args.kwargs["check_env"] is False+ assert result is True++ def test_returns_get_typed_setting_value_result(self):+ """Verify helper returns exactly what get_typed_setting_value returns."""+ sentinel = object()+ with patch(+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value",+ return_value=sentinel,+ ):+ from local_deep_research.web.routes.settings_routes import (+ coerce_setting_for_write,+ )++ result = coerce_setting_for_write("k", "v", "text")+ assert result is sentinel+++class TestApiUpdateSettingTypeConversion:+ """Integration tests: PUT /api/<key> round-trip type conversion."""++ def test_put_string_number_stored_as_int(self, authenticated_client):+ """PUT string "999" for number setting -> GET returns int 999."""+ # Find a number setting to test with+ get_resp = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search.iterations"+ )+ assert get_resp.status_code == 200+ original = get_resp.get_json()+ assert original["ui_element"] == "number"++ # PUT a string number+ put_resp = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search.iterations",+ json={"value": "999"},+ content_type="application/json",+ )+ assert put_resp.status_code == 200++ # GET should return int, not string+ verify_resp = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/search.iterations"+ )+ assert verify_resp.status_code == 200+ stored_value = verify_resp.get_json()["value"]+ assert stored_value == 999+ assert isinstance(stored_value, int)++ # Restore original value+ authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/search.iterations",+ json={"value": original["value"]},+ content_type="application/json",+ )++ def test_put_string_bool_stored_as_bool(self, authenticated_client):+ """PUT string "true" for checkbox setting -> GET returns bool True."""+ # Find a checkbox setting that exists in defaults+ get_resp = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/app.enable_notifications"+ )+ assert get_resp.status_code == 200+ original = get_resp.get_json()+ assert original["ui_element"] == "checkbox"++ # PUT string "true"+ put_resp = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/app.enable_notifications",+ json={"value": "true"},+ content_type="application/json",+ )+ assert put_resp.status_code == 200++ # GET should return bool, not string+ verify_resp = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/app.enable_notifications"+ )+ assert verify_resp.status_code == 200+ stored_value = verify_resp.get_json()["value"]+ assert stored_value is True+ assert isinstance(stored_value, bool)++ # Restore original value+ authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/app.enable_notifications",+ json={"value": original["value"]},+ content_type="application/json",+ )