π OpenHands: AI-Driven Development
APP-1197 Migrate settings endpoints to V1 API (/api/v1/settings) (#13759)
Tim O'Farrelle38eda4ac970
diff --git a/enterprise/server/routes/feedback.py b/enterprise/server/routes/feedback.pyindex f8ce971808..d7976e308a 100644--- a/enterprise/server/routes/feedback.py+++ b/enterprise/server/routes/feedback.py@@ -7,8 +7,8 @@ from storage.database import a_session_makerfrom storage.feedback import ConversationFeedbackfrom storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.events.event_store import EventStore-from openhands.server.dependencies import get_dependenciesfrom openhands.server.shared import file_storefrom openhands.server.user_auth import get_user_iddiff --git a/enterprise/server/routes/user.py b/enterprise/server/routes/user.pyindex 54fc93388a..610775f354 100644--- a/enterprise/server/routes/user.py+++ b/enterprise/server/routes/user.py@@ -7,6 +7,7 @@ from server.auth.token_manager import TokenManagerfrom storage.user_store import UserStorefrom utils.identity import resolve_display_name+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.integrations.provider import (PROVIDER_TOKEN_TYPE,ProviderHandler,@@ -23,7 +24,6 @@ from openhands.microagent.types import (MicroagentContentResponse,MicroagentResponse,)-from openhands.server.dependencies import get_dependenciesfrom openhands.server.routes.git import (get_repository_branches,get_repository_microagent_content,diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.pyindex 02fb97986d..5a54137ddf 100644--- a/openhands/app_server/app_conversation/app_conversation_router.py+++ b/openhands/app_server/app_conversation/app_conversation_router.py@@ -65,12 +65,12 @@ from openhands.app_server.services.httpx_client_injector import (from openhands.app_server.services.injector import InjectorStatefrom openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTRfrom openhands.app_server.user.user_context import UserContext+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.app_server.utils.docker_utils import (replace_localhost_hostname_for_docker,)from openhands.sdk.context.skills import KeywordTrigger, TaskTriggerfrom openhands.sdk.workspace.remote.async_remote_workspace import AsyncRemoteWorkspace-from openhands.server.dependencies import get_dependencies# Handle anext compatibility for Python < 3.10if sys.version_info >= (3, 10):diff --git a/openhands/app_server/event/event_router.py b/openhands/app_server/event/event_router.pyindex ae525d3e04..04f3151a24 100644--- a/openhands/app_server/event/event_router.py+++ b/openhands/app_server/event/event_router.py@@ -10,8 +10,8 @@ from openhands.agent_server.models import EventPage, EventSortOrderfrom openhands.app_server.config import depends_event_servicefrom openhands.app_server.event.event_service import EventServicefrom openhands.app_server.event_callback.event_callback_models import EventKind+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.sdk import Event-from openhands.server.dependencies import get_dependencies# We use the get_dependencies method here to signal to the OpenAPI docs that this endpoint# is protected. The actual protection is provided by SetAuthCookieMiddlewarediff --git a/openhands/app_server/pending_messages/pending_message_router.py b/openhands/app_server/pending_messages/pending_message_router.pyindex 7c78e2d6eb..78e9f7a6ce 100644--- a/openhands/app_server/pending_messages/pending_message_router.py+++ b/openhands/app_server/pending_messages/pending_message_router.py@@ -13,7 +13,7 @@ from openhands.app_server.pending_messages.pending_message_models import (from openhands.app_server.pending_messages.pending_message_service import (PendingMessageService,)-from openhands.server.dependencies import get_dependencies+from openhands.app_server.utils.dependencies import get_dependencieslogger = logging.getLogger(__name__)diff --git a/openhands/app_server/sandbox/sandbox_router.py b/openhands/app_server/sandbox/sandbox_router.pyindex 54dedecfbb..4d5df8b6a3 100644--- a/openhands/app_server/sandbox/sandbox_router.py+++ b/openhands/app_server/sandbox/sandbox_router.py@@ -19,7 +19,7 @@ from openhands.app_server.sandbox.sandbox_service import ()from openhands.app_server.sandbox.session_auth import validate_session_keyfrom openhands.app_server.user.auth_user_context import AuthUserContext-from openhands.server.dependencies import get_dependencies+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.server.user_auth.user_auth import (get_for_user as get_user_auth_for_user,)diff --git a/openhands/app_server/sandbox/sandbox_spec_router.py b/openhands/app_server/sandbox/sandbox_spec_router.pyindex 1a1f98bb96..baed63016f 100644--- a/openhands/app_server/sandbox/sandbox_spec_router.py+++ b/openhands/app_server/sandbox/sandbox_spec_router.py@@ -12,7 +12,7 @@ from openhands.app_server.sandbox.sandbox_spec_models import (from openhands.app_server.sandbox.sandbox_spec_service import (SandboxSpecService,)-from openhands.server.dependencies import get_dependencies+from openhands.app_server.utils.dependencies import get_dependencies# We use the get_dependencies method here to signal to the OpenAPI docs that this endpoint# is protected. The actual protection is provided by SetAuthCookieMiddlewarediff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.pynew file mode 100644index 0000000000..81dc2d7329--- /dev/null+++ b/openhands/app_server/settings/settings_router.py@@ -0,0 +1,268 @@+"""Settings router for OpenHands App Server.++This module provides the V1 API routes for user settings under /api/v1/settings.+"""++import os++from fastapi import APIRouter, Depends, status+from fastapi.responses import JSONResponse++from openhands.app_server.utils.dependencies import get_dependencies+from openhands.core.logger import openhands_logger as logger+from openhands.integrations.provider import (+ PROVIDER_TOKEN_TYPE,+ ProviderType,+)+from openhands.server.routes.secrets import invalidate_legacy_secrets_store+from openhands.server.settings import (+ GETSettingsModel,+)+from openhands.server.shared import config+from openhands.server.user_auth import (+ get_provider_tokens,+ get_secrets_store,+ get_user_settings,+ get_user_settings_store,+)+from openhands.storage.data_models.settings import Settings+from openhands.storage.secrets.secrets_store import SecretsStore+from openhands.storage.settings.settings_store import SettingsStore+from openhands.utils.llm import get_provider_api_base, is_openhands_model++LITE_LLM_API_URL = os.environ.get(+ 'LITE_LLM_API_URL', 'https://llm-proxy.app.all-hands.dev'+)++# Create router with /api/v1/settings prefix+router = APIRouter(+ prefix='/settings',+ tags=['Settings'],+ dependencies=get_dependencies(),+)+++async def store_llm_settings(+ settings: Settings, existing_settings: Settings+) -> Settings:+ """Merge LLM settings with existing settings."""+ if not existing_settings:+ return settings++ # Preserve unset LLM settings+ settings.llm_api_key = settings.llm_api_key or existing_settings.llm_api_key+ settings.llm_model = settings.llm_model or existing_settings.llm_model++ if settings.llm_base_url is None:+ # Not provided at all (e.g. MCP config save) - preserve existing or auto-detect+ if existing_settings.llm_base_url:+ settings.llm_base_url = existing_settings.llm_base_url+ elif is_openhands_model(settings.llm_model):+ # OpenHands models use the LiteLLM proxy+ settings.llm_base_url = LITE_LLM_API_URL+ elif settings.llm_model:+ # For non-openhands models, try to get URL from litellm+ try:+ api_base = get_provider_api_base(settings.llm_model)+ if api_base:+ settings.llm_base_url = api_base+ else:+ logger.debug(+ f'No api_base found in litellm for model: {settings.llm_model}'+ )+ except Exception as e:+ logger.error(+ f'Failed to get api_base from litellm for model {settings.llm_model}: {e}'+ )+ elif settings.llm_base_url == '':+ # Explicitly cleared by the user (basic view save or advanced view clear)+ settings.llm_base_url = None++ settings.search_api_key = (+ settings.search_api_key or existing_settings.search_api_key+ )+ return settings+++def convert_to_settings(settings_with_token_data: Settings) -> Settings:+ """Convert settings with token data to Settings model."""+ settings_data = settings_with_token_data.model_dump()++ # Filter out additional fields from `SettingsWithTokenData`+ filtered_settings_data = {+ key: value+ for key, value in settings_data.items()+ if key in Settings.model_fields # Ensures only `Settings` fields are included+ }++ # Convert the API keys to `SecretStr` instances+ filtered_settings_data['llm_api_key'] = settings_with_token_data.llm_api_key+ filtered_settings_data['search_api_key'] = settings_with_token_data.search_api_key++ # Create a new Settings instance+ settings = Settings(**filtered_settings_data)+ return settings+++# NOTE: We use response_model=None for endpoints that return JSONResponse directly.+# This is because FastAPI's response_model expects a Pydantic model, but we're returning+# a response object directly. We document the possible responses using the 'responses'+# parameter and maintain proper type annotations for mypy.+ '',+ response_model=GETSettingsModel,+ responses={+ 404: {'description': 'Settings not found', 'model': dict},+ 401: {'description': 'Invalid token', 'model': dict},+ },+)+async def load_settings(+ provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),+ settings_store: SettingsStore = Depends(get_user_settings_store),+ settings: Settings = Depends(get_user_settings),+ secrets_store: SecretsStore = Depends(get_secrets_store),+) -> GETSettingsModel | JSONResponse:+ """Load user settings.++ Retrieves the settings for the authenticated user, including LLM configuration,+ provider tokens, and other user preferences.++ Returns:+ GETSettingsModel: The user settings with token data++ Raises:+ 404: Settings not found+ 401: Invalid token+ """+ try:+ if not settings:+ return JSONResponse(+ status_code=status.HTTP_404_NOT_FOUND,+ content={'error': 'Settings not found'},+ )++ # On initial load, user secrets may not be populated with values migrated from settings store+ user_secrets = await invalidate_legacy_secrets_store(+ settings, settings_store, secrets_store+ )++ # If invalidation is successful, then the returned user secrets holds the most recent values+ git_providers = (+ user_secrets.provider_tokens if user_secrets else provider_tokens+ )++ provider_tokens_set: dict[ProviderType, str | None] = {}+ if git_providers:+ for provider_type, provider_token in git_providers.items():+ if provider_token.token or provider_token.user_id:+ provider_tokens_set[provider_type] = provider_token.host++ settings_with_token_data = GETSettingsModel(+ **settings.model_dump(exclude={'secrets_store'}),+ llm_api_key_set=settings.llm_api_key is not None+ and bool(settings.llm_api_key),+ search_api_key_set=settings.search_api_key is not None+ and bool(settings.search_api_key),+ provider_tokens_set=provider_tokens_set,+ )++ # If the base url matches the default for the provider, we don't send it+ # So that the frontend can display basic mode+ if is_openhands_model(settings.llm_model):+ if settings.llm_base_url == LITE_LLM_API_URL:+ settings_with_token_data.llm_base_url = None+ elif settings.llm_model and settings.llm_base_url == get_provider_api_base(+ settings.llm_model+ ):+ settings_with_token_data.llm_base_url = None++ settings_with_token_data.llm_api_key = None+ settings_with_token_data.search_api_key = None+ settings_with_token_data.sandbox_api_key = None+ return settings_with_token_data+ except Exception as e:+ logger.warning(f'Invalid token: {e}')+ # Get user_id from settings if available+ user_id = getattr(settings, 'user_id', 'unknown') if settings else 'unknown'+ logger.info(+ f'Returning 401 Unauthorized - Invalid token for user_id: {user_id}'+ )+ return JSONResponse(+ status_code=status.HTTP_401_UNAUTHORIZED,+ content={'error': 'Invalid token'},+ )+++ '',+ response_model=None,+ responses={+ 200: {'description': 'Settings stored successfully', 'model': dict},+ 500: {'description': 'Error storing settings', 'model': dict},+ },+)+async def store_settings(+ settings: Settings,+ settings_store: SettingsStore = Depends(get_user_settings_store),+) -> JSONResponse:+ """Store user settings.++ Saves the user settings including LLM configuration, provider tokens,+ and other user preferences.++ Returns:+ 200: Settings stored successfully+ 500: Error storing settings+ """+ # Check provider tokens are valid+ try:+ existing_settings = await settings_store.load()++ # Convert to Settings model and merge with existing settings+ if existing_settings:+ settings = await store_llm_settings(settings, existing_settings)++ # Keep existing analytics consent if not provided+ if settings.user_consents_to_analytics is None:+ settings.user_consents_to_analytics = (+ existing_settings.user_consents_to_analytics+ )++ # Keep existing disabled_skills if not provided+ if settings.disabled_skills is None:+ settings.disabled_skills = existing_settings.disabled_skills++ # Update sandbox config with new settings+ if settings.remote_runtime_resource_factor is not None:+ config.sandbox.remote_runtime_resource_factor = (+ settings.remote_runtime_resource_factor+ )++ # Update git configuration with new settings+ git_config_updated = False+ if settings.git_user_name is not None:+ config.git_user_name = settings.git_user_name+ git_config_updated = True+ if settings.git_user_email is not None:+ config.git_user_email = settings.git_user_email+ git_config_updated = True++ # Note: Git configuration will be applied when new sessions are initialized+ # Existing sessions will continue with their current git configuration+ if git_config_updated:+ logger.info(+ f'Updated global git configuration: name={config.git_user_name}, email={config.git_user_email}'+ )++ settings = convert_to_settings(settings)+ await settings_store.store(settings)+ return JSONResponse(+ status_code=status.HTTP_200_OK,+ content={'message': 'Settings stored'},+ )+ except Exception as e:+ logger.warning(f'Something went wrong storing settings: {e}')+ return JSONResponse(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ content={'error': 'Something went wrong storing settings'},+ )diff --git a/openhands/app_server/user/skills_router.py b/openhands/app_server/user/skills_router.pyindex 398deaa9a9..2e192e7a29 100644--- a/openhands/app_server/user/skills_router.py+++ b/openhands/app_server/user/skills_router.py@@ -5,9 +5,9 @@ import yamlfrom fastapi import APIRouter, Queryfrom pydantic import BaseModel+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.memory.memory import GLOBAL_MICROAGENTS_DIR, USER_MICROAGENTS_DIR-from openhands.server.dependencies import get_dependenciesrouter = APIRouter(prefix='/skills', tags=['Skills'], dependencies=get_dependencies())diff --git a/openhands/app_server/user/user_router.py b/openhands/app_server/user/user_router.pyindex 3cee936bde..4d4353eb2b 100644--- a/openhands/app_server/user/user_router.py+++ b/openhands/app_server/user/user_router.py@@ -9,7 +9,7 @@ from openhands.app_server.config import depends_user_contextfrom openhands.app_server.sandbox.session_auth import validate_session_keyfrom openhands.app_server.user.user_context import UserContextfrom openhands.app_server.user.user_models import UserInfo-from openhands.server.dependencies import get_dependencies+from openhands.app_server.utils.dependencies import get_dependencies_logger = logging.getLogger(__name__)diff --git a/openhands/server/dependencies.py b/openhands/app_server/utils/dependencies.pysimilarity index 61%rename from openhands/server/dependencies.pyrename to openhands/app_server/utils/dependencies.pyindex c4141c7c0b..8ca238a94d 100644--- a/openhands/server/dependencies.py+++ b/openhands/app_server/utils/dependencies.py@@ -1,11 +1,3 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.import osfrom fastapi import Depends, HTTPException, statusdiff --git a/openhands/app_server/v1_router.py b/openhands/app_server/v1_router.pyindex 4c18ef6932..4cda2d9214 100644--- a/openhands/app_server/v1_router.py+++ b/openhands/app_server/v1_router.py@@ -9,6 +9,9 @@ from openhands.app_server.pending_messages.pending_message_router import (router as pending_message_router,)from openhands.app_server.sandbox import sandbox_router, sandbox_spec_router+from openhands.app_server.settings.settings_router import (+ router as settings_router,+)from openhands.app_server.user import skills_router, user_routerfrom openhands.app_server.web_client import web_client_router@@ -19,6 +22,7 @@ router.include_router(app_conversation_router.router)router.include_router(pending_message_router)router.include_router(sandbox_router.router)router.include_router(sandbox_spec_router.router)+router.include_router(settings_router)router.include_router(user_router.router)router.include_router(skills_router.router)router.include_router(webhook_router.router)diff --git a/openhands/server/routes/conversation.py b/openhands/server/routes/conversation.pyindex a44a3ca221..5dd3970efe 100644--- a/openhands/server/routes/conversation.py+++ b/openhands/server/routes/conversation.py@@ -19,6 +19,7 @@ from openhands.app_server.app_conversation.app_conversation_models import (AppConversationInfo,)from openhands.app_server.config import depends_app_conversation_info_service+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.events.action.message import MessageActionfrom openhands.events.event_filter import EventFilter@@ -27,7 +28,6 @@ from openhands.events.serialization.event import event_to_dictfrom openhands.memory.memory import Memoryfrom openhands.microagent.types import InputMetadatafrom openhands.runtime.base import Runtime-from openhands.server.dependencies import get_dependenciesfrom openhands.server.session.conversation import ServerConversationfrom openhands.server.shared import conversation_manager, file_storefrom openhands.server.user_auth import get_user_iddiff --git a/openhands/server/routes/feedback.py b/openhands/server/routes/feedback.pyindex 30a243eb56..468ff03c61 100644--- a/openhands/server/routes/feedback.py+++ b/openhands/server/routes/feedback.py@@ -9,12 +9,12 @@from fastapi import APIRouter, Depends, Request, statusfrom fastapi.responses import JSONResponse+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.events.async_event_store_wrapper import AsyncEventStoreWrapperfrom openhands.events.event_filter import EventFilterfrom openhands.events.serialization import event_to_dictfrom openhands.server.data_models.feedback import FeedbackDataModel, store_feedback-from openhands.server.dependencies import get_dependenciesfrom openhands.server.session.conversation import ServerConversationfrom openhands.server.utils import get_conversationfrom openhands.utils.async_utils import call_sync_from_asyncdiff --git a/openhands/server/routes/files.py b/openhands/server/routes/files.pyindex 403a65cfca..bbe17ef769 100644--- a/openhands/server/routes/files.py+++ b/openhands/server/routes/files.py@@ -14,10 +14,10 @@ from fastapi import APIRouter, Depends, HTTPException, UploadFile, statusfrom fastapi.responses import FileResponse, JSONResponsefrom starlette.background import BackgroundTask+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.exceptions import AgentRuntimeUnavailableErrorfrom openhands.core.logger import openhands_logger as loggerfrom openhands.runtime.base import Runtime-from openhands.server.dependencies import get_dependenciesfrom openhands.server.file_config import FILES_TO_IGNOREfrom openhands.server.files import POSTUploadFilesModelfrom openhands.server.session.conversation import ServerConversationdiff --git a/openhands/server/routes/git.py b/openhands/server/routes/git.pyindex 411d90ba79..bce73549fb 100644--- a/openhands/server/routes/git.py+++ b/openhands/server/routes/git.py@@ -13,6 +13,7 @@ from fastapi import APIRouter, Depends, Query, statusfrom fastapi.responses import JSONResponsefrom pydantic import SecretStr+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.integrations.provider import (PROVIDER_TOKEN_TYPE,@@ -32,7 +33,6 @@ from openhands.microagent.types import (MicroagentContentResponse,MicroagentResponse,)-from openhands.server.dependencies import get_dependenciesfrom openhands.server.shared import server_configfrom openhands.server.user_auth import (get_access_token,diff --git a/openhands/server/routes/manage_conversations.py b/openhands/server/routes/manage_conversations.pyindex 19b87884aa..7f464845b2 100644--- a/openhands/server/routes/manage_conversations.py+++ b/openhands/server/routes/manage_conversations.py@@ -47,6 +47,7 @@ from openhands.app_server.services.db_session_injector import set_db_session_keefrom openhands.app_server.services.httpx_client_injector import (set_httpx_client_keep_open,)+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.config.llm_config import LLMConfigfrom openhands.core.config.mcp_config import MCPConfigfrom openhands.core.logger import openhands_logger as logger@@ -77,7 +78,6 @@ from openhands.server.data_models.conversation_info import ConversationInfofrom openhands.server.data_models.conversation_info_result_set import (ConversationInfoResultSet,)-from openhands.server.dependencies import get_dependenciesfrom openhands.server.services.conversation_service import (create_new_conversation,setup_init_conversation_settings,diff --git a/openhands/server/routes/public.py b/openhands/server/routes/public.pyindex 0b3fa72150..49dab2f36c 100644--- a/openhands/server/routes/public.py+++ b/openhands/server/routes/public.py@@ -11,9 +11,9 @@ from typing import Anyfrom fastapi import APIRouter, Depends, Request+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.controller.agent import Agentfrom openhands.security.options import SecurityAnalyzers-from openhands.server.dependencies import get_dependenciesfrom openhands.server.shared import config, server_configfrom openhands.utils.llm import ModelsResponse, get_supported_llm_modelsdiff --git a/openhands/server/routes/secrets.py b/openhands/server/routes/secrets.pyindex 033471cc6b..936ff9cf31 100644--- a/openhands/server/routes/secrets.py+++ b/openhands/server/routes/secrets.py@@ -9,11 +9,11 @@from fastapi import APIRouter, Depends, statusfrom fastapi.responses import JSONResponse+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.integrations.provider import PROVIDER_TOKEN_TYPE, CustomSecretfrom openhands.integrations.service_types import ProviderTypefrom openhands.integrations.utils import validate_provider_token-from openhands.server.dependencies import get_dependenciesfrom openhands.server.settings import (CustomSecretModel,CustomSecretWithoutValueModel,diff --git a/openhands/server/routes/security.py b/openhands/server/routes/security.pyindex 5ff1bfdd70..ea9eb8a565 100644--- a/openhands/server/routes/security.py+++ b/openhands/server/routes/security.py@@ -15,7 +15,7 @@ from fastapi import (status,)-from openhands.server.dependencies import get_dependencies+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.server.session.conversation import ServerConversationfrom openhands.server.utils import get_conversationdiff --git a/openhands/server/routes/settings.py b/openhands/server/routes/settings.pyindex 9562df1cc1..f53d978269 100644--- a/openhands/server/routes/settings.py+++ b/openhands/server/routes/settings.py@@ -8,20 +8,22 @@# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.import os-from fastapi import APIRouter, Depends, status+from fastapi import APIRouter, Dependsfrom fastapi.responses import JSONResponse-from openhands.core.logger import openhands_logger as logger+from openhands.app_server.settings.settings_router import (+ load_settings as v1_load_settings,+)+from openhands.app_server.settings.settings_router import (+ store_settings as v1_store_settings,+)+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.integrations.provider import (PROVIDER_TOKEN_TYPE,- ProviderType,)-from openhands.server.dependencies import get_dependencies-from openhands.server.routes.secrets import invalidate_legacy_secrets_storefrom openhands.server.settings import (GETSettingsModel,)-from openhands.server.shared import configfrom openhands.server.user_auth import (get_provider_tokens,get_secrets_store,@@ -31,7 +33,6 @@ from openhands.server.user_auth import (from openhands.storage.data_models.settings import Settingsfrom openhands.storage.secrets.secrets_store import SecretsStorefrom openhands.storage.settings.settings_store import SettingsStore-from openhands.utils.llm import get_provider_api_base, is_openhands_modelLITE_LLM_API_URL = os.environ.get('LITE_LLM_API_URL', 'https://llm-proxy.app.all-hands.dev'@@ -47,6 +48,7 @@ app = APIRouter(prefix='/api', dependencies=get_dependencies())404: {'description': 'Settings not found', 'model': dict},401: {'description': 'Invalid token', 'model': dict},},+ deprecated=True,)async def load_settings(provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),@@ -54,110 +56,11 @@ async def load_settings(settings: Settings = Depends(get_user_settings),secrets_store: SecretsStore = Depends(get_secrets_store),) -> GETSettingsModel | JSONResponse:- try:- if not settings:- return JSONResponse(- status_code=status.HTTP_404_NOT_FOUND,- content={'error': 'Settings not found'},- )-- # On initial load, user secrets may not be populated with values migrated from settings store- user_secrets = await invalidate_legacy_secrets_store(- settings, settings_store, secrets_store- )-- # If invalidation is successful, then the returned user secrets holds the most recent values- git_providers = (- user_secrets.provider_tokens if user_secrets else provider_tokens- )-- provider_tokens_set: dict[ProviderType, str | None] = {}- if git_providers:- for provider_type, provider_token in git_providers.items():- if provider_token.token or provider_token.user_id:- provider_tokens_set[provider_type] = provider_token.host-- settings_with_token_data = GETSettingsModel(- **settings.model_dump(exclude={'secrets_store'}),- llm_api_key_set=settings.llm_api_key is not None- and bool(settings.llm_api_key),- search_api_key_set=settings.search_api_key is not None- and bool(settings.search_api_key),- provider_tokens_set=provider_tokens_set,- )+ return await v1_load_settings(+ provider_tokens, settings_store, settings, secrets_store+ )- # If the base url matches the default for the provider, we don't send it- # So that the frontend can display basic mode- if is_openhands_model(settings.llm_model):- if settings.llm_base_url == LITE_LLM_API_URL:- settings_with_token_data.llm_base_url = None- elif settings.llm_model and settings.llm_base_url == get_provider_api_base(- settings.llm_model- ):- settings_with_token_data.llm_base_url = None- settings_with_token_data.llm_api_key = None- settings_with_token_data.search_api_key = None- settings_with_token_data.sandbox_api_key = None- return settings_with_token_data- except Exception as e:- logger.warning(f'Invalid token: {e}')- # Get user_id from settings if available- user_id = getattr(settings, 'user_id', 'unknown') if settings else 'unknown'- logger.info(- f'Returning 401 Unauthorized - Invalid token for user_id: {user_id}'- )- return JSONResponse(- status_code=status.HTTP_401_UNAUTHORIZED,- content={'error': 'Invalid token'},- )---async def store_llm_settings(- settings: Settings, existing_settings: Settings-) -> Settings:- # Convert to Settings model and merge with existing settings- if existing_settings:- # Keep existing LLM settings if not provided- if settings.llm_api_key is None:- settings.llm_api_key = existing_settings.llm_api_key- if settings.llm_model is None:- settings.llm_model = existing_settings.llm_model- if settings.llm_base_url is None:- # Not provided at all (e.g. MCP config save) - preserve existing or auto-detect- if existing_settings.llm_base_url:- settings.llm_base_url = existing_settings.llm_base_url- elif is_openhands_model(settings.llm_model):- # OpenHands models use the LiteLLM proxy- settings.llm_base_url = LITE_LLM_API_URL- elif settings.llm_model:- # For non-openhands models, try to get URL from litellm- try:- api_base = get_provider_api_base(settings.llm_model)- if api_base:- settings.llm_base_url = api_base- else:- logger.debug(- f'No api_base found in litellm for model: {settings.llm_model}'- )- except Exception as e:- logger.error(- f'Failed to get api_base from litellm for model {settings.llm_model}: {e}'- )- elif settings.llm_base_url == '':- # Explicitly cleared by the user (basic view save or advanced view clear)- settings.llm_base_url = None- # Keep search API key if missing or empty- if not settings.search_api_key:- settings.search_api_key = existing_settings.search_api_key-- return settings---# NOTE: We use response_model=None for endpoints that return JSONResponse directly.-# This is because FastAPI's response_model expects a Pydantic model, but we're returning-# a response object directly. We document the possible responses using the 'responses'-# parameter and maintain proper type annotations for mypy.@app.post('/settings',response_model=None,@@ -165,79 +68,10 @@ async def store_llm_settings(200: {'description': 'Settings stored successfully', 'model': dict},500: {'description': 'Error storing settings', 'model': dict},},+ deprecated=True,)async def store_settings(settings: Settings,settings_store: SettingsStore = Depends(get_user_settings_store),) -> JSONResponse:- # Check provider tokens are valid- try:- existing_settings = await settings_store.load()-- # Convert to Settings model and merge with existing settings- if existing_settings:- settings = await store_llm_settings(settings, existing_settings)-- # Keep existing analytics consent if not provided- if settings.user_consents_to_analytics is None:- settings.user_consents_to_analytics = (- existing_settings.user_consents_to_analytics- )-- # Keep existing disabled_skills if not provided- if settings.disabled_skills is None:- settings.disabled_skills = existing_settings.disabled_skills-- # Update sandbox config with new settings- if settings.remote_runtime_resource_factor is not None:- config.sandbox.remote_runtime_resource_factor = (- settings.remote_runtime_resource_factor- )-- # Update git configuration with new settings- git_config_updated = False- if settings.git_user_name is not None:- config.git_user_name = settings.git_user_name- git_config_updated = True- if settings.git_user_email is not None:- config.git_user_email = settings.git_user_email- git_config_updated = True-- # Note: Git configuration will be applied when new sessions are initialized- # Existing sessions will continue with their current git configuration- if git_config_updated:- logger.info(- f'Updated global git configuration: name={config.git_user_name}, email={config.git_user_email}'- )-- settings = convert_to_settings(settings)- await settings_store.store(settings)- return JSONResponse(- status_code=status.HTTP_200_OK,- content={'message': 'Settings stored'},- )- except Exception as e:- logger.warning(f'Something went wrong storing settings: {e}')- return JSONResponse(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- content={'error': 'Something went wrong storing settings'},- )---def convert_to_settings(settings_with_token_data: Settings) -> Settings:- settings_data = settings_with_token_data.model_dump()-- # Filter out additional fields from `SettingsWithTokenData`- filtered_settings_data = {- key: value- for key, value in settings_data.items()- if key in Settings.model_fields # Ensures only `Settings` fields are included- }-- # Convert the API keys to `SecretStr` instances- filtered_settings_data['llm_api_key'] = settings_with_token_data.llm_api_key- filtered_settings_data['search_api_key'] = settings_with_token_data.search_api_key-- # Create a new Settings instance- settings = Settings(**filtered_settings_data)- return settings+ return await v1_store_settings(settings, settings_store)diff --git a/openhands/server/routes/trajectory.py b/openhands/server/routes/trajectory.pyindex 047a9e5dfd..6fd8685fdc 100644--- a/openhands/server/routes/trajectory.py+++ b/openhands/server/routes/trajectory.py@@ -9,12 +9,12 @@from fastapi import APIRouter, Depends, statusfrom fastapi.responses import JSONResponse+from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.core.logger import openhands_logger as loggerfrom openhands.events.async_event_store_wrapper import AsyncEventStoreWrapperfrom openhands.events.event_filter import EventFilterfrom openhands.events.event_store import EventStorefrom openhands.events.serialization import event_to_trajectory-from openhands.server.dependencies import get_dependenciesfrom openhands.server.shared import file_storefrom openhands.server.utils import get_conversation_metadatafrom openhands.storage.data_models.conversation_metadata import ConversationMetadatadiff --git a/tests/unit/app_server/test_event_router.py b/tests/unit/app_server/test_event_router.pyindex a3b94dd0ff..e5abfeb25c 100644--- a/tests/unit/app_server/test_event_router.py+++ b/tests/unit/app_server/test_event_router.py@@ -12,7 +12,7 @@ from fastapi import FastAPI, HTTPException, statusfrom fastapi.testclient import TestClientfrom openhands.app_server.event.event_router import batch_get_events, router-from openhands.server.dependencies import check_session_api_key+from openhands.app_server.utils.dependencies import check_session_api_keydef _make_mock_event_service(search_return=None, batch_get_return=None):diff --git a/tests/unit/app_server/test_sandbox_secrets_router.py b/tests/unit/app_server/test_sandbox_secrets_router.pyindex 5976098bc1..5d9543f34e 100644--- a/tests/unit/app_server/test_sandbox_secrets_router.py+++ b/tests/unit/app_server/test_sandbox_secrets_router.py@@ -413,7 +413,7 @@ def _build_integration_test_app(router as sandbox_router,)from openhands.app_server.user.user_router import router as user_router- from openhands.server.dependencies import check_session_api_key+ from openhands.app_server.utils.dependencies import check_session_api_keyapp = FastAPI()diff --git a/tests/unit/server/routes/test_settings_api.py b/tests/unit/app_server/test_settings_api.pysimilarity index 86%rename from tests/unit/server/routes/test_settings_api.pyrename to tests/unit/app_server/test_settings_api.pyindex f812f04467..7c9b91ac19 100644--- a/tests/unit/server/routes/test_settings_api.py+++ b/tests/unit/app_server/test_settings_api.py@@ -65,7 +65,7 @@ def test_client():# Create a test clientwith (patch.dict(os.environ, {'SESSION_API_KEY': ''}, clear=False),- patch('openhands.server.dependencies._SESSION_API_KEY', None),+ patch('openhands.app_server.utils.dependencies._SESSION_API_KEY', None),patch('openhands.server.user_auth.user_auth.UserAuth.get_instance',return_value=MockUserAuth(),@@ -96,13 +96,13 @@ async def test_settings_api_endpoints(test_client):}# Make the POST request to store settings- response = test_client.post('/api/settings', json=settings_data)+ response = test_client.post('/api/v1/settings', json=settings_data)# We're not checking the exact response, just that it doesn't errorassert response.status_code == 200# Test the GET settings endpoint- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200# Test updating with partial settings@@ -112,7 +112,7 @@ async def test_settings_api_endpoints(test_client):'llm_api_key': None, # Should preserve existing value}- response = test_client.post('/api/settings', json=partial_settings)+ response = test_client.post('/api/v1/settings', json=partial_settings)assert response.status_code == 200# Test the unset-provider-tokens endpoint@@ -128,11 +128,11 @@ async def test_search_api_key_preservation(test_client):'search_api_key': 'initial-secret-key','llm_model': 'gpt-4',}- response = test_client.post('/api/settings', json=initial_settings)+ response = test_client.post('/api/v1/settings', json=initial_settings)assert response.status_code == 200# Verify key is set- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200assert response.json()['search_api_key_set'] is True@@ -142,11 +142,11 @@ async def test_search_api_key_preservation(test_client):'search_api_key': '', # The frontend sends an empty string here'llm_model': 'claude-3-opus',}- response = test_client.post('/api/settings', json=update_settings)+ response = test_client.post('/api/v1/settings', json=update_settings)assert response.status_code == 200# 3. Verify the key was NOT wiped out (The Critical Check)- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200# If the bug was present, this would be Falseassert response.json()['search_api_key_set'] is True@@ -163,11 +163,11 @@ async def test_disabled_skills_persistence(test_client):'llm_api_key': 'test-key','disabled_skills': ['skill_a', 'skill_b'],}- response = test_client.post('/api/settings', json=settings_data)+ response = test_client.post('/api/v1/settings', json=settings_data)assert response.status_code == 200# 2. Retrieve and verify- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200data = response.json()assert data['disabled_skills'] == ['skill_a', 'skill_b']@@ -176,10 +176,10 @@ async def test_disabled_skills_persistence(test_client):update_settings = {'disabled_skills': ['skill_c'],}- response = test_client.post('/api/settings', json=update_settings)+ response = test_client.post('/api/v1/settings', json=update_settings)assert response.status_code == 200- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200data = response.json()assert data['disabled_skills'] == ['skill_c']@@ -188,10 +188,10 @@ async def test_disabled_skills_persistence(test_client):update_settings = {'disabled_skills': [],}- response = test_client.post('/api/settings', json=update_settings)+ response = test_client.post('/api/v1/settings', json=update_settings)assert response.status_code == 200- response = test_client.get('/api/settings')+ response = test_client.get('/api/v1/settings')assert response.status_code == 200data = response.json()assert data['disabled_skills'] == []diff --git a/tests/unit/server/routes/test_get_repository_microagents.py b/tests/unit/server/routes/test_get_repository_microagents.pyindex b68931d983..98084f2fef 100644--- a/tests/unit/server/routes/test_get_repository_microagents.py+++ b/tests/unit/server/routes/test_get_repository_microagents.py@@ -9,13 +9,13 @@ from fastapi.testclient import TestClientfrom httpcore import Requestfrom pydantic import SecretStr+from openhands.app_server.utils.dependencies import check_session_api_keyfrom openhands.integrations.provider import ProviderToken, ProviderTypefrom openhands.integrations.service_types import (AuthenticationError,Repository,)from openhands.microagent.types import MicroagentContentResponse-from openhands.server.dependencies import check_session_api_keyfrom openhands.server.routes.git import app as git_appfrom openhands.server.user_auth import (get_access_token,diff --git a/tests/unit/server/routes/test_secrets_api.py b/tests/unit/server/routes/test_secrets_api.pyindex 59c978b05b..b8f8688f6d 100644--- a/tests/unit/server/routes/test_secrets_api.py+++ b/tests/unit/server/routes/test_secrets_api.py@@ -31,7 +31,7 @@ def test_client():# Mock SESSION_API_KEY to None to disable authentication in testswith patch.dict(os.environ, {'SESSION_API_KEY': ''}, clear=False):# Clear the SESSION_API_KEY to disable auth dependency- with patch('openhands.server.dependencies._SESSION_API_KEY', None):+ with patch('openhands.app_server.utils.dependencies._SESSION_API_KEY', None):yield TestClient(app)diff --git a/tests/unit/server/routes/test_settings_store_functions.py b/tests/unit/server/routes/test_settings_store_functions.pyindex 48bc79a280..dedee12faf 100644--- a/tests/unit/server/routes/test_settings_store_functions.py+++ b/tests/unit/server/routes/test_settings_store_functions.py@@ -6,6 +6,7 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom pydantic import SecretStr+from openhands.app_server.settings.settings_router import store_llm_settingsfrom openhands.core.config.mcp_config import MCPConfig, MCPStdioServerConfigfrom openhands.integrations.provider import ProviderTokenfrom openhands.integrations.service_types import ProviderType@@ -15,7 +16,6 @@ from openhands.server.routes.secrets import (from openhands.server.routes.secrets import (check_provider_tokens,)-from openhands.server.routes.settings import store_llm_settingsfrom openhands.server.settings import POSTProviderModelfrom openhands.storage import get_file_storefrom openhands.storage.data_models.secrets import Secrets@@ -39,7 +39,7 @@ def test_client():with (patch.dict(os.environ, {'SESSION_API_KEY': ''}, clear=False),- patch('openhands.server.dependencies._SESSION_API_KEY', None),+ patch('openhands.app_server.utils.dependencies._SESSION_API_KEY', None),patch('openhands.server.routes.secrets.check_provider_tokens',AsyncMock(return_value=''),@@ -339,7 +339,7 @@ async def test_store_llm_settings_litellm_error_logged():)# The function should not raise even if litellm fails- with patch('openhands.server.routes.settings.logger') as mock_logger:+ with patch('openhands.app_server.settings.settings_router.logger') as mock_logger:result = await store_llm_settings(settings, existing_settings)# llm_base_url should remain None since litellm couldn't find the modeldiff --git a/tests/unit/server/routes/test_skills_api.py b/tests/unit/server/routes/test_skills_api.pyindex 06ac195bcc..e6467d801f 100644--- a/tests/unit/server/routes/test_skills_api.py+++ b/tests/unit/server/routes/test_skills_api.py@@ -65,7 +65,7 @@ class MockUserAuth(UserAuth):def test_client():with (patch.dict(os.environ, {'SESSION_API_KEY': ''}, clear=False),- patch('openhands.server.dependencies._SESSION_API_KEY', None),+ patch('openhands.app_server.utils.dependencies._SESSION_API_KEY', None),patch('openhands.server.user_auth.user_auth.UserAuth.get_instance',return_value=MockUserAuth(),diff --git a/tests/unit/storage/data_models/test_settings.py b/tests/unit/storage/data_models/test_settings.pyindex 621baf1b2c..868eeeda77 100644--- a/tests/unit/storage/data_models/test_settings.py+++ b/tests/unit/storage/data_models/test_settings.py@@ -3,11 +3,11 @@ from unittest.mock import patchfrom pydantic import SecretStr+from openhands.app_server.settings.settings_router import convert_to_settingsfrom openhands.core.config.llm_config import LLMConfigfrom openhands.core.config.openhands_config import OpenHandsConfigfrom openhands.core.config.sandbox_config import SandboxConfigfrom openhands.core.config.security_config import SecurityConfig-from openhands.server.routes.settings import convert_to_settingsfrom openhands.storage.data_models.settings import Settings