π OpenHands: AI-Driven Development
fix: restore org settings payload contract (#14051)
Graham Neubiga8926068ff61
diff --git a/AGENTS.md b/AGENTS.mdindex 1905a96ffd..199aaf7a6a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -144,6 +144,8 @@ Frontend:- Query hooks should follow the pattern use[Resource] (e.g., `useConversationSkills`)- Mutation hooks should follow the pattern use[Action] (e.g., `useDeleteConversation`)- Architecture rule: UI components β TanStack Query hooks β Data Access Layer (`frontend/src/api`) β API endpoints+ - For SaaS organization management screens, prefer deriving the selected organization from `useOrganizations()` plus the selected org ID store instead of adding a dedicated single-org fetch when only list-level fields (for example `name`) are needed.+VSCode Extension:- Located in the `openhands/integrations/vscode` directorydiff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.pyindex 18e3c2a830..ed9c77bde8 100644--- a/enterprise/server/routes/org_models.py+++ b/enterprise/server/routes/org_models.py@@ -213,10 +213,9 @@ class OrgPage(BaseModel):class OrgUpdate(BaseModel):"""Request model for updating an organization.- ``agent_settings`` and ``conversation_settings`` match the wire format- the frontend already uses for ``OrgLLMSettingsUpdate``; they're- applied to the org row as partial/diff patches via ``deep_merge`` in- ``OrgStore.update_org``.+ ``agent_settings_diff`` and ``conversation_settings_diff`` are sparse diffs+ that are deep-merged into the org row and then validated as full settings+ before persistence."""name: Annotated[@@ -236,12 +235,144 @@ class OrgUpdate(BaseModel):enable_solvability_analysis: bool | None = Nonev1_enabled: bool | None = Nonesearch_api_key: str | None = None- agent_settings: dict[str, Any] | None = None- conversation_settings: dict[str, Any] | None = None+ llm_api_key: str | None = None+ agent_settings_diff: dict[str, Any] | None = None+ conversation_settings_diff: dict[str, Any] | None = None++ @model_validator(mode='after')+ def _normalize_settings_diffs(self) -> 'OrgUpdate':+ """Normalize sparse settings diffs before merge/persistence."""+ self._normalize_agent_settings_diff()+ self._cleanup_empty_diff('agent_settings_diff', nested_key='llm')+ self._cleanup_empty_diff('conversation_settings_diff')+ return self++ def _normalize_agent_settings_diff(self) -> None:+ """Normalize nested LLM settings inside ``agent_settings_diff``."""+ llm_diff = self._get_agent_llm_diff()+ if llm_diff is None:+ return++ self._lift_and_mask_llm_api_key(llm_diff)+ self._resolve_agent_llm_base_url(llm_diff)++ def _get_agent_llm_diff(self) -> dict[str, Any] | None:+ """Return the nested ``llm`` diff when present and dictionary-shaped."""+ if self.agent_settings_diff is None:+ return None+ llm_diff = self.agent_settings_diff.get('llm')+ return llm_diff if isinstance(llm_diff, dict) else None++ def _lift_and_mask_llm_api_key(self, llm_diff: dict[str, Any]) -> None:+ """Lift nested api keys to ``llm_api_key`` and mask the JSON diff."""+ if 'api_key' not in llm_diff:+ return++ nested_key = llm_diff.pop('api_key')+ if (+ self.llm_api_key is None+ and nested_key is not None+ and nested_key != MASKED_API_KEY+ ):+ self.llm_api_key = nested_key+ if nested_key is not None:+ llm_diff['api_key'] = MASKED_API_KEY++ def _resolve_agent_llm_base_url(self, llm_diff: dict[str, Any]) -> None:+ """Fill provider-default base URLs for sparse LLM diffs when needed."""+ resolved_base_url = resolve_llm_base_url(+ model=llm_diff.get('model'),+ base_url=llm_diff.get('base_url'),+ managed_proxy_url=LITE_LLM_API_URL,+ )+ if resolved_base_url is not None:+ llm_diff['base_url'] = resolved_base_url++ def _cleanup_empty_diff(+ self,+ field_name: str,+ nested_key: str | None = None,+ ) -> None:+ """Drop empty nested diffs and collapse empty diff payloads to ``None``."""+ settings_diff = getattr(self, field_name)+ if not isinstance(settings_diff, dict):+ if not settings_diff:+ setattr(self, field_name, None)+ return++ if nested_key is not None and not settings_diff.get(nested_key):+ settings_diff.pop(nested_key, None)+ if not settings_diff:+ setattr(self, field_name, None)++ def updated_fields(self) -> set[str]:+ """Return the public field names explicitly present on the update."""+ return {+ field+ for field in type(self).model_fields+ if getattr(self, field) is not None+ }++ def has_updates(self) -> bool:+ """Check if any public update field is set (not None)."""+ return bool(self.updated_fields())++ def touches_org_defaults(self) -> bool:+ """Whether this update touches shared organization defaults."""+ return bool(+ self.updated_fields()+ & {+ 'agent_settings_diff',+ 'conversation_settings_diff',+ 'search_api_key',+ 'llm_api_key',+ }+ )+ def restricted_fields(self) -> set[str]:+ """Return fields that require elevated org settings permissions."""+ return self.updated_fields() & {+ 'agent_settings_diff',+ 'conversation_settings_diff',+ 'search_api_key',+ 'sandbox_api_key',+ 'llm_api_key',+ }++ def model_update_dict(self) -> dict[str, Any]:+ """Return JSON-serializable scalar fields for persistence."""+ return self.model_dump(+ mode='json',+ exclude_none=True,+ exclude={'agent_settings_diff', 'conversation_settings_diff'},+ )++ def apply_to_org(self, org: Org) -> None:+ """Apply non-settings fields directly to the organization model."""+ for key, value in self.model_update_dict().items():+ if hasattr(org, key):+ setattr(org, key, value)-class OrgLLMSettingsResponse(BaseModel):- """Response model for organization default LLM settings."""+ def get_member_updates(self) -> 'OrgMemberSettingsUpdate | None':+ """Get shared updates that need to be propagated to org members.++ An empty ``llm_api_key`` means the org-wide custom key is being cleared+ (e.g. owner switching to a managed/OpenHands provider). It must not+ land in member rows β ``OrgMember.llm_api_key``'s setter has no+ ``if raw else None`` guard because the column is ``nullable=False``,+ so an empty string would become an encrypted empty blob rather than a+ cleared value. Coerce ``""`` to ``None`` so member rows are untouched.+ """+ member_settings = OrgMemberSettingsUpdate(+ agent_settings_diff=self.agent_settings_diff,+ conversation_settings_diff=self.conversation_settings_diff,+ llm_api_key=self.llm_api_key or None,+ )+ return member_settings if member_settings.has_updates() else None+++class OrgDefaultsSettingsResponse(BaseModel):+ """Response model for organization default settings."""agent_settings: AgentSettings = Field(default_factory=AgentSettings)conversation_settings: ConversationSettings = Field(@@ -263,7 +394,7 @@ class OrgLLMSettingsResponse(BaseModel):return '****' + raw[-4:]@classmethod- def from_org(cls, org: Org) -> 'OrgLLMSettingsResponse':+ def from_org(cls, org: Org) -> 'OrgDefaultsSettingsResponse':"""Create response from Org entity.Denormalizes the SDK's ``litellm_proxy/`` prefix back to@@ -316,8 +447,8 @@ class OrgLLMSettingsResponse(BaseModel):llm.api_key = None-class OrgMemberLLMSettings(BaseModel):- """Shared LLM settings that may be propagated to organization members.+class OrgMemberSettingsUpdate(BaseModel):+ """Shared settings updates that may be propagated to organization members.``llm_api_key`` is typed as ``SecretStr`` so the raw value never ends upin logs or ``model_dump(mode='json')`` output by accident β the@@ -325,7 +456,7 @@ class OrgMemberLLMSettings(BaseModel):directly and unwraps via ``get_secret_value()``.``has_custom_llm_api_key`` propagates through- ``update_all_members_llm_settings_async`` so an org-defaults save can+ ``update_all_members_settings_async`` so an org-defaults save canreset every member's "I have a personal BYOR key" flag in one pass βmanaged-mode switches rely on this to stop load-time fallthrough fromreturning stale custom markers.@@ -343,129 +474,6 @@ class OrgMemberLLMSettings(BaseModel):)-class OrgLLMSettingsUpdate(BaseModel):- """Request model for updating organization LLM settings.-- ``agent_settings`` and ``conversation_settings`` are applied to the org- as partial/diff patches via ``deep_merge`` and are also propagated to- each member's stored diff so stale member overrides don't mask the new- org defaults.- """-- agent_settings: dict[str, Any] | None = None- conversation_settings: dict[str, Any] | None = None- search_api_key: str | None = None- llm_api_key: str | None = None-- @model_validator(mode='after')- def _normalize_agent_settings(self) -> 'OrgLLMSettingsUpdate':- """Normalize ``agent_settings`` so post-save stored state stays- consistent between the org row, every member row, and the encrypted- ``_llm_api_key`` column.-- Two jobs:-- * **Lift ``llm.api_key`` and mask it in the JSON.** The frontend- posts the raw key nested inside ``agent_settings``. Leaving it- nested would push a raw secret into the ``org.agent_settings``- JSON column while ``org._llm_api_key`` (the encrypted column read- by ``_get_effective_llm_api_key`` at load time) stays stale. We- move the raw value up to ``self.llm_api_key`` (for the encrypted- column) and leave a universal ``MASKED_API_KEY`` marker in the- JSON. That marker then propagates through ``deep_merge`` into- ``org.agent_settings.llm.api_key`` and through- ``get_member_updates`` into every member's- ``agent_settings_diff.llm.api_key`` β matching the convention- ``SaasSettingsStore.store`` already follows via- ``model_dump(mode='json')``.-- * **Fill ``llm.base_url`` for OpenHands / managed models.** The- basic-view payload sends ``base_url: null`` when the user picks- the OpenHands provider. ``deep_merge`` treats ``None`` as "delete- this key," which would leave ``org.agent_settings.llm`` without a- ``base_url`` (and the frontend then can't tell which provider is- configured β see the empty basic-view dropdowns). Substitute the- managed LiteLLM proxy URL so the stored state is complete and- self-describing.- """- if self.agent_settings is None:- return self- llm = self.agent_settings.get('llm')- if not isinstance(llm, dict):- return self-- if 'api_key' in llm:- nested_key = llm.pop('api_key')- # Don't re-lift the masked placeholder β the frontend echoes- # it back when the user saves without editing the api_key- # field. Treating it as a raw key would encrypt ``**********``- # into the column and nuke the real key.- if (- self.llm_api_key is None- and nested_key is not None- and nested_key != MASKED_API_KEY- ):- self.llm_api_key = nested_key- if nested_key is not None:- # Keep the JSON in sync with the encrypted column β both- # ``org.agent_settings.llm.api_key`` and every member's- # ``agent_settings_diff.llm.api_key`` will carry this marker- # after ``deep_merge`` / propagation. An empty string still- # gets the marker: the rotation step that runs after the- # store update will write a freshly generated managed key- # into the column, so "masked" in the JSON still reflects- # reality by end of transaction.- llm['api_key'] = MASKED_API_KEY-- # Auto-fill ``base_url`` when the wire payload sends ``null``- # (basic-view pattern). ``resolve_llm_base_url`` is shared with- # ``_post_merge_llm_fixups`` in the personal-settings router so- # both save paths agree on "this provider uses this base URL."- resolved_base_url = resolve_llm_base_url(- model=llm.get('model'),- base_url=llm.get('base_url'),- managed_proxy_url=LITE_LLM_API_URL,- )- if resolved_base_url is not None:- llm['base_url'] = resolved_base_url-- if not llm:- self.agent_settings.pop('llm', None)- if not self.agent_settings:- self.agent_settings = None- return self-- def has_updates(self) -> bool:- """Check if any field is set (not None)."""- return any(- getattr(self, field) is not None for field in type(self).model_fields- )-- def apply_to_org(self, org: Org) -> None:- """Apply non-None settings to the organization model."""- if self.search_api_key is not None:- org.search_api_key = self.search_api_key or None- if self.llm_api_key is not None:- org.llm_api_key = self.llm_api_key or None-- def get_member_updates(self) -> OrgMemberLLMSettings | None:- """Get updates that need to be propagated to org members.-- An empty ``llm_api_key`` means the orgβwide custom key is being cleared- (e.g. owner switching to a managed/OpenHands provider). It must not- land in member rows β ``OrgMember.llm_api_key``'s setter has no- ``if raw else None`` guard because the column is ``nullable=False``,- so an empty string would become an encrypted empty blob rather than a- cleared value. Coerce ``""`` to ``None`` so member rows are untouched.- """- member_settings = OrgMemberLLMSettings(- agent_settings_diff=self.agent_settings,- conversation_settings_diff=self.conversation_settings,- llm_api_key=self.llm_api_key or None,- )- return member_settings if member_settings.has_updates() else None--class OrgMemberResponse(BaseModel):"""Response model for a single organization member."""diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.pyindex a9a7c4d05e..84dd533e31 100644--- a/enterprise/server/routes/orgs.py+++ b/enterprise/server/routes/orgs.py@@ -24,8 +24,7 @@ from server.routes.org_models import (OrgAuthorizationError,OrgCreate,OrgDatabaseError,- OrgLLMSettingsResponse,- OrgLLMSettingsUpdate,+ OrgDefaultsSettingsResponse,OrgMemberFinancialPage,OrgMemberNotFoundError,OrgMemberPage,@@ -43,15 +42,12 @@ from server.services.org_app_settings_service import (OrgAppSettingsService,OrgAppSettingsServiceInjector,)-from server.services.org_llm_settings_service import (- OrgLLMSettingsService,- OrgLLMSettingsServiceInjector,-)from server.services.org_member_financial_service import OrgMemberFinancialServicefrom server.services.org_member_service import OrgMemberServicefrom sqlalchemy.exc import IntegrityErrorfrom storage.org_git_claim_store import OrgGitClaimStorefrom storage.org_service import OrgService+from storage.org_store import OrgStorefrom storage.user_store import UserStorefrom openhands.core.logger import openhands_logger as logger@@ -60,9 +56,6 @@ from openhands.server.user_auth import get_user_id# Initialize API routerorg_router = APIRouter(prefix='/api/organizations', tags=['Orgs'])-# Create injector instance and dependency for LLM settings-_org_llm_settings_injector = OrgLLMSettingsServiceInjector()-org_llm_settings_service_dependency = Depends(_org_llm_settings_injector.depends)# Create injector instance and dependency at module level_org_app_settings_injector = OrgAppSettingsServiceInjector()org_app_settings_service_dependency = Depends(_org_app_settings_injector.depends)@@ -228,102 +221,156 @@ async def create_org()-@org_router.get(- '/llm',- response_model=OrgLLMSettingsResponse,- dependencies=[Depends(require_permission(Permission.VIEW_LLM_SETTINGS))],-)-async def get_org_llm_settings(- service: OrgLLMSettingsService = org_llm_settings_service_dependency,-) -> OrgLLMSettingsResponse:- """Get LLM settings for the user's current organization.-- This endpoint retrieves the LLM configuration settings for the- authenticated user's current organization. All organization members- can view these settings.-- Args:- service: OrgLLMSettingsService (injected by dependency)+@org_router.get('/{org_id}/settings', response_model=OrgDefaultsSettingsResponse)+async def get_org_defaults_settings(+ org_id: UUID,+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),+) -> OrgDefaultsSettingsResponse:+ """Get org-default settings for a specific organization."""+ try:+ org = await OrgService.get_org_by_id(org_id=org_id, user_id=user_id)+ return OrgDefaultsSettingsResponse.from_org(org)+ except OrgNotFoundError as e:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=str(e),+ )+ except Exception as e:+ logger.exception(+ 'Error getting organization defaults settings',+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},+ )+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to retrieve organization defaults settings',+ )- Returns:- OrgLLMSettingsResponse: The organization's LLM settings- Raises:- HTTPException: 401 if not authenticated- HTTPException: 403 if not a member of any organization- HTTPException: 404 if current organization not found- HTTPException: 500 if retrieval fails- """+@org_router.patch('/{org_id}/settings', response_model=OrgDefaultsSettingsResponse)+async def update_org_defaults_settings(+ org_id: UUID,+ settings: OrgUpdate,+ user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),+) -> OrgDefaultsSettingsResponse:+ """Update org-default settings for a specific organization."""try:- return await service.get_org_llm_settings()+ allowed_fields = {+ 'agent_settings_diff',+ 'conversation_settings_diff',+ 'search_api_key',+ 'llm_api_key',+ }+ invalid_fields = settings.updated_fields() - allowed_fields+ if invalid_fields:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=(+ 'Only organization default settings fields are supported on '+ '/api/organizations/{org_id}/settings'+ ),+ )++ updated_org = await OrgService.update_org_with_permissions(+ org_id=org_id,+ update_data=settings,+ user_id=user_id,+ )+ return OrgDefaultsSettingsResponse.from_org(updated_org)except OrgNotFoundError as e:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=str(e),)+ except OrgDatabaseError as e:+ logger.error(+ 'Database error updating organization defaults settings',+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},+ )+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to update organization defaults settings',+ )+ except HTTPException:+ raiseexcept Exception as e:logger.exception(- 'Error getting organization LLM settings',- extra={'error': str(e)},+ 'Error updating organization defaults settings',+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail='Failed to retrieve LLM settings',+ detail='Failed to update organization defaults settings',)-@org_router.post(+@org_router.get('/llm',- response_model=OrgLLMSettingsResponse,- dependencies=[Depends(require_permission(Permission.EDIT_LLM_SETTINGS))],+ response_model=OrgDefaultsSettingsResponse,+ deprecated=True,)-async def update_org_llm_settings(- settings: OrgLLMSettingsUpdate,- service: OrgLLMSettingsService = org_llm_settings_service_dependency,-) -> OrgLLMSettingsResponse:- """Update LLM settings for the user's current organization.-- This endpoint updates the LLM configuration settings for the- authenticated user's current organization. Only admins and owners- can update these settings.-- Args:- settings: The LLM settings to update (only non-None fields are updated)- service: OrgLLMSettingsService (injected by dependency)-- Returns:- OrgLLMSettingsResponse: The updated organization's LLM settings-- Raises:- HTTPException: 401 if not authenticated- HTTPException: 403 if user lacks EDIT_LLM_SETTINGS permission- HTTPException: 404 if current organization not found- HTTPException: 500 if update fails- """+async def get_legacy_org_defaults_settings(+ user_id: str = Depends(require_permission(Permission.VIEW_LLM_SETTINGS)),+) -> OrgDefaultsSettingsResponse:+ """Get org-default settings through the deprecated ``/llm`` wrapper."""try:- return await service.update_org_llm_settings(settings)+ org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)+ if not org:+ raise OrgNotFoundError('current')+ return await get_org_defaults_settings(org_id=org.id, user_id=user_id)except OrgNotFoundError as e:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=str(e),)- except OrgDatabaseError as e:- logger.error(- 'Database error updating LLM settings',- extra={'error': str(e)},+ except HTTPException:+ raise+ except Exception as e:+ logger.exception(+ 'Error getting legacy organization defaults settings',+ extra={'user_id': user_id, 'error': str(e)},)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail='Failed to update LLM settings',+ detail='Failed to retrieve organization defaults settings',+ )+++@org_router.post(+ '/llm',+ response_model=OrgDefaultsSettingsResponse,+ deprecated=True,+)+async def update_legacy_org_defaults_settings(+ settings: OrgUpdate,+ user_id: str = Depends(require_permission(Permission.EDIT_LLM_SETTINGS)),+) -> OrgDefaultsSettingsResponse:+ """Update org-default settings through the deprecated ``/llm`` wrapper."""+ try:+ org = await OrgStore.get_current_org_from_keycloak_user_id(user_id)+ if not org:+ raise OrgNotFoundError('current')+ if not settings.has_updates():+ return OrgDefaultsSettingsResponse.from_org(org)+ return await update_org_defaults_settings(+ org_id=org.id,+ settings=settings,+ user_id=user_id,+ )+ except OrgNotFoundError as e:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=str(e),)+ except HTTPException:+ raiseexcept Exception as e:logger.exception(- 'Error updating organization LLM settings',- extra={'error': str(e)},+ 'Error updating legacy organization defaults settings',+ extra={'user_id': user_id, 'error': str(e)},)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail='Failed to update LLM settings',+ detail='Failed to update organization defaults settings',)@@ -417,31 +464,17 @@ async def update_org_app_settings()-@org_router.get('/{org_id}', response_model=OrgResponse, status_code=status.HTTP_200_OK)+@org_router.get(+ '/{org_id}',+ response_model=OrgResponse,+ status_code=status.HTTP_200_OK,+ deprecated=True,+)async def get_org(org_id: UUID,user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),) -> OrgResponse:- """Get organization details by ID.-- This endpoint retrieves details for a specific organization. Access requires- the VIEW_ORG_SETTINGS permission, which is granted to all organization members- (member, admin, and owner roles).-- Args:- org_id: Organization ID (UUID)- user_id: Authenticated user ID (injected by require_permission dependency)-- Returns:- OrgResponse: The organization details-- Raises:- HTTPException: 401 if user is not authenticated- HTTPException: 403 if user lacks VIEW_ORG_SETTINGS permission- HTTPException: 404 if organization not found- HTTPException: 422 if org_id is not a valid UUID (handled by FastAPI)- HTTPException: 500 if retrieval fails- """+ """Get organization details by ID through the deprecated detail route."""logger.info('Retrieving organization details',extra={@@ -451,15 +484,11 @@ async def get_org()try:- # Use service layer to get organization with membership validationorg = await OrgService.get_org_by_id(org_id=org_id,user_id=user_id,)-- # Retrieve credits from LiteLLMcredits = await OrgService.get_org_credits(user_id, org.id)-return OrgResponse.from_org(org, credits=credits, user_id=user_id)except OrgNotFoundError as e:raise HTTPException(diff --git a/enterprise/server/services/org_llm_settings_service.py b/enterprise/server/services/org_llm_settings_service.pydeleted file mode 100644index d06dee5ad7..0000000000--- a/enterprise/server/services/org_llm_settings_service.py+++ /dev/null@@ -1,277 +0,0 @@-"""Service class for managing organization LLM settings.--Separates business logic from route handlers.-Uses dependency injection for db_session and user_context.-"""--from __future__ import annotations--import uuid-from dataclasses import dataclass-from typing import AsyncGenerator--from fastapi import Request-from pydantic import SecretStr-from server.constants import LITE_LLM_API_URL-from server.routes.org_models import (- OrgLLMSettingsResponse,- OrgLLMSettingsUpdate,- OrgMemberLLMSettings,- OrgNotFoundError,-)-from sqlalchemy import select-from storage.lite_llm_manager import LiteLlmManager, get_openhands_cloud_key_alias-from storage.org import Org-from storage.org_llm_settings_store import OrgLLMSettingsStore-from storage.org_member import OrgMember-from storage.org_member_store import OrgMemberStore--from openhands.app_server.services.injector import Injector, InjectorState-from openhands.app_server.user.user_context import UserContext-from openhands.core.logger import openhands_logger as logger-from openhands.utils.llm import is_openhands_model---@dataclass-class OrgLLMSettingsService:- """Service for org LLM settings with injected dependencies."""-- store: OrgLLMSettingsStore- user_context: UserContext-- async def get_org_llm_settings(self) -> OrgLLMSettingsResponse:- """Get LLM settings for user's current organization.-- User ID is obtained from the injected user_context.-- Returns:- OrgLLMSettingsResponse: The organization's LLM settings-- Raises:- ValueError: If user is not authenticated- OrgNotFoundError: If current organization not found- """- user_id = await self.user_context.get_user_id()- if not user_id:- raise ValueError('User is not authenticated')-- logger.info(- 'Getting organization LLM settings',- extra={'user_id': user_id},- )-- org = await self.store.get_current_org_by_user_id(user_id)-- if not org:- raise OrgNotFoundError('No current organization')-- return OrgLLMSettingsResponse.from_org(org)-- async def update_org_llm_settings(- self,- update_data: OrgLLMSettingsUpdate,- ) -> OrgLLMSettingsResponse:- """Update LLM settings for user's current organization.-- Only updates fields that are explicitly provided in update_data.- User ID is obtained from the injected user_context.- Session auto-commits at request end via DbSessionInjector.-- Args:- update_data: The update data from the request-- Returns:- OrgLLMSettingsResponse: The updated organization's LLM settings-- Raises:- ValueError: If user is not authenticated- OrgNotFoundError: If current organization not found- """- user_id = await self.user_context.get_user_id()- if not user_id:- raise ValueError('User is not authenticated')-- logger.info(- 'Updating organization LLM settings',- extra={'user_id': user_id},- )-- # Check if any fields are provided- if not update_data.has_updates():- # No fields to update, just return current settings- return await self.get_org_llm_settings()-- # Get user's current org first- org = await self.store.get_current_org_by_user_id(user_id)- if not org:- raise OrgNotFoundError('No current organization')-- # Update the org LLM settings- updated_org = await self.store.update_org_llm_settings(- org_id=org.id,- update_data=update_data,- )-- if not updated_org:- raise OrgNotFoundError(str(org.id))-- # Build the member-propagation payload from the update diff, then- # let the managed-key rotation merge in a freshly generated /- # reused managed key (OpenHands / LiteLLM proxy case). A single- # ``update_all_members_llm_settings_async`` call at the end writes- # the ``agent_settings_diff``, ``llm_api_key``, and a- # ``has_custom_llm_api_key=False`` reset to every member row in one- # pass. The flag reset is load-bearing: org-defaults saves are an- # org-wide "use the org default" signal, so any lingering- # "I have a personal BYOR key" marker on a member row would make- # ``_get_effective_llm_api_key`` return the wrong key at read time.- member_updates = update_data.get_member_updates()-- effective_managed_key = await self._maybe_rotate_managed_llm_key_for_user(- updated_org=updated_org,- user_id=user_id,- )- if effective_managed_key is not None:- if member_updates is None:- member_updates = OrgMemberLLMSettings()- member_updates.llm_api_key = SecretStr(effective_managed_key)-- if member_updates is not None:- member_updates.has_custom_llm_api_key = False- await OrgMemberStore.update_all_members_llm_settings_async(- self.store.db_session,- org.id,- member_updates,- )- logger.info(- 'Propagated org LLM settings to members',- extra={'user_id': user_id, 'org_id': str(org.id)},- )-- logger.info(- 'Organization LLM settings updated successfully',- extra={'user_id': user_id, 'org_id': str(org.id)},- )-- return OrgLLMSettingsResponse.from_org(updated_org)-- async def _maybe_rotate_managed_llm_key_for_user(- self,- updated_org: Org,- user_id: str,- ) -> str | None:- """Return the managed LLM key every member row should carry, or- ``None`` if the org isn't in managed mode.-- When the updated org defaults target a managed LLM (OpenHands- provider or the LiteLLM proxy base URL), this reuses the acting- user's (any admin or owner with ``EDIT_LLM_SETTINGS``) current- managed key if ``verify_existing_key`` confirms it's still valid,- otherwise generates a fresh one. The returned key is what every- member's ``_llm_api_key`` column should hold β the caller bundles- it into the single ``update_all_members_llm_settings_async`` call- alongside the ``agent_settings_diff`` and a- ``has_custom_llm_api_key=False`` reset so one DB pass covers all- three. Detection matches ``SaasSettingsStore.store`` so the two- save paths agree on when managed mode is in play; propagation- semantics differ because org-defaults saves are intentionally an- org-wide operation.- """- llm = (updated_org.agent_settings or {}).get('llm') or {}- llm_model = llm.get('model')- llm_base_url = llm.get('base_url')- normalized_llm_base_url = llm_base_url.rstrip('/') if llm_base_url else None- normalized_managed_base_url = LITE_LLM_API_URL.rstrip('/')- openhands_type = is_openhands_model(llm_model)- uses_managed_llm_key = (- normalized_llm_base_url == normalized_managed_base_url- or (normalized_llm_base_url is None and openhands_type)- )- if not uses_managed_llm_key:- return None-- result = await self.store.db_session.execute(- select(OrgMember).where(- OrgMember.org_id == updated_org.id,- OrgMember.user_id == uuid.UUID(user_id),- )- )- acting_member = result.scalars().first()- if acting_member is None:- # Shouldn't happen β the caller already resolved the user's- # current org via ``get_current_org_by_user_id`` before calling- # us, so the ``OrgMember`` row must exist. If it's missing- # anyway, the org-wide managed-key propagation skips the- # ``llm_api_key`` write (``effective_managed_key`` returns- # ``None``) and members keep whatever was in their columns.- # Log loudly so this data-consistency issue surfaces instead of- # silently leaving stale keys on member rows.- logger.error(- 'Acting member row not found during managed LLM key '- 'rotation; skipping managed-key propagation. Members may '- 'retain stale keys until they save personal settings.',- extra={'user_id': user_id, 'org_id': str(updated_org.id)},- )- return None-- existing_key = acting_member.llm_api_key- existing_key_raw = existing_key.get_secret_value() if existing_key else None- if existing_key_raw and await LiteLlmManager.verify_existing_key(- existing_key_raw,- user_id,- str(updated_org.id),- openhands_type=openhands_type,- ):- # Reuse the acting user's still-valid managed key β no need to- # burn a LiteLLM key rotation on a no-op save.- effective_key = existing_key_raw- rotated = False- else:- if openhands_type:- effective_key = await LiteLlmManager.generate_key(- user_id,- str(updated_org.id),- None,- {'type': 'openhands'},- )- else:- key_alias = get_openhands_cloud_key_alias(user_id, str(updated_org.id))- await LiteLlmManager.delete_key_by_alias(key_alias=key_alias)- effective_key = await LiteLlmManager.generate_key(- user_id,- str(updated_org.id),- key_alias,- None,- )- rotated = True-- # The caller merges ``effective_key`` into ``member_updates`` and- # issues a single ``update_all_members_llm_settings_async`` call- # that writes the key column AND resets ``has_custom_llm_api_key``- # on every member β including this acting row β so we don't touch- # the row directly here.-- if rotated:- logger.info(- 'Generated managed LLM key for acting user on org-defaults save',- extra={'user_id': user_id, 'org_id': str(updated_org.id)},- )-- return effective_key---class OrgLLMSettingsServiceInjector(Injector[OrgLLMSettingsService]):- """Injector that composes store and user_context for OrgLLMSettingsService."""-- async def inject(- self, state: InjectorState, request: Request | None = None- ) -> AsyncGenerator[OrgLLMSettingsService, None]:- # Local imports to avoid circular dependencies- from openhands.app_server.config import get_db_session, get_user_context-- async with (- get_user_context(state, request) as user_context,- get_db_session(state, request) as db_session,- ):- store = OrgLLMSettingsStore(db_session=db_session)- yield OrgLLMSettingsService(store=store, user_context=user_context)diff --git a/enterprise/storage/lite_llm_manager.py b/enterprise/storage/lite_llm_manager.pyindex 52dfacd825..022f6e46f6 100644--- a/enterprise/storage/lite_llm_manager.py+++ b/enterprise/storage/lite_llm_manager.py@@ -217,7 +217,7 @@ class LiteLlmManager:oss_settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'CodeActAgent','llm': {'model': get_default_litellm_model(),diff --git a/enterprise/storage/org_llm_settings_store.py b/enterprise/storage/org_llm_settings_store.pydeleted file mode 100644index ebc15dfa5d..0000000000--- a/enterprise/storage/org_llm_settings_store.py+++ /dev/null@@ -1,85 +0,0 @@-"""Store class for managing organization LLM settings."""--from __future__ import annotations--import uuid-from dataclasses import dataclass-from uuid import UUID--from server.routes.org_models import OrgLLMSettingsUpdate-from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession-from storage.org import Org-from storage.user import User--from openhands.utils.jsonpatch_compat import deep_merge---@dataclass-class OrgLLMSettingsStore:- """Store for org LLM settings with injected db_session."""-- db_session: AsyncSession-- async def get_current_org_by_user_id(self, user_id: str) -> Org | None:- """Get the user's current organization.-- Args:- user_id: The user's ID (Keycloak user ID)-- Returns:- Org: The user's current organization, or None if not found- """- # First get the user to find their current_org_id- result = await self.db_session.execute(- select(User).filter(User.id == uuid.UUID(user_id))- )- user = result.scalars().first()-- if not user or not user.current_org_id:- return None-- # Then get the org- result = await self.db_session.execute(- select(Org).filter(Org.id == user.current_org_id)- )- return result.scalars().first()-- async def update_org_llm_settings(- self, org_id: UUID, update_data: OrgLLMSettingsUpdate- ) -> Org | None:- """Update organization LLM settings.-- Uses flush() - commit happens at request end via DbSessionInjector.-- Args:- org_id: The organization's ID- update_data: Pydantic model with fields to update-- Returns:- Org: The updated organization, or None if org not found- """- result = await self.db_session.execute(- select(Org).filter(Org.id == org_id).with_for_update()- )- org = result.scalars().first()-- if not org:- return None-- update_data.apply_to_org(org)- if update_data.agent_settings:- org.agent_settings = deep_merge(- org.agent_settings,- update_data.agent_settings,- )- if update_data.conversation_settings:- org.conversation_settings = deep_merge(- org.conversation_settings,- update_data.conversation_settings,- )-- # flush instead of commit - DbSessionInjector auto-commits at request end- await self.db_session.flush()- await self.db_session.refresh(org)- return orgdiff --git a/enterprise/storage/org_member_store.py b/enterprise/storage/org_member_store.pyindex d3a8980d86..de2b60172e 100644--- a/enterprise/storage/org_member_store.py+++ b/enterprise/storage/org_member_store.py@@ -5,7 +5,7 @@ Store class for managing organization-member relationships.from typing import Any, Optionalfrom uuid import UUID-from server.routes.org_models import OrgMemberLLMSettings+from server.routes.org_models import OrgMemberSettingsUpdatefrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import joinedload@@ -237,12 +237,12 @@ class OrgMemberStore:return members, has_more@staticmethod- async def update_all_members_llm_settings_async(+ async def update_all_members_settings_async(session: AsyncSession,org_id: UUID,- member_settings: OrgMemberLLMSettings,+ member_settings: OrgMemberSettingsUpdate,) -> None:- """Update shared LLM settings for all members of an organization.+ """Update shared settings for all members of an organization.Args:session: Database session (passed from caller for transaction)diff --git a/enterprise/storage/org_service.py b/enterprise/storage/org_service.pyindex 69656a58e4..83ca025a8d 100644--- a/enterprise/storage/org_service.py+++ b/enterprise/storage/org_service.py@@ -539,41 +539,31 @@ class OrgService:)raise OrgNameExistsError(update_data.name)- # Convert to dict for OrgStore (excluding None values)- update_dict = update_data.model_dump(exclude_none=True)- if not update_dict:+ if not update_data.has_updates():logger.info('No fields to update',extra={'org_id': str(org_id), 'user_id': user_id},)return existing_org- restricted_fields = {- 'agent_settings',- 'conversation_settings',- 'search_api_key',- 'sandbox_api_key',- }- if restricted_fields.intersection(- update_dict- ) and not await OrgService.has_admin_or_owner_role(user_id, org_id):+ restricted_fields = update_data.restricted_fields()+ if restricted_fields and not await OrgService.has_admin_or_owner_role(+ user_id, org_id+ ):logger.warning('Insufficient role for restricted organization settings update',extra={'user_id': user_id,'org_id': str(org_id),- 'restricted_fields': sorted(- restricted_fields.intersection(update_dict)- ),+ 'restricted_fields': sorted(restricted_fields),},)raise PermissionError(- 'Admin or owner role required to update organization agent settings'+ 'Admin or owner role required to update organization default settings')- # Perform the updatetry:- updated_org = await OrgStore.update_org(org_id, update_dict)+ updated_org = await OrgStore.update_org(org_id, update_data, user_id)if not updated_org:raise OrgDatabaseError('Failed to update organization in database')@@ -582,7 +572,7 @@ class OrgService:extra={'org_id': str(org_id),'user_id': user_id,- 'updated_fields': list(update_dict.keys()),+ 'updated_fields': sorted(update_data.updated_fields()),},)diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.pyindex a6d5b75610..b320633a9e 100644--- a/enterprise/storage/org_store.py+++ b/enterprise/storage/org_store.py@@ -1,21 +1,24 @@-"""-Store class for managing organizations.-"""+"""Store class for managing organizations."""-from typing import Optional+from typing import Any, Optionalfrom uuid import UUID+from pydantic import SecretStrfrom server.constants import (DEFAULT_V1_ENABLED,LITE_LLM_API_URL,ORG_SETTINGS_VERSION,get_default_litellm_model,)-from server.routes.org_models import OrgLLMSettingsUpdate, OrphanedUserError+from server.routes.org_models import (+ OrgMemberSettingsUpdate,+ OrgUpdate,+ OrphanedUserError,+)from sqlalchemy import select, textfrom sqlalchemy.orm import joinedloadfrom storage.database import a_session_maker-from storage.lite_llm_manager import LiteLlmManager+from storage.lite_llm_manager import LiteLlmManager, get_openhands_cloud_key_aliasfrom storage.org import Orgfrom storage.org_member import OrgMemberfrom storage.user import User@@ -25,6 +28,7 @@ from openhands.core.logger import openhands_logger as loggerfrom openhands.sdk.settings import AgentSettings, ConversationSettingsfrom openhands.storage.data_models.settings import Settingsfrom openhands.utils.jsonpatch_compat import deep_merge+from openhands.utils.llm import is_openhands_model_ORG_SETTINGS_EXCLUDED_FIELDS = {'id',@@ -129,11 +133,11 @@ class OrgStore:async def _validate_org_version(org: Org | None) -> Org | None:"""Check if we need to update org version."""if org and org.org_version < ORG_SETTINGS_VERSION:- org = await OrgStore.update_org(+ org = await OrgStore._update_org_kwargs(org.id,{'org_version': ORG_SETTINGS_VERSION,- 'agent_settings': {+ 'agent_settings_diff': {'llm': {'model': get_default_litellm_model(),'base_url': LITE_LLM_API_URL,@@ -155,8 +159,7 @@ class OrgStore:async def get_user_orgs_paginated(user_id: UUID, page_id: str | None = None, limit: int = 100) -> tuple[list[Org], str | None]:- """- Get paginated list of organizations for a user.+ """Get paginated list of organizations for a user.Args:user_id: User UUID@@ -211,41 +214,111 @@ class OrgStore:return validated_orgs, next_page_id+ @staticmethod+ def _merge_and_validate_settings(+ current_settings: dict[str, Any],+ settings_diff: dict[str, Any],+ settings_type: type[AgentSettings] | type[ConversationSettings],+ ) -> AgentSettings | ConversationSettings:+ """Deep-merge a sparse settings diff and validate the merged result."""+ merged_settings = deep_merge(current_settings or {}, settings_diff)+ return settings_type.model_validate(merged_settings)+@staticmethodasync def update_org(org_id: UUID,- kwargs: dict,+ update_data: OrgUpdate,+ user_id: str | None = None,+ ) -> Optional[Org]:+ """Update organization details from a validated OrgUpdate payload."""+ return await OrgStore._update_org_kwargs(+ org_id,+ update_data.model_update_dict(),+ user_id=user_id,+ update_data=update_data,+ )++ @staticmethod+ async def _update_org_kwargs(+ org_id: UUID,+ org_kwargs: dict[str, Any],+ user_id: str | None = None,+ update_data: OrgUpdate | None = None,) -> Optional[Org]:- """Update organization details."""+ """Internal helper for updating organization fields from raw kwargs."""+ from storage.org_member_store import OrgMemberStore++ org_kwargs = dict(org_kwargs)+async with a_session_maker() as session:result = await session.execute(select(Org).filter(Org.id == org_id))org = result.scalars().first()if not org:return None- if 'id' in kwargs:- kwargs.pop('id')+ if 'id' in org_kwargs:+ org_kwargs.pop('id')# Pop the diff-style kwargs before the setattr loop β otherwise# ``hasattr(org, 'agent_settings')`` is True and the loop would# *overwrite* the JSON column instead of deep-merging into it.- agent_settings_diff = kwargs.pop('agent_settings', None)- conversation_settings_diff = kwargs.pop('conversation_settings', None)- for key, value in kwargs.items():+ agent_settings_diff = (+ update_data.agent_settings_diff+ if update_data is not None+ else org_kwargs.pop('agent_settings_diff', None)+ )+ conversation_settings_diff = (+ update_data.conversation_settings_diff+ if update_data is not None+ else org_kwargs.pop('conversation_settings_diff', None)+ )+ for key, value in org_kwargs.items():if hasattr(org, key):setattr(org, key, value)if agent_settings_diff is not None:- org.agent_settings = deep_merge(+ org.agent_settings = OrgStore._merge_and_validate_settings(org.agent_settings,agent_settings_diff,- )+ AgentSettings,+ ).model_dump(mode='json', exclude_unset=True)if conversation_settings_diff is not None:- org.conversation_settings = deep_merge(+ org.conversation_settings = OrgStore._merge_and_validate_settings(org.conversation_settings,conversation_settings_diff,+ ConversationSettings,+ ).model_dump(mode='json', exclude_unset=True)++ if update_data is not None and update_data.touches_org_defaults():+ if user_id is None:+ raise ValueError(+ 'user_id is required when updating organization defaults'+ )++ member_updates = update_data.get_member_updates()+ effective_managed_key = (+ await OrgStore._maybe_get_managed_llm_key_for_user(+ session,+ org,+ user_id,+ )+ )+ should_reset_custom_key_flag = (+ update_data.llm_api_key is not None+ or effective_managed_key is not None)+ if effective_managed_key is not None:+ if member_updates is None:+ member_updates = OrgMemberSettingsUpdate()+ member_updates.llm_api_key = SecretStr(effective_managed_key)++ if member_updates is not None:+ if should_reset_custom_key_flag:+ member_updates.has_custom_llm_api_key = False+ await OrgMemberStore.update_all_members_settings_async(+ session, org_id, member_updates+ )await session.commit()await session.refresh(org)@@ -273,8 +346,7 @@ class OrgStore:org: Org,org_member: OrgMember,) -> Org:- """- Persist organization and owner membership in a single transaction.+ """Persist organization and owner membership in a single transaction.Args:org: Organization entity to persist@@ -295,8 +367,7 @@ class OrgStore:@staticmethodasync def delete_org_cascade(org_id: UUID) -> Org | None:- """- Delete organization and all associated data in cascade, including external LiteLLM cleanup.+ """Delete organization and all associated data in cascade, including external LiteLLM cleanup.Args:org_id: UUID of the organization to delete@@ -445,46 +516,81 @@ class OrgStore:return await OrgStore.get_org_by_id(org_id)@staticmethod- async def update_org_llm_settings_async(- org_id: UUID,- llm_settings: OrgLLMSettingsUpdate,- ) -> Org | None:- """Update organization LLM settings and propagate to members (async version).-- Args:- org_id: Organization ID- llm_settings: Typed LLM settings update model-- Returns:- Updated Org or None if not found- """- from storage.org_member_store import OrgMemberStore-- async with a_session_maker() as session:- result = await session.execute(select(Org).filter(Org.id == org_id))- org = result.scalars().first()- if not org:- return None-- llm_settings.apply_to_org(org)- if llm_settings.agent_settings is not None:- org.agent_settings = deep_merge(- org.agent_settings,- llm_settings.agent_settings,- )- if llm_settings.conversation_settings is not None:- org.conversation_settings = deep_merge(- org.conversation_settings,- llm_settings.conversation_settings,- )+ async def _maybe_get_managed_llm_key_for_user(+ session,+ updated_org: Org,+ user_id: str,+ ) -> str | None:+ """Return the managed LLM key every member row should carry, if any."""+ llm_settings = OrgStore.get_agent_settings_from_org(updated_org).llm+ llm_model = llm_settings.model+ llm_base_url = llm_settings.base_url+ normalized_llm_base_url = llm_base_url.rstrip('/') if llm_base_url else None+ normalized_managed_base_url = LITE_LLM_API_URL.rstrip('/')+ openhands_type = is_openhands_model(llm_model)+ uses_managed_llm_key = (+ normalized_llm_base_url == normalized_managed_base_url+ or (normalized_llm_base_url is None and openhands_type)+ )+ if not uses_managed_llm_key:+ return None++ result = await session.execute(+ select(OrgMember).where(+ OrgMember.org_id == updated_org.id,+ OrgMember.user_id == UUID(user_id),+ )+ )+ acting_member = result.scalars().first()+ if acting_member is None:+ logger.error(+ 'Acting member row not found during managed LLM key '+ 'rotation; skipping managed-key propagation. Members may '+ 'retain stale keys until they save personal settings.',+ extra={'user_id': user_id, 'org_id': str(updated_org.id)},+ )+ return None++ existing_key = acting_member.llm_api_key+ existing_key_raw = existing_key.get_secret_value() if existing_key else None+ if existing_key_raw and await LiteLlmManager.verify_existing_key(+ existing_key_raw,+ user_id,+ str(updated_org.id),+ openhands_type=openhands_type,+ ):+ return existing_key_raw++ if openhands_type:+ logger.info(+ 'Generated managed LLM key for acting user on org-defaults save',+ extra={'user_id': user_id, 'org_id': str(updated_org.id)},+ )+ return await LiteLlmManager.generate_key(+ user_id,+ str(updated_org.id),+ None,+ {'type': 'openhands'},+ )- # Propagate relevant settings to all org members- member_updates = llm_settings.get_member_updates()- if member_updates:- await OrgMemberStore.update_all_members_llm_settings_async(- session, org_id, member_updates- )+ key_alias = get_openhands_cloud_key_alias(user_id, str(updated_org.id))+ await LiteLlmManager.delete_key_by_alias(key_alias=key_alias)+ logger.info(+ 'Generated managed LLM key for acting user on org-defaults save',+ extra={'user_id': user_id, 'org_id': str(updated_org.id)},+ )+ return await LiteLlmManager.generate_key(+ user_id,+ str(updated_org.id),+ key_alias,+ None,+ )- await session.commit()- await session.refresh(org)- return org+ @staticmethod+ async def update_org_defaults_async(+ org_id: UUID,+ update_data: OrgUpdate,+ user_id: str,+ ) -> Org | None:+ """Backward-compatible wrapper for org-defaults updates."""+ return await OrgStore.update_org(org_id, update_data, user_id)diff --git a/enterprise/storage/saas_settings_store.py b/enterprise/storage/saas_settings_store.pyindex a29d53b7f6..e73c3e62ba 100644--- a/enterprise/storage/saas_settings_store.py+++ b/enterprise/storage/saas_settings_store.py@@ -8,7 +8,7 @@ from pydantic import SecretStrfrom server.auth.token_manager import TokenManagerfrom server.constants import LITE_LLM_API_URLfrom server.logger import logger-from server.routes.org_models import OrgMemberLLMSettings+from server.routes.org_models import OrgMemberSettingsUpdatefrom sqlalchemy import selectfrom sqlalchemy.orm import joinedloadfrom storage.database import a_session_maker@@ -262,10 +262,10 @@ class SaasSettingsStore(SettingsStore):else None)- await OrgMemberStore.update_all_members_llm_settings_async(+ await OrgMemberStore.update_all_members_settings_async(session,org_id,- OrgMemberLLMSettings(+ OrgMemberSettingsUpdate(agent_settings_diff=effective_agent_settings_diff,conversation_settings_diff=effective_conversation_diff,llm_api_key=(diff --git a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py b/enterprise/tests/unit/server/routes/test_org_defaults_settings.pynew file mode 100644index 0000000000..ca05000ee1--- /dev/null+++ b/enterprise/tests/unit/server/routes/test_org_defaults_settings.py@@ -0,0 +1,160 @@+"""Unit tests for organization-default settings models and serialization."""++from unittest.mock import MagicMock++from pydantic import SecretStr+from server.constants import LITE_LLM_API_URL+from server.routes.org_models import (+ MASKED_API_KEY,+ OrgDefaultsSettingsResponse,+ OrgUpdate,+)+from storage.org import Org+++def test_org_update_keeps_sparse_diff_dicts():+ """OrgUpdate should preserve sparse org-default diffs as dictionaries."""+ update_data = OrgUpdate.model_validate(+ {+ 'agent_settings_diff': {'llm': {'model': 'claude-3-5-sonnet'}},+ 'conversation_settings_diff': {'security_analyzer': 'llm'},+ }+ )++ assert update_data.agent_settings_diff == {'llm': {'model': 'claude-3-5-sonnet'}}+ assert update_data.conversation_settings_diff == {'security_analyzer': 'llm'}+++def test_normalize_agent_settings_masks_api_key_in_json_on_empty_and_real_keys():+ """Nested api_key values are lifted and masked in the JSON patch."""+ real_key = OrgUpdate.model_validate(+ {'agent_settings_diff': {'llm': {'model': 'anthropic/x', 'api_key': 'sk-raw'}}}+ )+ empty_key = OrgUpdate.model_validate(+ {+ 'agent_settings_diff': {+ 'llm': {'model': 'openhands/x', 'api_key': '', 'base_url': None},+ },+ }+ )++ assert real_key.llm_api_key == 'sk-raw'+ assert real_key.agent_settings_diff is not None+ assert real_key.agent_settings_diff['llm']['api_key'] == MASKED_API_KEY+ assert empty_key.llm_api_key == ''+ assert empty_key.agent_settings_diff is not None+ assert empty_key.agent_settings_diff['llm']['api_key'] == MASKED_API_KEY+++def test_normalize_agent_settings_fills_base_url_for_all_providers():+ """Managed and BYOR providers should keep usable base URLs in diffs."""+ openhands_null = OrgUpdate.model_validate(+ {+ 'agent_settings_diff': {+ 'llm': {'model': 'openhands/claude-3', 'base_url': None},+ },+ }+ )+ openhands_missing = OrgUpdate.model_validate(+ {'agent_settings_diff': {'llm': {'model': 'openhands/claude-3'}}}+ )+ anthropic_null = OrgUpdate.model_validate(+ {+ 'agent_settings_diff': {+ 'llm': {'model': 'anthropic/claude-3-opus-20240229', 'base_url': None},+ },+ }+ )++ openhands_null_diff = openhands_null.agent_settings_diff+ assert openhands_null_diff is not None+ assert openhands_null_diff['llm']['model'] == 'openhands/claude-3'+ assert openhands_null_diff['llm']['base_url'].rstrip('/') == (+ LITE_LLM_API_URL.rstrip('/')+ )++ openhands_missing_diff = openhands_missing.agent_settings_diff+ assert openhands_missing_diff is not None+ assert openhands_missing_diff['llm']['model'] == 'openhands/claude-3'+ assert openhands_missing_diff['llm']['base_url'].rstrip('/') == (+ LITE_LLM_API_URL.rstrip('/')+ )++ anthropic_diff = anthropic_null.agent_settings_diff+ assert anthropic_diff is not None+ anthropic_base = anthropic_diff['llm']['base_url']+ assert isinstance(anthropic_base, str)+ assert 'anthropic.com' in anthropic_base+++def test_from_org_denormalizes_litellm_proxy_prefix_and_returns_base_url_as_stored():+ """Managed-model responses should be denormalized for the frontend."""+ org = MagicMock(spec=Org)+ org.agent_settings = {+ 'schema_version': 1,+ 'agent': 'CodeActAgent',+ 'llm': {+ 'model': 'litellm_proxy/minimax-m2.5',+ 'base_url': LITE_LLM_API_URL,+ 'api_key': MASKED_API_KEY,+ },+ }+ org.conversation_settings = {}+ org.llm_api_key = None+ org.search_api_key = None++ response = OrgDefaultsSettingsResponse.from_org(org)++ assert response.agent_settings.llm.model == 'openhands/minimax-m2.5'+ assert response.agent_settings.llm.base_url == LITE_LLM_API_URL+ assert response.agent_settings.llm.api_key is None+++def test_from_org_returns_provider_default_base_url_as_stored_for_non_managed_models():+ """BYOR provider-default base URLs should round-trip unchanged."""+ from openhands.utils.llm import get_provider_api_base as _provider_base++ anthropic_default = _provider_base('anthropic/claude-3-opus-20240229')+ assert anthropic_default is not None++ org = MagicMock(spec=Org)+ org.agent_settings = {+ 'schema_version': 1,+ 'agent': 'CodeActAgent',+ 'llm': {+ 'model': 'anthropic/claude-3-opus-20240229',+ 'base_url': anthropic_default,+ },+ }+ org.conversation_settings = {}+ org.llm_api_key = None+ org.search_api_key = None++ response = OrgDefaultsSettingsResponse.from_org(org)++ assert response.agent_settings.llm.model == 'anthropic/claude-3-opus-20240229'+ assert response.agent_settings.llm.base_url == anthropic_default+++def test_from_org_keeps_custom_base_url_that_is_not_provider_default():+ """Custom BYOR base URLs should be preserved in the wrapper response."""+ org = MagicMock(spec=Org)+ org.agent_settings = {+ 'schema_version': 1,+ 'agent': 'CodeActAgent',+ 'llm': {+ 'model': 'anthropic/claude-3-opus-20240229',+ 'base_url': 'https://company-proxy.internal/anthropic',+ },+ }+ org.conversation_settings = {}+ org.llm_api_key = None+ org.search_api_key = SecretStr('search-key-1234')++ response = OrgDefaultsSettingsResponse.from_org(org)++ assert (+ response.agent_settings.llm.base_url+ == 'https://company-proxy.internal/anthropic'+ )+ assert response.search_api_key == '****1234'diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.pyindex 496ce2e5ba..aaba1a785d 100644--- a/enterprise/tests/unit/server/routes/test_orgs.py+++ b/enterprise/tests/unit/server/routes/test_orgs.py@@ -29,18 +29,22 @@ from server.routes.org_models import (OrgMemberUpdate,OrgNameExistsError,OrgNotFoundError,+ OrgUpdate,OrphanedUserError,RoleNotFoundError,)from server.routes.orgs import (get_me,+ get_org_defaults_settings,get_org_members,org_router,remove_org_member,+ update_org_defaults_settings,update_org_member,)from storage.org import Org+from openhands.sdk.settings import AgentSettings, ConversationSettingsfrom openhands.server.user_auth import get_user_id# Test user ID constant (must be a valid UUID string)@@ -1020,12 +1024,10 @@ def mock_owner_role():@pytest.mark.asyncioasync def test_get_org_success(mock_app_with_get_user_id, mock_owner_role):- """- GIVEN: Valid org_id and authenticated user who is a member+ """GIVEN: Valid org_id and authenticated memberWHEN: GET /api/organizations/{org_id} is called- THEN: Organization details are returned with 200 status+ THEN: the deprecated detail route still returns the organization response"""- # Arrangeorg_id = uuid.uuid4()mock_org = Org(id=org_id,@@ -1055,54 +1057,24 @@ async def test_get_org_success(mock_app_with_get_user_id, mock_owner_role):),):client = TestClient(mock_app_with_get_user_id)-- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_200_OK- response_data = response.json()- assert response_data['id'] == str(org_id)- assert response_data['name'] == 'Test Organization'- assert response_data['contact_name'] == 'John Doe'- assert response_data['contact_email'] == '[email protected]'- assert response_data['credits'] == 75.5- assert response_data['org_version'] == 5---async def test_get_org_user_not_member(mock_app_with_get_user_id):- """- GIVEN: User is not a member of the organization- WHEN: GET /api/organizations/{org_id} is called- THEN: 403 Forbidden error is returned (permission check fails first)- """- # Arrange- org_id = uuid.uuid4()-- # When user is not a member, get_user_org_role returns None- with patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=None),- ):- client = TestClient(mock_app_with_get_user_id)-- # Actresponse = client.get(f'/api/organizations/{org_id}')- # Assert - Permission check now returns 403 before org lookup- assert response.status_code == status.HTTP_403_FORBIDDEN- assert 'not a member' in response.json()['detail'].lower()+ assert response.status_code == status.HTTP_200_OK+ response_data = response.json()+ assert response_data['id'] == str(org_id)+ assert response_data['name'] == 'Test Organization'+ assert response_data['contact_name'] == 'John Doe'+ assert response_data['contact_email'] == '[email protected]'+ assert response_data['credits'] == 75.5+ assert response_data['org_version'] == 5@pytest.mark.asyncioasync def test_get_org_not_found(mock_app_with_get_user_id, mock_owner_role):- """- GIVEN: Organization does not exist+ """GIVEN: Unknown org idWHEN: GET /api/organizations/{org_id} is called- THEN: 404 Not Found error is returned+ THEN: the deprecated detail route returns 404"""- # Arrangeorg_id = uuid.uuid4()with (@@ -1116,294 +1088,111 @@ async def test_get_org_not_found(mock_app_with_get_user_id, mock_owner_role):),):client = TestClient(mock_app_with_get_user_id)-- # Actresponse = client.get(f'/api/organizations/{org_id}')- # Assert- assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.status_code == status.HTTP_404_NOT_FOUND@pytest.mark.asyncioasync def test_get_org_invalid_uuid(mock_app_with_get_user_id):- """- GIVEN: Invalid UUID format for org_id+ """GIVEN: Invalid UUID formatWHEN: GET /api/organizations/{org_id} is called- THEN: 422 Unprocessable Entity error is returned+ THEN: FastAPI returns 422"""- # Arrange- invalid_org_id = 'not-a-valid-uuid'-client = TestClient(mock_app_with_get_user_id)-- # Act- response = client.get(f'/api/organizations/{invalid_org_id}')-- # Assert+ response = client.get('/api/organizations/not-a-valid-uuid')assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY@pytest.mark.asyncio-async def test_get_org_unauthorized():- """- GIVEN: User is not authenticated- WHEN: GET /api/organizations/{org_id} is called- THEN: 401 Unauthorized error is returned- """- # Arrange- app = FastAPI()- app.include_router(org_router)-- # Override to simulate unauthenticated user- async def mock_unauthenticated():- raise HTTPException(status_code=401, detail='User not authenticated')-- app.dependency_overrides[get_user_id] = mock_unauthenticated-- org_id = uuid.uuid4()- client = TestClient(app)-- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_401_UNAUTHORIZED---async def test_get_org_unexpected_error(mock_app_with_get_user_id, mock_owner_role):- """- GIVEN: Unexpected error occurs during retrieval- WHEN: GET /api/organizations/{org_id} is called- THEN: 500 Internal Server Error is returned+async def test_get_org_defaults_settings_success():+ """GIVEN: A user can view a specific organization's defaults+ WHEN: the org-id settings route is invoked+ THEN: it loads the org through OrgService and serializes the defaults response"""- # Arrangeorg_id = uuid.uuid4()-- with (- patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=mock_owner_role),- ),- patch(- 'server.routes.orgs.OrgService.get_org_by_id',- AsyncMock(side_effect=RuntimeError('Unexpected database error')),- ),- ):- client = TestClient(mock_app_with_get_user_id)-- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR- assert 'unexpected error' in response.json()['detail'].lower()---async def test_get_org_personal_workspace():- """- GIVEN: User retrieves their personal organization (org.id == user_id)- WHEN: GET /api/organizations/{org_id} is called- THEN: is_personal field is True- """- # Arrange- app = FastAPI()- app.include_router(org_router)-- # Use a valid UUID for user_id- user_id = str(uuid.uuid4())- org_id = uuid.UUID(user_id) # Personal org has same ID as user-- def mock_get_user_id():- return user_id-- app.dependency_overrides[get_user_id] = mock_get_user_id-- mock_org = Org(- id=org_id,- name=f'user_{user_id}_org',- contact_name='John Doe',- contact_email='[email protected]',- org_version=5,+ mock_org = MagicMock(spec=Org)+ mock_org.agent_settings = AgentSettings(+ agent='CodeActAgent',+ llm={'model': 'openhands/claude-3', 'base_url': 'https://proxy.example'},)+ mock_org.conversation_settings = ConversationSettings(security_analyzer='llm')+ mock_org.llm_api_key = None+ mock_org.search_api_key = None- mock_role = MagicMock()- mock_role.name = 'owner'-- with (- patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=mock_role),- ),- patch(- 'server.routes.orgs.OrgService.get_org_by_id',- AsyncMock(return_value=mock_org),- ),- patch(- 'server.routes.orgs.OrgService.get_org_credits',- AsyncMock(return_value=50.0),- ),- ):- client = TestClient(app)+ with patch(+ 'server.routes.orgs.OrgService.get_org_by_id',+ AsyncMock(return_value=mock_org),+ ) as mock_get_org:+ response = await get_org_defaults_settings(org_id=org_id, user_id=TEST_USER_ID)- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_200_OK- response_data = response.json()- assert response_data['is_personal'] is True+ assert response.agent_settings.llm.model == 'openhands/claude-3'+ assert response.agent_settings.llm.base_url == 'https://proxy.example'+ assert response.conversation_settings.security_analyzer == 'llm'+ mock_get_org.assert_awaited_once_with(org_id=org_id, user_id=TEST_USER_ID)@pytest.mark.asyncio-async def test_get_org_team_workspace(mock_app_with_get_user_id, mock_owner_role):- """- GIVEN: User retrieves a team organization (org.id != user_id)- WHEN: GET /api/organizations/{org_id} is called- THEN: is_personal field is False+async def test_update_org_defaults_settings_forwards_through_org_service():+ """GIVEN: An org-scoped defaults update payload+ WHEN: the org-id settings write route is invoked+ THEN: it forwards the update through OrgService.update_org_with_permissions"""- # Arrange- org_id = uuid.uuid4() # Different from user_id- mock_org = Org(- id=org_id,- name='Team Organization',- contact_name='John Doe',- contact_email='[email protected]',- org_version=5,+ org_id = uuid.uuid4()+ updated_org = MagicMock(spec=Org)+ updated_org.agent_settings = AgentSettings(+ llm={+ 'model': 'openhands/claude-3.5-sonnet',+ 'base_url': 'https://proxy.example',+ })+ updated_org.conversation_settings = ConversationSettings(confirmation_mode=False)+ updated_org.llm_api_key = 'secret'+ updated_org.search_api_key = None- with (- patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=mock_owner_role),- ),- patch(- 'server.routes.orgs.OrgService.get_org_by_id',- AsyncMock(return_value=mock_org),- ),- patch(- 'server.routes.orgs.OrgService.get_org_credits',- AsyncMock(return_value=100.0),- ),- ):- client = TestClient(mock_app_with_get_user_id)-- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_200_OK- response_data = response.json()- assert response_data['is_personal'] is False---async def test_get_org_with_credits_none(mock_app_with_get_user_id, mock_owner_role):- """- GIVEN: Organization exists but credits retrieval returns None- WHEN: GET /api/organizations/{org_id} is called- THEN: Organization is returned with credits as None- """- # Arrange- org_id = uuid.uuid4()- mock_org = Org(- id=org_id,- name='Test Organization',- contact_name='John Doe',- contact_email='[email protected]',- org_version=5,- agent_settings={- 'llm': {'model': 'claude-opus-4-5-20251101'},- 'condenser': {'enabled': True},+ update_data = OrgUpdate(+ agent_settings_diff={+ 'llm': {'model': 'openhands/claude-3.5-sonnet'},},- enable_proactive_conversation_starters=True,+ conversation_settings_diff={'confirmation_mode': False},)- with (- patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=mock_owner_role),- ),- patch(- 'server.routes.orgs.OrgService.get_org_by_id',- AsyncMock(return_value=mock_org),- ),- patch(- 'server.routes.orgs.OrgService.get_org_credits',- AsyncMock(return_value=None),- ),- ):- client = TestClient(mock_app_with_get_user_id)-- # Act- response = client.get(f'/api/organizations/{org_id}')+ with patch(+ 'server.routes.orgs.OrgService.update_org_with_permissions',+ AsyncMock(return_value=updated_org),+ ) as mock_update:+ response = await update_org_defaults_settings(+ org_id=org_id,+ settings=update_data,+ user_id=TEST_USER_ID,+ )- # Assert- assert response.status_code == status.HTTP_200_OK- response_data = response.json()- assert response_data['credits'] is None+ mock_update.assert_awaited_once_with(+ org_id=org_id,+ update_data=update_data,+ user_id=TEST_USER_ID,+ )+ assert response.agent_settings.llm.model == 'openhands/claude-3.5-sonnet'@pytest.mark.asyncio-async def test_get_org_sensitive_fields_not_exposed(- mock_app_with_get_user_id, mock_owner_role-):- """- GIVEN: Organization is retrieved successfully- WHEN: Response is returned- THEN: Sensitive fields (API keys) are not exposed+async def test_update_org_defaults_settings_rejects_non_default_fields():+ """GIVEN: A non-default org field is sent to the settings-only route+ WHEN: the route is invoked+ THEN: it rejects the payload instead of forwarding a broader org update"""- # Arrangeorg_id = uuid.uuid4()- mock_org = Org(- id=org_id,- name='Test Organization',- contact_name='John Doe',- contact_email='[email protected]',- org_version=5,- agent_settings={- 'llm': {'model': 'claude-opus-4-5-20251101'},- 'condenser': {'enabled': True},- },- search_api_key='secret-search-key-123', # Should not be exposed- sandbox_api_key='secret-sandbox-key-123', # Should not be exposed- enable_proactive_conversation_starters=True,- )-- with (- patch(- 'server.auth.authorization.get_user_org_role',- AsyncMock(return_value=mock_owner_role),- ),- patch(- 'server.routes.orgs.OrgService.get_org_by_id',- AsyncMock(return_value=mock_org),- ),- patch(- 'server.routes.orgs.OrgService.get_org_credits',- AsyncMock(return_value=100.0),- ),- ):- client = TestClient(mock_app_with_get_user_id)+ update_data = OrgUpdate(name='Renamed Org')- # Act- response = client.get(f'/api/organizations/{org_id}')-- # Assert- assert response.status_code == status.HTTP_200_OK- response_data = response.json()-- # Verify sensitive fields are not in response or are None- assert (- 'search_api_key' not in response_data- or response_data.get('search_api_key') is None- )- assert (- 'sandbox_api_key' not in response_data- or response_data.get('sandbox_api_key') is None+ with pytest.raises(HTTPException) as exc_info:+ await update_org_defaults_settings(+ org_id=org_id,+ settings=update_data,+ user_id=TEST_USER_ID,)+ assert exc_info.value.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY+@pytest.mark.asyncioasync def test_delete_org_success(mock_app, mock_owner_role):@@ -3019,13 +2808,13 @@ class TestGetMeEndpoint:status_val='active',):"""Create a MeResponse for testing."""- agent_settings = {'schema_version': 1}+ agent_settings_diff = {'schema_version': 1}if llm_model is not None:- agent_settings.setdefault('llm', {})['model'] = llm_model+ agent_settings_diff.setdefault('llm', {})['model'] = llm_modelif llm_base_url is not None:- agent_settings.setdefault('llm', {})['base_url'] = llm_base_url+ agent_settings_diff.setdefault('llm', {})['base_url'] = llm_base_urlif max_iterations is not None:- agent_settings['max_iterations'] = max_iterations+ agent_settings_diff['max_iterations'] = max_iterationsreturn MeResponse(org_id=str(org_id),@@ -3033,7 +2822,7 @@ class TestGetMeEndpoint:email=email,role=role,llm_api_key=llm_api_key,- agent_settings_diff=agent_settings,+ agent_settings_diff=agent_settings_diff,status=status_val,)diff --git a/enterprise/tests/unit/server/services/test_org_llm_settings_service.py b/enterprise/tests/unit/server/services/test_org_llm_settings_service.pydeleted file mode 100644index 30be9173fe..0000000000--- a/enterprise/tests/unit/server/services/test_org_llm_settings_service.py+++ /dev/null@@ -1,813 +0,0 @@-"""-Unit tests for OrgLLMSettingsService.--Tests the service layer for organization LLM settings operations.-"""--import uuid-from unittest.mock import AsyncMock, MagicMock--import pytest-from pydantic import SecretStr-from server.constants import LITE_LLM_API_URL-from server.routes.org_models import (- MASKED_API_KEY,- OrgLLMSettingsResponse,- OrgLLMSettingsUpdate,- OrgNotFoundError,-)-from server.services import org_llm_settings_service as service_module-from server.services.org_llm_settings_service import OrgLLMSettingsService-from storage.org import Org-from storage.org_member import OrgMember-from storage.org_member_store import OrgMemberStore---def user_id():- """Create a test user ID."""- return str(uuid.uuid4())---def org_id():- """Create a test org ID."""- return uuid.uuid4()---def mock_org(org_id):- """Create a mock organization with LLM settings."""- org = MagicMock(spec=Org)- org.id = org_id- org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'claude-3',- 'base_url': 'https://api.anthropic.com',- },- }- org.conversation_settings = {}- org.llm_api_key = None- org.search_api_key = None- return org---def mock_store():- """Create a mock OrgLLMSettingsStore."""- return MagicMock()---def mock_user_context(user_id):- """Create a mock UserContext that returns the user_id."""- context = MagicMock()- context.get_user_id = AsyncMock(return_value=user_id)- return context---async def test_get_org_llm_settings_success(- user_id, mock_org, mock_store, mock_user_context-):- """- GIVEN: A user with a current organization- WHEN: get_org_llm_settings is called- THEN: OrgLLMSettingsResponse is returned with correct data- """- # Arrange- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- result = await service.get_org_llm_settings()-- # Assert- assert isinstance(result, OrgLLMSettingsResponse)- assert result.agent_settings.llm.model == 'claude-3'- assert result.agent_settings.agent == 'CodeActAgent'- mock_store.get_current_org_by_user_id.assert_called_once_with(user_id)---async def test_get_org_llm_settings_user_not_authenticated(mock_store):- """- GIVEN: A user is not authenticated- WHEN: get_org_llm_settings is called- THEN: ValueError is raised- """- # Arrange- mock_user_context = MagicMock()- mock_user_context.get_user_id = AsyncMock(return_value=None)- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act & Assert- with pytest.raises(ValueError) as exc_info:- await service.get_org_llm_settings()-- assert 'not authenticated' in str(exc_info.value)---async def test_get_org_llm_settings_org_not_found(- user_id, mock_store, mock_user_context-):- """- GIVEN: A user has no current organization- WHEN: get_org_llm_settings is called- THEN: OrgNotFoundError is raised- """- # Arrange- mock_store.get_current_org_by_user_id = AsyncMock(return_value=None)- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act & Assert- with pytest.raises(OrgNotFoundError) as exc_info:- await service.get_org_llm_settings()-- assert 'No current organization' in str(exc_info.value)---async def test_update_org_llm_settings_success(- user_id, mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: A user with a current organization- WHEN: update_org_llm_settings is called with new values- THEN: OrgLLMSettingsResponse is returned with updated data- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {'model': 'new-model'},- }- updated_org.conversation_settings = {- 'confirmation_mode': False,- 'max_iterations': 100,- }- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate(- agent_settings={- 'llm': {'model': 'new-model'},- },- conversation_settings={- 'confirmation_mode': False,- 'max_iterations': 100,- },- )-- mock_store.db_session = MagicMock()- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)- monkeypatch.setattr(- OrgMemberStore, 'update_all_members_llm_settings_async', AsyncMock()- )- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- result = await service.update_org_llm_settings(update_data)-- # Assert- assert isinstance(result, OrgLLMSettingsResponse)- assert result.agent_settings.llm.model == 'new-model'- assert result.conversation_settings.confirmation_mode is False- assert result.conversation_settings.max_iterations == 100- mock_store.update_org_llm_settings.assert_called_once_with(- org_id=mock_org.id,- update_data=update_data,- )---async def test_update_org_llm_settings_no_changes(- user_id, mock_org, mock_store, mock_user_context-):- """- GIVEN: A user with a current organization- WHEN: update_org_llm_settings is called with no fields- THEN: Current settings are returned without calling update- """- # Arrange- update_data = OrgLLMSettingsUpdate() # No fields set-- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock()- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- result = await service.update_org_llm_settings(update_data)-- # Assert- assert isinstance(result, OrgLLMSettingsResponse)- assert result.agent_settings.llm.model == 'claude-3'- mock_store.update_org_llm_settings.assert_not_called()---async def test_update_org_llm_settings_org_not_found(- user_id, mock_store, mock_user_context-):- """- GIVEN: A user has no current organization- WHEN: update_org_llm_settings is called- THEN: OrgNotFoundError is raised- """- # Arrange- update_data = OrgLLMSettingsUpdate(agent_settings={'llm': {'model': 'new-model'}})-- mock_store.get_current_org_by_user_id = AsyncMock(return_value=None)- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act & Assert- with pytest.raises(OrgNotFoundError) as exc_info:- await service.update_org_llm_settings(update_data)-- assert 'No current organization' in str(exc_info.value)---async def test_update_org_llm_settings_accepts_wire_payload_and_propagates(- mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: The exact wire payload the frontend posts to /api/organizations/llm- ({"agent_settings": {...}}) and an org with members carrying stale- agent_settings_diff overrides- WHEN: update_org_llm_settings is called- THEN: 1) the org is actually updated (was a silent no-op before the- field-name fix because the payload keys didn't match the model),- 2) OrgMemberStore.update_all_members_llm_settings_async is invoked- so members' stale diffs are overwritten by the new org defaults- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'claude-3',- 'base_url': 'https://llm-proxy.staging.all-hands.dev',- },- }- updated_org.conversation_settings = {}- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {'base_url': 'https://llm-proxy.staging.all-hands.dev'},- },- }- )-- mock_store.db_session = MagicMock()- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)-- propagation_mock = AsyncMock()- monkeypatch.setattr(- OrgMemberStore,- 'update_all_members_llm_settings_async',- propagation_mock,- )-- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- await service.update_org_llm_settings(update_data)-- # Assert- mock_store.update_org_llm_settings.assert_awaited_once_with(- org_id=mock_org.id,- update_data=update_data,- )- propagation_mock.assert_awaited_once()- call_args = propagation_mock.await_args- assert call_args.args[0] is mock_store.db_session- assert call_args.args[1] == mock_org.id- member_settings = call_args.args[2]- assert member_settings.agent_settings_diff == {- 'llm': {'base_url': 'https://llm-proxy.staging.all-hands.dev'},- }- assert member_settings.conversation_settings_diff is None- assert member_settings.llm_api_key is None---async def test_update_org_llm_settings_does_not_propagate_when_only_org_fields(- mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: An update that only touches org-scoped fields (search_api_key),- with nothing that should land on members- WHEN: update_org_llm_settings is called- THEN: member propagation is not invoked, guarding against regressions- that would needlessly rewrite every member's row- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = mock_org.agent_settings- updated_org.conversation_settings = {}- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate(search_api_key='new-search-key')-- mock_store.db_session = MagicMock()- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)-- propagation_mock = AsyncMock()- monkeypatch.setattr(- OrgMemberStore,- 'update_all_members_llm_settings_async',- propagation_mock,- )-- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- await service.update_org_llm_settings(update_data)-- # Assert- propagation_mock.assert_not_awaited()---async def test_update_org_llm_settings_lifts_nested_api_key_for_column_sync(- mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: The frontend posts the api_key nested inside agent_settings.llm- WHEN: update_org_llm_settings is called- THEN: the raw key is routed through the top-level llm_api_key field,- so every member's encrypted _llm_api_key column is updated via- the propagation call. Without this, members' encrypted columns- stay stale and _get_effective_llm_api_key returns the old key- when they refetch settings.- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {'model': 'claude-3', 'base_url': 'https://example.com'},- }- updated_org.conversation_settings = {}- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {- 'api_key': 'sk-new-raw-key',- 'base_url': 'https://example.com',- },- },- }- )-- # The validator must move the raw key out of agent_settings and into the- # top-level field the rest of the pipeline actually wires to the column,- # AND leave a masked marker in the JSON so ``org.agent_settings.llm``- # and member ``agent_settings_diff.llm`` stay consistent with the- # encrypted column.- assert update_data.llm_api_key == 'sk-new-raw-key'- assert update_data.agent_settings == {- 'llm': {'api_key': MASKED_API_KEY, 'base_url': 'https://example.com'},- }-- mock_store.db_session = MagicMock()- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)-- propagation_mock = AsyncMock()- monkeypatch.setattr(- OrgMemberStore,- 'update_all_members_llm_settings_async',- propagation_mock,- )-- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- await service.update_org_llm_settings(update_data)-- # Assert- propagation_mock.assert_awaited_once()- member_settings = propagation_mock.await_args.args[2]- assert isinstance(member_settings.llm_api_key, SecretStr)- assert member_settings.llm_api_key.get_secret_value() == 'sk-new-raw-key'- assert member_settings.agent_settings_diff == {- 'llm': {'api_key': MASKED_API_KEY, 'base_url': 'https://example.com'},- }- # org-defaults saves are org-wide: always reset members' personal- # BYOR flag so load-time fallthrough won't return a stale custom key.- assert member_settings.has_custom_llm_api_key is False---def test_get_member_updates_treats_empty_llm_api_key_as_none():- """- GIVEN: The frontend posts an empty api_key to signal "switch to the- managed/OpenHands provider" (clear the org-wide custom key)- WHEN: get_member_updates builds the payload for member propagation- THEN: llm_api_key is coerced to None β because OrgMember.llm_api_key's- setter has no ``if raw else None`` guard (the column is- ``nullable=False``), an empty string would be encrypted into an- empty blob on every member rather than cleared. agent_settings_diff- still carries the model diff so the org default actually lands on- members.- """- # Arrange- update = OrgLLMSettingsUpdate(- agent_settings={'llm': {'model': 'openhands/x'}}, llm_api_key=''- )-- # Act- member_updates = update.get_member_updates()-- # Assert β llm_api_key is coerced to None, and the agent_settings_diff- # carries both the model diff AND the auto-filled LiteLLM proxy URL so- # the stored state is self-describing.- assert member_updates is not None- assert member_updates.llm_api_key is None- assert member_updates.agent_settings_diff == {- 'llm': {'model': 'openhands/x', 'base_url': LITE_LLM_API_URL},- }---async def test_update_org_llm_settings_generates_managed_key_for_openhands(- user_id, mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: An admin or owner saves org-defaults with the OpenHands provider- in basic view (payload: model="openhands/...", api_key="",- base_url=None), and their OrgMember row still holds the custom key- from a prior *All*-tab save- WHEN: update_org_llm_settings runs- THEN: a managed LiteLLM key is generated for the acting user, their- has_custom_llm_api_key flag is cleared, and a single propagation- call writes the generated key + agent_settings_diff to every- member row in one DB pass β so the whole org shares one managed- key column value without doubling the row-write churn.- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {'model': 'openhands/claude-3'},- }- updated_org.conversation_settings = {}- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {- 'model': 'openhands/claude-3',- 'api_key': '',- 'base_url': None,- },- },- }- )-- # The acting user's member row β carries the stale custom key from the- # prior *All*-tab save.- acting_member = MagicMock(spec=OrgMember)- acting_member.llm_api_key = SecretStr('old-custom-key')- acting_member.has_custom_llm_api_key = True-- scalars_result = MagicMock()- scalars_result.first.return_value = acting_member- execute_result = MagicMock()- execute_result.scalars.return_value = scalars_result-- db_session = MagicMock()- db_session.execute = AsyncMock(return_value=execute_result)-- mock_store.db_session = db_session- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)-- propagation_mock = AsyncMock()- monkeypatch.setattr(- OrgMemberStore,- 'update_all_members_llm_settings_async',- propagation_mock,- )- monkeypatch.setattr(- service_module.LiteLlmManager,- 'verify_existing_key',- AsyncMock(return_value=False),- )- generate_key_mock = AsyncMock(return_value='litellm-new-key')- monkeypatch.setattr(- service_module.LiteLlmManager, 'generate_key', generate_key_mock- )-- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- await service.update_org_llm_settings(update_data)-- # Assert β key was generated with openhands metadata.- generate_key_mock.assert_awaited_once()- assert generate_key_mock.await_args.args[0] == user_id- assert generate_key_mock.await_args.args[1] == str(mock_org.id)- assert generate_key_mock.await_args.args[2] is None- assert generate_key_mock.await_args.args[3] == {'type': 'openhands'}-- # Assert β a single propagation call writes the diff, the generated- # key, AND the has_custom_llm_api_key=False reset to every member row- # (including the acting user's own row) in one DB pass.- propagation_mock.assert_awaited_once()- member_settings = propagation_mock.await_args.args[2]- assert isinstance(member_settings.llm_api_key, SecretStr)- assert member_settings.llm_api_key.get_secret_value() == 'litellm-new-key'- assert member_settings.has_custom_llm_api_key is False- assert member_settings.agent_settings_diff == {- 'llm': {- 'model': 'openhands/claude-3',- 'api_key': MASKED_API_KEY,- 'base_url': LITE_LLM_API_URL,- },- }---async def test_update_org_llm_settings_does_not_generate_key_for_non_managed_model(- mock_org, mock_store, mock_user_context, monkeypatch-):- """- GIVEN: The owner saves org-defaults with a BYOR model (non-OpenHands,- non-proxy base_url)- WHEN: update_org_llm_settings runs- THEN: no LiteLLM key is generated β the managed-key path is reserved for- the OpenHands provider / managed-proxy case, mirroring the personal- save flow's detection logic.- """- # Arrange- updated_org = MagicMock(spec=Org)- updated_org.id = mock_org.id- updated_org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'anthropic/claude-3',- 'base_url': 'https://example.com',- },- }- updated_org.conversation_settings = {}- updated_org.llm_api_key = None- updated_org.search_api_key = None-- update_data = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {- 'model': 'anthropic/claude-3',- 'base_url': 'https://example.com',- 'api_key': 'custom',- },- },- }- )-- mock_store.db_session = MagicMock()- mock_store.get_current_org_by_user_id = AsyncMock(return_value=mock_org)- mock_store.update_org_llm_settings = AsyncMock(return_value=updated_org)-- monkeypatch.setattr(- OrgMemberStore,- 'update_all_members_llm_settings_async',- AsyncMock(),- )- generate_key_mock = AsyncMock(return_value='should-not-be-called')- monkeypatch.setattr(- service_module.LiteLlmManager, 'generate_key', generate_key_mock- )- monkeypatch.setattr(- service_module.LiteLlmManager,- 'verify_existing_key',- AsyncMock(return_value=True),- )-- service = OrgLLMSettingsService(store=mock_store, user_context=mock_user_context)-- # Act- await service.update_org_llm_settings(update_data)-- # Assert- generate_key_mock.assert_not_awaited()---def test_normalize_agent_settings_masks_api_key_in_json_on_empty_and_real_keys():- """- GIVEN: Wire payloads that either carry a real raw api_key (BYOR save) or- an empty string api_key (managed/OpenHands switch)- WHEN: OrgLLMSettingsUpdate's model validator runs- THEN: both shapes lift the raw value to ``llm_api_key`` for encrypted- column sync AND leave the universal ``MASKED_API_KEY`` marker in- ``agent_settings.llm.api_key``, so the three storage locations- (``org._llm_api_key``, ``org.agent_settings.llm.api_key``,- ``org_member.agent_settings_diff.llm.api_key``) stay in sync once- the update is applied + propagated.- """- # Arrange + Act- real_key = OrgLLMSettingsUpdate.model_validate(- {'agent_settings': {'llm': {'model': 'anthropic/x', 'api_key': 'sk-raw'}}}- )- empty_key = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {'model': 'openhands/x', 'api_key': '', 'base_url': None},- },- }- )-- # Assert β masked in JSON in both cases; lifted raw value on top-level.- assert real_key.llm_api_key == 'sk-raw'- assert real_key.agent_settings is not None- assert real_key.agent_settings['llm']['api_key'] == MASKED_API_KEY- assert empty_key.llm_api_key == ''- assert empty_key.agent_settings is not None- assert empty_key.agent_settings['llm']['api_key'] == MASKED_API_KEY---def test_normalize_agent_settings_fills_base_url_for_all_providers():- """- GIVEN: Wire payloads from the basic view that send ``base_url: null`` for- various providers (OpenHands managed + BYOR providers like OpenAI- and Anthropic)- WHEN: OrgLLMSettingsUpdate's model validator runs- THEN: ``base_url`` is populated for every recognised provider β- ``LITE_LLM_API_URL`` for OpenHands/managed models and the- litellm-derived default URL for non-managed providers (via- ``get_provider_api_base``). Mirrors the ``_post_merge_llm_fixups``- behavior the personal-save flow already performs, so- ``org.agent_settings.llm`` and every member's- ``agent_settings_diff.llm`` carry a usable, self-describing- base URL.- """- # Arrange + Act β covers: OpenHands explicit null, OpenHands missing,- # BYOR provider explicit null (base_url auto-filled to provider default).- openhands_null = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {'model': 'openhands/claude-3', 'base_url': None},- },- }- )- openhands_missing = OrgLLMSettingsUpdate.model_validate(- {'agent_settings': {'llm': {'model': 'openhands/claude-3'}}}- )- anthropic_null = OrgLLMSettingsUpdate.model_validate(- {- 'agent_settings': {- 'llm': {'model': 'anthropic/claude-3-opus-20240229', 'base_url': None},- },- }- )-- # Assert β OpenHands gets the proxy URL; non-OpenHands provider gets the- # provider default that ``litellm.get_api_base`` reports.- assert openhands_null.agent_settings is not None- assert openhands_null.agent_settings['llm']['base_url'] == LITE_LLM_API_URL- assert openhands_missing.agent_settings is not None- assert openhands_missing.agent_settings['llm']['base_url'] == LITE_LLM_API_URL- assert anthropic_null.agent_settings is not None- # get_provider_api_base('anthropic/claude-3-opus-20240229') returns the- # Anthropic public API. Be lenient about the exact suffix litellm returns- # across versions β only require that it got filled with Anthropic's host.- anthropic_base = anthropic_null.agent_settings['llm']['base_url']- assert isinstance(anthropic_base, str)- assert 'anthropic.com' in anthropic_base---def test_from_org_denormalizes_litellm_proxy_prefix_and_returns_base_url_as_stored():- """- GIVEN: An org whose stored ``agent_settings.llm.model`` is in the SDK's- normalized ``litellm_proxy/`` form with ``base_url`` equal to the- managed proxy URL (the state produced by- ``_normalize_agent_settings`` on save)- WHEN: OrgLLMSettingsResponse.from_org serializes for the frontend- THEN: the response shows ``openhands/X`` so the basic-view provider- dropdown matches, returns ``base_url`` exactly as stored so the- three sync targets (``org.agent_settings.llm.base_url``,- ``org_member.agent_settings_diff.llm.base_url``, and this- response) agree, and nulls ``api_key`` so neither the raw secret- nor the ``MASKED_API_KEY`` marker leaks in the response.- """- # Arrange- org = MagicMock(spec=Org)- org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'litellm_proxy/minimax-m2.5',- 'base_url': LITE_LLM_API_URL,- 'api_key': MASKED_API_KEY,- },- }- org.conversation_settings = {}- org.llm_api_key = None- org.search_api_key = None-- # Act- response = OrgLLMSettingsResponse.from_org(org)-- # Assert- assert response.agent_settings.llm.model == 'openhands/minimax-m2.5'- assert response.agent_settings.llm.base_url == LITE_LLM_API_URL- assert response.agent_settings.llm.api_key is None---def test_from_org_returns_provider_default_base_url_as_stored_for_non_managed_models():- """- GIVEN: An org saved with a BYOR provider whose stored ``base_url`` equals- that provider's canonical base URL (what ``_normalize_agent_settings``- auto-filled on save via ``get_provider_api_base``)- WHEN: OrgLLMSettingsResponse.from_org serializes for the frontend- THEN: ``base_url`` is passed through unchanged β the response must- reflect stored state so a future drift that re-introduces- clearing fails this test. The frontend- (``KNOWN_PROVIDER_DEFAULT_BASE_URLS``) is responsible for- recognizing provider defaults as "basic mode."- """- # Arrange β look up the canonical anthropic base URL the same way the- # validator does so the test stays in sync with whatever litellm reports.- from openhands.utils.llm import get_provider_api_base as _provider_base-- anthropic_default = _provider_base('anthropic/claude-3-opus-20240229')- assert anthropic_default is not None-- org = MagicMock(spec=Org)- org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'anthropic/claude-3-opus-20240229',- 'base_url': anthropic_default,- },- }- org.conversation_settings = {}- org.llm_api_key = None- org.search_api_key = None-- # Act- response = OrgLLMSettingsResponse.from_org(org)-- # Assert β model is unchanged (no litellm_proxy/ prefix), base_url is- # returned as stored so stored state and response agree.- assert response.agent_settings.llm.model == 'anthropic/claude-3-opus-20240229'- assert response.agent_settings.llm.base_url == anthropic_default---def test_from_org_keeps_custom_base_url_that_is_not_provider_default():- """- GIVEN: An org saved with a BYOR provider and a genuinely custom base URL- (e.g. a company-run proxy) that does NOT match the provider default- WHEN: OrgLLMSettingsResponse.from_org serializes for the frontend- THEN: ``base_url`` is preserved so the "advanced" view can display it β- we only clear values we're certain match a canonical default.- """- # Arrange- org = MagicMock(spec=Org)- org.agent_settings = {- 'schema_version': 1,- 'agent': 'CodeActAgent',- 'llm': {- 'model': 'anthropic/claude-3-opus-20240229',- 'base_url': 'https://company-proxy.internal/anthropic',- },- }- org.conversation_settings = {}- org.llm_api_key = None- org.search_api_key = None-- # Act- response = OrgLLMSettingsResponse.from_org(org)-- # Assert- assert (- response.agent_settings.llm.base_url- == 'https://company-proxy.internal/anthropic'- )diff --git a/enterprise/tests/unit/storage/test_org_llm_settings_store.py b/enterprise/tests/unit/storage/test_org_llm_settings_store.pydeleted file mode 100644index 24c7e08c09..0000000000--- a/enterprise/tests/unit/storage/test_org_llm_settings_store.py+++ /dev/null@@ -1,178 +0,0 @@-"""-Unit tests for OrgLLMSettingsStore.--Tests the async database operations for organization LLM settings.-"""--import uuid--import pytest-from server.routes.org_models import OrgLLMSettingsUpdate-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine-from sqlalchemy.pool import StaticPool-from storage.base import Base-from storage.org import Org-from storage.org_llm_settings_store import OrgLLMSettingsStore-from storage.user import User---async def async_engine():- """Create an async SQLite engine for testing."""- engine = create_async_engine(- 'sqlite+aiosqlite:///:memory:',- poolclass=StaticPool,- connect_args={'check_same_thread': False},- echo=False,- )- async with engine.begin() as conn:- await conn.run_sync(Base.metadata.create_all)- yield engine- await engine.dispose()---async def async_session_maker(async_engine):- """Create an async session maker for testing."""- return async_sessionmaker(async_engine, class_=AsyncSession, expire_on_commit=False)---async def test_get_current_org_by_user_id_success(async_session_maker):- """- GIVEN: A user exists with a current_org_id- WHEN: get_current_org_by_user_id is called- THEN: The user's current organization is returned- """- # Arrange- async with async_session_maker() as session:- org = Org(- name='test-org',- agent_settings={'schema_version': 1, 'llm': {'model': 'claude-3'}},- )- session.add(org)- await session.flush()-- user = User(id=uuid.uuid4(), current_org_id=org.id)- session.add(user)- await session.commit()- user_id = str(user.id)-- # Act- store = OrgLLMSettingsStore(db_session=session)- result = await store.get_current_org_by_user_id(user_id)-- # Assert- assert result is not None- assert result.name == 'test-org'- assert result.agent_settings['llm']['model'] == 'claude-3'---async def test_get_current_org_by_user_id_user_not_found(async_session_maker):- """- GIVEN: A user does not exist in the database- WHEN: get_current_org_by_user_id is called- THEN: None is returned- """- # Arrange- non_existent_id = str(uuid.uuid4())-- # Act- async with async_session_maker() as session:- store = OrgLLMSettingsStore(db_session=session)- result = await store.get_current_org_by_user_id(non_existent_id)-- # Assert- assert result is None---async def test_update_org_llm_settings_success(async_session_maker):- """- GIVEN: An organization exists in the database- WHEN: update_org_llm_settings is called with new values- THEN: The organization's LLM settings are updated and returned- """- # Arrange- async with async_session_maker() as session:- org = Org(- name='test-org',- agent_settings={'schema_version': 1, 'llm': {'model': 'old-model'}},- )- session.add(org)- await session.commit()- org_id = org.id-- update_data = OrgLLMSettingsUpdate(- agent_settings={- 'llm': {'model': 'new-model'},- 'agent': 'CodeActAgent',- },- conversation_settings={- 'confirmation_mode': True,- },- )-- # Act- store = OrgLLMSettingsStore(db_session=session)- result = await store.update_org_llm_settings(org_id, update_data)-- # Assert- assert result is not None- assert result.agent_settings['llm']['model'] == 'new-model'- assert result.agent_settings['agent'] == 'CodeActAgent'- assert result.conversation_settings['confirmation_mode'] is True---async def test_update_org_llm_settings_org_not_found(async_session_maker):- """- GIVEN: An organization does not exist in the database- WHEN: update_org_llm_settings is called- THEN: None is returned- """- # Arrange- non_existent_org_id = uuid.uuid4()- update_data = OrgLLMSettingsUpdate(agent_settings={'llm': {'model': 'new-model'}})-- # Act- async with async_session_maker() as session:- store = OrgLLMSettingsStore(db_session=session)- result = await store.update_org_llm_settings(non_existent_org_id, update_data)-- # Assert- assert result is None---async def test_update_org_llm_settings_updates_org_defaults_only(async_session_maker):- """- GIVEN: An organization exists with new org-wide defaults- WHEN: update_org_llm_settings is called- THEN: The org defaults are updated without requiring member propagation- """- async with async_session_maker() as session:- org = Org(- name='test-org',- agent_settings={'schema_version': 1, 'llm': {'model': 'old-model'}},- )- session.add(org)- await session.commit()-- store = OrgLLMSettingsStore(db_session=session)- result = await store.update_org_llm_settings(- org.id,- OrgLLMSettingsUpdate(- agent_settings={'llm': {'model': 'new-model'}},- llm_api_key='new-api-key',- search_api_key='search-key',- ),- )-- assert result is not None- assert result.agent_settings['llm']['model'] == 'new-model'- assert result.llm_api_key is not None- assert result.llm_api_key.get_secret_value() == 'new-api-key'- assert result.search_api_key is not None- assert result.search_api_key.get_secret_value() == 'search-key'diff --git a/enterprise/tests/unit/test_lite_llm_manager.py b/enterprise/tests/unit/test_lite_llm_manager.pyindex 8d592f674c..350249654a 100644--- a/enterprise/tests/unit/test_lite_llm_manager.py+++ b/enterprise/tests/unit/test_lite_llm_manager.py@@ -138,7 +138,7 @@ class TestLiteLlmManager:settings = Settings()settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'TestAgent','llm': {'model': 'test-model',diff --git a/enterprise/tests/unit/test_org_member_store.py b/enterprise/tests/unit/test_org_member_store.pyindex 758d01f90a..ec0ea860e1 100644--- a/enterprise/tests/unit/test_org_member_store.py+++ b/enterprise/tests/unit/test_org_member_store.py@@ -56,7 +56,7 @@ def test_get_kwargs_from_settings_starts_members_without_agent_setting_overridessettings = Settings()settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'CodeActAgent','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',@@ -64,7 +64,7 @@ def test_get_kwargs_from_settings_starts_members_without_agent_setting_overrides'api_key': 'member-secret',},},- 'conversation_settings': {+ 'conversation_settings_diff': {'max_iterations': 42,'confirmation_mode': True,},@@ -951,15 +951,15 @@ async def test_get_org_members_paginated_email_filter_case_insensitive(@pytest.mark.asyncio-async def test_update_all_members_llm_settings_async_with_llm_api_key(+async def test_update_all_members_settings_async_with_llm_api_key(async_session_maker,):"""GIVEN: Organization with members and llm_api_key in member settings- WHEN: update_all_members_llm_settings_async is called with llm_api_key+ WHEN: update_all_members_settings_async is called with llm_api_keyTHEN: The llm_api_key is encrypted and stored in _llm_api_key column for all members"""- from server.routes.org_models import OrgMemberLLMSettings+ from server.routes.org_models import OrgMemberSettingsUpdatefrom storage.encrypt_utils import decrypt_value# Arrange@@ -995,10 +995,10 @@ async def test_update_all_members_llm_settings_async_with_llm_api_key(# Actnew_api_key = 'new-test-api-key-12345'- member_settings = OrgMemberLLMSettings(llm_api_key=new_api_key)+ member_settings = OrgMemberSettingsUpdate(llm_api_key=new_api_key)async with async_session_maker() as session:- await OrgMemberStore.update_all_members_llm_settings_async(+ await OrgMemberStore.update_all_members_settings_async(session, org_id, member_settings)await session.commit()@@ -1020,15 +1020,15 @@ async def test_update_all_members_llm_settings_async_with_llm_api_key(@pytest.mark.asyncio-async def test_update_all_members_llm_settings_async_with_non_encrypted_fields(+async def test_update_all_members_settings_async_with_non_encrypted_fields(async_session_maker,):"""GIVEN: Organization with members- WHEN: update_all_members_llm_settings_async is called with non-encrypted fields+ WHEN: update_all_members_settings_async is called with non-encrypted fieldsTHEN: The fields are updated directly without encryption"""- from server.routes.org_models import OrgMemberLLMSettings+ from server.routes.org_models import OrgMemberSettingsUpdate# Arrangeasync with async_session_maker() as session:@@ -1061,7 +1061,7 @@ async def test_update_all_members_llm_settings_async_with_non_encrypted_fields(org_id = org.id# Act- member_settings = OrgMemberLLMSettings(+ member_settings = OrgMemberSettingsUpdate(agent_settings_diff={'llm': {'model': 'new-model',@@ -1072,7 +1072,7 @@ async def test_update_all_members_llm_settings_async_with_non_encrypted_fields()async with async_session_maker() as session:- await OrgMemberStore.update_all_members_llm_settings_async(+ await OrgMemberStore.update_all_members_settings_async(session, org_id, member_settings)await session.commit()@@ -1095,15 +1095,15 @@ async def test_update_all_members_llm_settings_async_with_non_encrypted_fields(@pytest.mark.asyncio-async def test_update_all_members_llm_settings_async_with_empty_settings(+async def test_update_all_members_settings_async_with_empty_settings(async_session_maker,):"""GIVEN: Organization with members and empty member settings- WHEN: update_all_members_llm_settings_async is called with no fields set+ WHEN: update_all_members_settings_async is called with no fields setTHEN: No database update is performed"""- from server.routes.org_models import OrgMemberLLMSettings+ from server.routes.org_models import OrgMemberSettingsUpdate# Arrangeasync with async_session_maker() as session:@@ -1135,10 +1135,10 @@ async def test_update_all_members_llm_settings_async_with_empty_settings(org_id = org.id# Act - Empty settings (all None)- member_settings = OrgMemberLLMSettings()+ member_settings = OrgMemberSettingsUpdate()async with async_session_maker() as session:- await OrgMemberStore.update_all_members_llm_settings_async(+ await OrgMemberStore.update_all_members_settings_async(session, org_id, member_settings)await session.commit()@@ -1155,132 +1155,3 @@ async def test_update_all_members_llm_settings_async_with_empty_settings(assert member.agent_settings_diff['llm']['model'] == 'original-model'# Original key should still be there (encrypted)assert member._llm_api_key is not None---# =============================================================================-# OrgMemberLLMSettings and OrgLLMSettingsUpdate Model Unit Tests-# =============================================================================---def test_org_member_llm_settings_has_updates_with_llm_api_key():- """- GIVEN: OrgMemberLLMSettings with only llm_api_key set- WHEN: has_updates() is called- THEN: Returns True- """- from server.routes.org_models import OrgMemberLLMSettings-- # Arrange- settings = OrgMemberLLMSettings(llm_api_key='test-key')-- # Act- result = settings.has_updates()-- # Assert- assert result is True---def test_org_member_llm_settings_has_updates_empty():- """- GIVEN: OrgMemberLLMSettings with no fields set- WHEN: has_updates() is called- THEN: Returns False- """- from server.routes.org_models import OrgMemberLLMSettings-- # Arrange- settings = OrgMemberLLMSettings()-- # Act- result = settings.has_updates()-- # Assert- assert result is False---def test_org_llm_settings_update_apply_to_org_updates_secret_fields():- """- GIVEN: OrgLLMSettingsUpdate with search_api_key and llm_api_key set- WHEN: apply_to_org() is called- THEN: both org-managed secret fields are applied to the org- """- from unittest.mock import MagicMock-- from server.routes.org_models import OrgLLMSettingsUpdate-- # Arrange- settings = OrgLLMSettingsUpdate(- search_api_key='applied-to-org',- llm_api_key='applied-to-org-llm-key',- )- mock_org = MagicMock()- mock_org.search_api_key = None- mock_org.llm_api_key = None-- # Act- settings.apply_to_org(mock_org)-- # Assert- assert mock_org.search_api_key == 'applied-to-org'- assert mock_org.llm_api_key == 'applied-to-org-llm-key'---def test_org_llm_settings_update_get_member_updates_includes_llm_api_key():- """- GIVEN: OrgLLMSettingsUpdate with agent_settings and llm_api_key set- WHEN: get_member_updates() is called- THEN: Returns OrgMemberLLMSettings including both the diff and llm_api_key- """- from server.routes.org_models import OrgLLMSettingsUpdate-- # Arrange- settings = OrgLLMSettingsUpdate(- agent_settings={'llm': {'model': 'claude-3'}},- llm_api_key='new-member-key',- )-- # Act- member_updates = settings.get_member_updates()-- # Assert- assert member_updates is not None- assert member_updates.llm_api_key.get_secret_value() == 'new-member-key'- assert member_updates.agent_settings_diff == {'llm': {'model': 'claude-3'}}---def test_org_llm_settings_update_get_member_updates_only_llm_api_key():- """- GIVEN: OrgLLMSettingsUpdate with only llm_api_key set- WHEN: get_member_updates() is called- THEN: Returns OrgMemberLLMSettings with llm_api_key (not None)- """- from server.routes.org_models import OrgLLMSettingsUpdate-- # Arrange- settings = OrgLLMSettingsUpdate(llm_api_key='member-key-only')-- # Act- member_updates = settings.get_member_updates()-- # Assert- assert member_updates is not None- assert member_updates.llm_api_key.get_secret_value() == 'member-key-only'- assert member_updates.agent_settings_diff is None---def test_org_llm_settings_update_has_updates_with_llm_api_key():- """- GIVEN: OrgLLMSettingsUpdate with only llm_api_key set- WHEN: has_updates() is called- THEN: Returns True- """- from server.routes.org_models import OrgLLMSettingsUpdate-- # Arrange- settings = OrgLLMSettingsUpdate(llm_api_key='test-key')-- # Act- result = settings.has_updates()-- # Assert- assert result is Truediff --git a/enterprise/tests/unit/test_org_service.py b/enterprise/tests/unit/test_org_service.pyindex a126eef4ce..9d2fdd253d 100644--- a/enterprise/tests/unit/test_org_service.py+++ b/enterprise/tests/unit/test_org_service.py@@ -1200,7 +1200,7 @@ async def test_update_org_with_permissions_success_llm_fields_admin(from server.routes.org_models import OrgUpdateupdate_data = OrgUpdate(- agent_settings={+ agent_settings_diff={'llm': {'model': 'claude-opus-4-5-20251101','base_url': 'https://api.anthropic.com',@@ -1266,10 +1266,10 @@ async def test_update_org_with_permissions_success_llm_fields_owner(from server.routes.org_models import OrgUpdateupdate_data = OrgUpdate(- agent_settings={+ agent_settings_diff={'llm': {'model': 'claude-opus-4-5-20251101'},},- conversation_settings={+ conversation_settings_diff={'security_analyzer': 'llm',},)@@ -1333,7 +1333,7 @@ async def test_update_org_with_permissions_success_mixed_fields_admin(update_data = OrgUpdate(contact_name='Jane Doe',- agent_settings={'llm': {'model': 'claude-opus-4-5-20251101'}},+ agent_settings_diff={'llm': {'model': 'claude-opus-4-5-20251101'}},conversation_expiration=30,)@@ -1537,7 +1537,7 @@ async def test_update_org_with_permissions_llm_fields_insufficient_permission(from server.routes.org_models import OrgUpdateupdate_data = OrgUpdate(- agent_settings={'llm': {'model': 'claude-opus-4-5-20251101'}}+ agent_settings_diff={'llm': {'model': 'claude-opus-4-5-20251101'}})with (@@ -1781,11 +1781,11 @@ async def test_update_org_with_permissions_only_llm_fields(from server.routes.org_models import OrgUpdateupdate_data = OrgUpdate(- agent_settings={+ agent_settings_diff={'llm': {'model': 'claude-opus-4-5-20251101'},'agent': 'agent-mode',},- conversation_settings={+ conversation_settings_diff={'security_analyzer': 'llm',},)diff --git a/enterprise/tests/unit/test_org_store.py b/enterprise/tests/unit/test_org_store.pyindex dd9c7375ae..90bd193a31 100644--- a/enterprise/tests/unit/test_org_store.py+++ b/enterprise/tests/unit/test_org_store.py@@ -3,6 +3,7 @@ from contextlib import asynccontextmanagerfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from server.routes.org_models import OrgUpdatefrom sqlalchemy import selectfrom sqlalchemy.exc import IntegrityErrorfrom storage.org import Org@@ -12,7 +13,7 @@ from storage.org_store import OrgStorefrom storage.role import Rolefrom storage.user import User-from openhands.sdk.settings import AgentSettings+from openhands.sdk.settings import AgentSettings, ConversationSettingsfrom openhands.storage.data_models.settings import Settings@@ -109,18 +110,28 @@ async def test_update_org(async_session_maker, mock_litellm_api):# Test updatewith (patch('storage.org_store.a_session_maker', async_session_maker),+ patch(+ 'storage.org_store.OrgStore._maybe_get_managed_llm_key_for_user',+ new=AsyncMock(return_value=None),+ ),+ patch(+ 'storage.org_member_store.OrgMemberStore.update_all_members_settings_async',+ new=AsyncMock(),+ ),):updated_org = await OrgStore.update_org(org_id=org_id,- kwargs={- 'name': 'updated-org',- 'agent_settings': {'agent': 'PlannerAgent'},- },+ update_data=OrgUpdate(+ name='updated-org',+ agent_settings_diff={'llm': {'model': 'openhands/claude-3'}},+ ),+ user_id=str(uuid.uuid4()),)assert updated_org is not Noneassert updated_org.name == 'updated-org'- assert updated_org.agent_settings['agent'] == 'PlannerAgent'+ agent_settings = OrgStore.get_agent_settings_from_org(updated_org)+ assert agent_settings.llm.model == 'litellm_proxy/claude-3'@pytest.mark.asyncio@@ -130,7 +141,7 @@ async def test_update_org_not_found(async_session_maker):from uuid import uuid4updated_org = await OrgStore.update_org(- org_id=uuid4(), kwargs={'name': 'updated-org'}+ org_id=uuid4(), update_data=OrgUpdate(name='updated-org'))assert updated_org is None@@ -289,7 +300,7 @@ def test_get_kwargs_from_settings():{'language': 'es','enable_sound_notifications': True,- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'CodeActAgent','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',@@ -1030,18 +1041,17 @@ def test_org_deletion_with_invitations_uses_passive_deletes(# =============================================================================-# Tests for async LLM settings methods+# Tests for async organization-defaults propagation methods# =============================================================================@pytest.mark.asyncio-async def test_update_org_llm_settings_async_with_llm_api_key():- """- GIVEN: Organization with members and llm_api_key in update settings- WHEN: update_org_llm_settings_async is called+async def test_update_org_defaults_async_with_llm_api_key():+ """GIVEN: Organization with members and llm_api_key in update settings+ WHEN: update_org_defaults_async is calledTHEN: Org fields are updated and llm_api_key is propagated to all members"""- from server.routes.org_models import OrgLLMSettingsUpdate+ from server.routes.org_models import OrgUpdate# Arrangeorg_id = uuid.uuid4()@@ -1052,8 +1062,8 @@ async def test_update_org_llm_settings_async_with_llm_api_key():agent_settings=AgentSettings(llm={'model': 'old-model'}),)- llm_settings = OrgLLMSettingsUpdate(- agent_settings={'llm': {'model': 'new-model'}},+ llm_settings = OrgUpdate(+ agent_settings_diff={'llm': {'model': 'new-model'}},llm_api_key='new-member-api-key',)@@ -1072,12 +1082,16 @@ async def test_update_org_llm_settings_async_with_llm_api_key():with (patch('storage.org_store.a_session_maker', mock_a_session_maker),patch(- 'storage.org_member_store.OrgMemberStore.update_all_members_llm_settings_async',+ 'storage.org_member_store.OrgMemberStore.update_all_members_settings_async',AsyncMock(),) as mock_member_update,):# Act- result = await OrgStore.update_org_llm_settings_async(org_id, llm_settings)+ result = await OrgStore.update_org_defaults_async(+ org_id,+ llm_settings,+ str(uuid.uuid4()),+ )# Assert - Org is returnedassert result is not None@@ -1092,17 +1106,116 @@ async def test_update_org_llm_settings_async_with_llm_api_key():@pytest.mark.asyncio-async def test_update_org_llm_settings_async_org_not_found():+async def test_update_org_defaults_async_propagates_managed_key_reset():+ """GIVEN: A unified OrgUpdate save that resolves to a managed org key+ WHEN: update_org_defaults_async is called+ THEN: the propagated member update carries that key and resets the custom-key flag"""- GIVEN: Non-existent organization ID- WHEN: update_org_llm_settings_async is called+ from server.routes.org_models import OrgUpdate++ org_id = uuid.uuid4()+ user_id = str(uuid.uuid4())+ mock_org = Org(+ id=org_id,+ name='Test Organization',+ agent_settings=AgentSettings(llm={'model': 'openhands/claude-3'}),+ )+ update_data = OrgUpdate(+ agent_settings_diff={'llm': {'model': 'openhands/claude-3'}}+ )++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = mock_org+ mock_session.execute.return_value = mock_result+ mock_session.commit = AsyncMock()+ mock_session.refresh = AsyncMock()++ @asynccontextmanager+ async def mock_a_session_maker():+ yield mock_session++ with (+ patch('storage.org_store.a_session_maker', mock_a_session_maker),+ patch(+ 'storage.org_store.OrgStore._maybe_get_managed_llm_key_for_user',+ AsyncMock(return_value='managed-key'),+ ),+ patch(+ 'storage.org_member_store.OrgMemberStore.update_all_members_settings_async',+ AsyncMock(),+ ) as mock_member_update,+ ):+ result = await OrgStore.update_org_defaults_async(org_id, update_data, user_id)++ assert result is not None+ agent_settings = OrgStore.get_agent_settings_from_org(result)+ assert agent_settings.llm.model == 'litellm_proxy/claude-3'+ mock_member_update.assert_called_once()+ member_settings = mock_member_update.call_args[0][2]+ assert member_settings.llm_api_key.get_secret_value() == 'managed-key'+ assert member_settings.has_custom_llm_api_key is False+++async def test_update_org_defaults_async_non_key_changes_keep_custom_key_flags():+ """GIVEN: An org-defaults save that only updates shared settings+ WHEN: update_org_defaults_async is called+ THEN: member propagation keeps personal custom-key flags untouched+ """+ from server.routes.org_models import OrgUpdate++ org_id = uuid.uuid4()+ user_id = str(uuid.uuid4())+ mock_org = Org(+ id=org_id,+ name='Test Organization',+ agent_settings=AgentSettings(llm={'model': 'openhands/claude-3'}),+ conversation_settings=ConversationSettings(),+ )+ update_data = OrgUpdate(conversation_settings_diff={'max_iterations': 42})++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = mock_org+ mock_session.execute.return_value = mock_result+ mock_session.commit = AsyncMock()+ mock_session.refresh = AsyncMock()++ @asynccontextmanager+ async def mock_a_session_maker():+ yield mock_session++ with (+ patch('storage.org_store.a_session_maker', mock_a_session_maker),+ patch(+ 'storage.org_store.OrgStore._maybe_get_managed_llm_key_for_user',+ AsyncMock(return_value=None),+ ),+ patch(+ 'storage.org_member_store.OrgMemberStore.update_all_members_settings_async',+ AsyncMock(),+ ) as mock_member_update,+ ):+ await OrgStore.update_org_defaults_async(org_id, update_data, user_id)++ mock_member_update.assert_called_once()+ member_settings = mock_member_update.call_args[0][2]+ assert member_settings.conversation_settings_diff == {'max_iterations': 42}+ assert member_settings.has_custom_llm_api_key is None+++async def test_update_org_defaults_async_org_not_found():+ """GIVEN: Non-existent organization ID+ WHEN: update_org_defaults_async is calledTHEN: Returns None"""- from server.routes.org_models import OrgLLMSettingsUpdate+ from server.routes.org_models import OrgUpdate# Arrangenon_existent_org_id = uuid.uuid4()- llm_settings = OrgLLMSettingsUpdate(agent_settings={'llm': {'model': 'new-model'}})+ llm_settings = OrgUpdate(agent_settings_diff={'llm': {'model': 'new-model'}})# Mock the async session to return None for orgmock_session = AsyncMock()@@ -1116,8 +1229,10 @@ async def test_update_org_llm_settings_async_org_not_found():# Actwith patch('storage.org_store.a_session_maker', mock_a_session_maker):- result = await OrgStore.update_org_llm_settings_async(- non_existent_org_id, llm_settings+ result = await OrgStore.update_org_defaults_async(+ non_existent_org_id,+ llm_settings,+ str(uuid.uuid4()),)# Assertdiff --git a/enterprise/tests/unit/test_saas_settings_store.py b/enterprise/tests/unit/test_saas_settings_store.pyindex 65163e953b..285e3f9b1f 100644--- a/enterprise/tests/unit/test_saas_settings_store.py+++ b/enterprise/tests/unit/test_saas_settings_store.py@@ -32,7 +32,7 @@ def _make_settings(language: str | None = None,**extra_agent: object,) -> DataSettings:- """Build a DataSettings with the new nested agent_settings API."""+ """Build a DataSettings with diff-only nested settings payloads."""top_level: dict = {}if language is not None:top_level['language'] = language@@ -44,20 +44,20 @@ def _make_settings(llm['base_url'] = base_urlif api_key is not None:llm['api_key'] = api_key- agent_settings: dict = {}+ agent_settings_diff: dict = {}if agent is not None:- agent_settings['agent'] = agent+ agent_settings_diff['agent'] = agentif llm:- agent_settings['llm'] = llm- agent_settings.update(extra_agent)+ agent_settings_diff['llm'] = llm+ agent_settings_diff.update(extra_agent)payload: dict = {}- if agent_settings:- payload['agent_settings'] = agent_settings- conv: dict = {}+ if agent_settings_diff:+ payload['agent_settings_diff'] = agent_settings_diff+ conversation_settings_diff: dict = {}if max_iterations is not None:- conv['max_iterations'] = max_iterations- if conv:- payload['conversation_settings'] = conv+ conversation_settings_diff['max_iterations'] = max_iterations+ if conversation_settings_diff:+ payload['conversation_settings_diff'] = conversation_settings_diffif payload:s.update(payload)return s@@ -86,7 +86,7 @@ def test_member_settings_persist_full_effective_agent_settings(mock_config):settings = Settings()settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'CodeActAgent','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',@@ -97,7 +97,7 @@ def test_member_settings_persist_full_effective_agent_settings(mock_config):'max_size': 128,},},- 'conversation_settings': {+ 'conversation_settings_diff': {'max_iterations': 42,'confirmation_mode': True,'security_analyzer': 'llm',@@ -158,7 +158,7 @@ def settings_store(async_session_maker, mock_config):)payload: dict = {}if agent_dict:- payload['agent_settings'] = agent_dict+ payload['agent_settings_diff'] = agent_dictif payload:settings.update(payload)return settings@@ -224,7 +224,7 @@ async def test_store_and_load_keycloak_user(settings_store):)settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'smith','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',@@ -288,7 +288,7 @@ async def test_encryption(settings_store):)settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'smith','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',@@ -609,7 +609,7 @@ async def test_store_saves_mcp_config_in_agent_settings(new_settings = DataSettings()new_settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'llm': {'model': 'test-model','base_url': 'http://non-litellm-url.com',@@ -745,7 +745,7 @@ async def test_store_and_load_mcp_config_via_agent_settings(admin_settings = DataSettings()admin_settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'llm': {'model': 'test-model','base_url': 'http://non-litellm-url.com',diff --git a/enterprise/tests/unit/test_user_store.py b/enterprise/tests/unit/test_user_store.pyindex ce1ea0c6cb..52db00e9f1 100644--- a/enterprise/tests/unit/test_user_store.py+++ b/enterprise/tests/unit/test_user_store.py@@ -55,7 +55,7 @@ def test_get_kwargs_from_settings():)settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'llm': {'model': 'anthropic/claude-sonnet-4-5-20250929','api_key': 'test-key',@@ -93,7 +93,7 @@ async def test_create_default_settings_with_litellm(mock_litellm_api):mock_settings = Settings(language='en')mock_settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'CodeActAgent','llm': {'model': 'anthropic/claude-sonnet-4-5-20250929',diff --git a/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx b/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsxindex 5878a9e02c..cbcd3f75f9 100644--- a/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx+++ b/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx@@ -303,7 +303,7 @@ describe("SdkSectionPage", () => {.spyOn(SettingsService, "getSettings").mockImplementation(async () => structuredClone(persistedSettings));vi.spyOn(SettingsService, "saveSettings").mockImplementation(async (payload) => {- const agentSettings = (payload.agent_settings ?? {}) as Record<string, unknown>;+ const agentSettings = payload.agent_settings_diff as Record<string, unknown>;const llmSettings = (agentSettings.llm ?? {}) as Record<string, unknown>;persistedSettings = buildSettings({@@ -395,7 +395,7 @@ describe("SdkSectionPage", () => {.spyOn(SettingsService, "getSettings").mockImplementation(async () => structuredClone(persistedSettings));vi.spyOn(SettingsService, "saveSettings").mockImplementation(async (payload) => {- const agentSettings = (payload.agent_settings ?? {}) as Record<string, unknown>;+ const agentSettings = payload.agent_settings_diff as Record<string, unknown>;const llmSettings = (agentSettings.llm ?? {}) as Record<string, unknown>;persistedSettings = buildSettings({diff --git a/frontend/__tests__/components/shared/modals/settings/settings-form.test.tsx b/frontend/__tests__/components/shared/modals/settings/settings-form.test.tsxindex 4872382cc7..2e989428ec 100644--- a/frontend/__tests__/components/shared/modals/settings/settings-form.test.tsx+++ b/frontend/__tests__/components/shared/modals/settings/settings-form.test.tsx@@ -30,7 +30,7 @@ describe("SettingsForm", () => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({model: getAgentSettingValue(DEFAULT_SETTINGS, "llm.model"),}),diff --git a/frontend/__tests__/hooks/query/organization-scoped-queries.test.tsx b/frontend/__tests__/hooks/query/organization-scoped-queries.test.tsxindex 57f4a401e5..68ece70883 100644--- a/frontend/__tests__/hooks/query/organization-scoped-queries.test.tsx+++ b/frontend/__tests__/hooks/query/organization-scoped-queries.test.tsx@@ -6,6 +6,7 @@ import { getSettingsQueryFn, useSettings } from "#/hooks/query/use-settings";import { useGetSecrets } from "#/hooks/query/use-get-secrets";import { useApiKeys } from "#/hooks/query/use-api-keys";import SettingsService from "#/api/settings-service/settings-service.api";+import { organizationService } from "#/api/organization-service/organization-service.api";import { SecretsService } from "#/api/secrets-service";import ApiKeysClient from "#/api/api-keys";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";@@ -117,6 +118,19 @@ describe("Organization-scoped query hooks", () => {expect(org2Data).toBeDefined();});+ it("should fetch org-scoped settings with the selected org id", async () => {+ const getOrganizationSettingsSpy = vi+ .spyOn(organizationService, "getOrganizationSettings")+ .mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS);++ const settings = await getSettingsQueryFn("org", "org-1");++ expect(settings.llm_model).toBe(MOCK_DEFAULT_USER_SETTINGS.llm_model);+ expect(getOrganizationSettingsSpy).toHaveBeenCalledWith({+ orgId: "org-1",+ });+ });+it("should prefer schema-managed LLM values over stale legacy flat fields", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue({...MOCK_DEFAULT_USER_SETTINGS,diff --git a/frontend/__tests__/routes/llm-settings.test.tsx b/frontend/__tests__/routes/llm-settings.test.tsxindex e99705653c..d45036e276 100644--- a/frontend/__tests__/routes/llm-settings.test.tsx+++ b/frontend/__tests__/routes/llm-settings.test.tsx@@ -144,6 +144,13 @@ async function selectModel(modelLabel: string) {return modelInput;}++function getPayloadAgentSettings(+ payload: Record<string, unknown>,+): Record<string, unknown> {+ return (payload.agent_settings_diff as Record<string, unknown>) ?? {};+}+function renderLlmSettingsScreen({appMode = "oss",organizationId = "1",@@ -405,7 +412,7 @@ describe("LlmSettingsScreen", () => {vi.spyOn(organizationService,- "getOrganizationAgentSettings",+ "getOrganizationSettings",).mockResolvedValue(buildSettings({llm_model: "gpt-4",@@ -605,7 +612,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({ api_key: "test-api-key" }),}),}),@@ -696,7 +703,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({api_key: "test-api-key",base_url: "https://schema.default/v1",@@ -711,9 +718,7 @@ describe("LlmSettingsScreen", () => {string,unknown>;- expect(- (payload.agent_settings as Record<string, unknown>) ?? {},- ).not.toHaveProperty("agent");+ expect(getPayloadAgentSettings(payload)).not.toHaveProperty("agent");});it("preserves existing MCP settings when saving the LLM page", async () => {@@ -780,10 +785,7 @@ describe("LlmSettingsScreen", () => {const saveSettingsSpy = vi.spyOn(SettingsService, "saveSettings").mockImplementation(async (payload) => {- const payloadAgentSettings = (payload.agent_settings ?? {}) as Record<- string,- unknown- >;+ const payloadAgentSettings = getPayloadAgentSettings(payload);const nextAgentSettings: NonNullable<Settings["agent_settings"]> = {...(persistedSettings.agent_settings ?? {}),@@ -822,9 +824,7 @@ describe("LlmSettingsScreen", () => {string,unknown>;- expect(- (payload.agent_settings as Record<string, unknown>) ?? {},- ).not.toHaveProperty("mcp_config");+ expect(getPayloadAgentSettings(payload)).not.toHaveProperty("mcp_config");await waitFor(() => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);@@ -857,11 +857,18 @@ describe("LlmSettingsScreen", () => {...persistedSettings.agent_settings,} as NonNullable<Settings["agent_settings"]>;- Object.entries(payload).forEach(([key, value]) => {- if (key.includes(".") || key === "agent" || key === "mcp_config") {- nextAgentSettings[key] = value as SettingsValue;- }- });+ const payloadAgentSettings = getPayloadAgentSettings(payload);+ Object.assign(+ nextAgentSettings,+ payloadAgentSettings as Record<string, SettingsValue>,+ );+ nextAgentSettings.llm = {+ ...((persistedSettings.agent_settings?.llm as Record<+ string,+ SettingsValue+ >) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ };persistedSettings = buildSettings({...persistedSettings,@@ -882,7 +889,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({ api_key: "test-api-key" }),}),}),@@ -928,11 +935,18 @@ describe("LlmSettingsScreen", () => {...persistedSettings.agent_settings,} as NonNullable<Settings["agent_settings"]>;- Object.entries(payload).forEach(([key, value]) => {- if (key.includes(".") || key === "agent" || key === "mcp_config") {- nextAgentSettings[key] = value as SettingsValue;- }- });+ const payloadAgentSettings = getPayloadAgentSettings(payload);+ Object.assign(+ nextAgentSettings,+ payloadAgentSettings as Record<string, SettingsValue>,+ );+ nextAgentSettings.llm = {+ ...((persistedSettings.agent_settings?.llm as Record<+ string,+ SettingsValue+ >) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ };persistedSettings = buildSettingsWithAdvancedToggle({...persistedSettings,@@ -955,7 +969,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({ api_key: "test-api-key" }),}),}),@@ -994,16 +1008,23 @@ describe("LlmSettingsScreen", () => {});const getOrganizationSettingsSpy = vi- .spyOn(organizationService, "getOrganizationAgentSettings")+ .spyOn(organizationService, "getOrganizationSettings").mockImplementation(async () => structuredClone(persistedSettings));const saveOrganizationSettingsSpy = vi- .spyOn(organizationService, "saveOrganizationAgentSettings")- .mockImplementation(async (payload) => {+ .spyOn(organizationService, "saveOrganizationSettings")+ .mockImplementation(async ({ settings }) => {const nextAgentSettings = {...persistedSettings.agent_settings,} as NonNullable<Settings["agent_settings"]>;- Object.entries(payload).forEach(([key, value]) => {+ const agentSettingsDiff = settings.agent_settings_diff as+ | Settings["agent_settings"]+ | undefined;+ if (agentSettingsDiff) {+ Object.assign(nextAgentSettings, agentSettingsDiff);+ }++ Object.entries(settings).forEach(([key, value]) => {if (key.includes(".") || key === "agent" || key === "mcp_config") {nextAgentSettings[key] = value as SettingsValue;}@@ -1031,21 +1052,22 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveOrganizationSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({- llm: expect.objectContaining({- api_key: "test-api-key",- base_url: null,+ settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({+ llm: expect.objectContaining({+ api_key: "test-api-key",+ base_url: null,+ }),}),}),}),);});- const payload = saveOrganizationSettingsSpy.mock.calls[0]?.at(0) as Record<- string,- unknown- >;- expect(payload).not.toHaveProperty("search_api_key");+ const payload = saveOrganizationSettingsSpy.mock.calls[0]?.at(0) as {+ settings: Record<string, unknown>;+ };+ expect(payload.settings).not.toHaveProperty("search_api_key");await waitFor(() => {expect(getOrganizationSettingsSpy).toHaveBeenCalledTimes(2);@@ -1079,11 +1101,18 @@ describe("LlmSettingsScreen", () => {...persistedSettings.agent_settings,} as NonNullable<Settings["agent_settings"]>;- Object.entries(payload).forEach(([key, value]) => {- if (key.includes(".") || key === "agent" || key === "mcp_config") {- nextAgentSettings[key] = value as SettingsValue;- }- });+ const payloadAgentSettings = getPayloadAgentSettings(payload);+ Object.assign(+ nextAgentSettings,+ payloadAgentSettings as Record<string, SettingsValue>,+ );+ nextAgentSettings.llm = {+ ...((persistedSettings.agent_settings?.llm as Record<+ string,+ SettingsValue+ >) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ };persistedSettings = buildSettingsWithAdvancedToggle({...persistedSettings,@@ -1105,7 +1134,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({api_key: "test-api-key",base_url: null,@@ -1140,11 +1169,18 @@ describe("LlmSettingsScreen", () => {...persistedSettings.agent_settings,} as NonNullable<Settings["agent_settings"]>;- Object.entries(payload).forEach(([key, value]) => {- if (key.includes(".") || key === "agent" || key === "mcp_config") {- nextAgentSettings[key] = value as SettingsValue;- }- });+ const payloadAgentSettings = getPayloadAgentSettings(payload);+ Object.assign(+ nextAgentSettings,+ payloadAgentSettings as Record<string, SettingsValue>,+ );+ nextAgentSettings.llm = {+ ...((persistedSettings.agent_settings?.llm as Record<+ string,+ SettingsValue+ >) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ };persistedSettings = buildSettingsWithAdvancedToggle({...persistedSettings,@@ -1175,7 +1211,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({model: "openai/gpt-4o",api_key: "test-api-key",@@ -1419,7 +1455,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(saveSettingsSpy).toHaveBeenCalledWith(expect.objectContaining({- agent_settings: expect.objectContaining({+ agent_settings_diff: expect.objectContaining({llm: expect.objectContaining({base_url: "https://custom.example/v1/extra",}),diff --git a/frontend/__tests__/routes/mcp-settings.test.tsx b/frontend/__tests__/routes/mcp-settings.test.tsxindex 9cb7ef03d3..907315ec8a 100644--- a/frontend/__tests__/routes/mcp-settings.test.tsx+++ b/frontend/__tests__/routes/mcp-settings.test.tsx@@ -126,12 +126,28 @@ describe("MCPSettingsScreen", () => {);vi.spyOn(SettingsService, "saveSettings").mockImplementation(async (payload) => {- persistedSettings = buildSettings(- deepMerge(- structuredClone(persistedSettings) as Record<string, unknown>,- payload as Record<string, unknown>,- ) as Partial<Settings>,- );+ const nextSettings = structuredClone(persistedSettings) as Record<+ string,+ unknown+ >;+ const agentSettingsPatch = (payload as Record<string, unknown>)+ .agent_settings_diff as Record<string, unknown> | undefined;++ if (agentSettingsPatch) {+ nextSettings.agent_settings = deepMerge(+ (nextSettings.agent_settings ?? {}) as Record<string, unknown>,+ agentSettingsPatch,+ );+ }++ for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {+ if (key === "agent_settings_diff") {+ continue;+ }+ nextSettings[key] = value;+ }++ persistedSettings = buildSettings(nextSettings as Partial<Settings>);return true;},);diff --git a/frontend/__tests__/utils/model-name-case-preservation.test.tsx b/frontend/__tests__/utils/model-name-case-preservation.test.tsxindex 560c0c5afa..4e63dd67cf 100644--- a/frontend/__tests__/utils/model-name-case-preservation.test.tsx+++ b/frontend/__tests__/utils/model-name-case-preservation.test.tsx@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { extractSettings } from "#/utils/settings-utils";function getLlmModel(settings: ReturnType<typeof extractSettings>): unknown {- const as = settings.agent_settings as Record<string, unknown> | undefined;+ const as = settings.agent_settings_diff as Record<string, unknown> | undefined;const llm = as?.llm as Record<string, unknown> | undefined;return llm?.model;}diff --git a/frontend/__tests__/utils/settings-utils.test.ts b/frontend/__tests__/utils/settings-utils.test.tsindex abe7affc8c..fdfed11dea 100644--- a/frontend/__tests__/utils/settings-utils.test.ts+++ b/frontend/__tests__/utils/settings-utils.test.ts@@ -65,7 +65,7 @@ describe("extractSettings", () => {const settings = extractSettings(formData);const expectedModel = `${provider}/${model}`;- const as = settings.agent_settings as Record<string, unknown>;+ const as = settings.agent_settings_diff as Record<string, unknown>;const llm = as?.llm as Record<string, unknown>;expect(llm?.model).toBe(expectedModel);if (expectedModel !== expectedModel.toLowerCase()) {@@ -83,7 +83,7 @@ describe("extractSettings", () => {const settings = extractSettings(formData);- const as = settings.agent_settings as Record<string, unknown>;+ const as = settings.agent_settings_diff as Record<string, unknown>;const llm = as?.llm as Record<string, unknown>;expect(llm?.model).toBe("sambanova/Meta-Llama-3.1-8B-Instruct");expect(llm?.model).not.toBe("custom-model-name");diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.tsindex a5e08908a1..fe92233a4c 100644--- a/frontend/src/api/organization-service/organization-service.api.ts+++ b/frontend/src/api/organization-service/organization-service.api.ts@@ -8,7 +8,7 @@ import {import { Settings } from "#/types/settings";import { openHands } from "../open-hands-axios";-type OrganizationAgentSettingsResponse = Pick<+type OrganizationSettingsResponse = Pick<Settings,| "agent_settings"| "conversation_settings"@@ -25,13 +25,6 @@ export const organizationService = {return data;},- getOrganization: async ({ orgId }: { orgId: string }) => {- const { data } = await openHands.get<Organization>(- `/api/organizations/${orgId}`,- );- return data;- },-getOrganizations: async () => {const { data } = await openHands.get<{items: Organization[];@@ -178,18 +171,22 @@ export const organizationService = {return data;},- getOrganizationAgentSettings: async () => {- const { data } = await openHands.get<OrganizationAgentSettingsResponse>(- "/api/organizations/llm",+ getOrganizationSettings: async ({ orgId }: { orgId: string }) => {+ const { data } = await openHands.get<OrganizationSettingsResponse>(+ `/api/organizations/${orgId}/settings`,);return data;},- saveOrganizationAgentSettings: async (- settings: Partial<Settings> & Record<string, unknown>,- ) => {- const { data } = await openHands.post<OrganizationAgentSettingsResponse>(- "/api/organizations/llm",+ saveOrganizationSettings: async ({+ orgId,+ settings,+ }: {+ orgId: string;+ settings: Partial<Settings> & Record<string, unknown>;+ }) => {+ const { data } = await openHands.patch<OrganizationSettingsResponse>(+ `/api/organizations/${orgId}/settings`,settings,);return data;diff --git a/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx b/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsxindex f30e42562d..db2130cc63 100644--- a/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx+++ b/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx@@ -226,10 +226,12 @@ export function SdkSectionPage({dirty,view,);- const defaultPayload =- settingsSource === "conversation_settings"- ? { conversation_settings: basePayload }- : { agent_settings: basePayload };+ let defaultPayload: Record<string, unknown>;+ if (settingsSource === "conversation_settings") {+ defaultPayload = { conversation_settings_diff: basePayload };+ } else {+ defaultPayload = { agent_settings_diff: basePayload };+ }payload = buildPayload? buildPayload(basePayload, { values, dirty, view }): defaultPayload;diff --git a/frontend/src/components/shared/modals/settings/settings-form.tsx b/frontend/src/components/shared/modals/settings/settings-form.tsxindex 38cec6b2b5..11ec26fe6f 100644--- a/frontend/src/components/shared/modals/settings/settings-form.tsx+++ b/frontend/src/components/shared/modals/settings/settings-form.tsx@@ -40,7 +40,7 @@ export function SettingsForm({ settings, onClose }: SettingsFormProps) {onClose();const agentLlm =- ((newSettings.agent_settings as Record<string, unknown>)+ ((newSettings.agent_settings_diff as Record<string, unknown>)?.llm as Record<string, unknown>) ?? {};posthog.capture("settings_saved", {LLM_MODEL: agentLlm.model,diff --git a/frontend/src/hooks/mutation/use-add-mcp-server.ts b/frontend/src/hooks/mutation/use-add-mcp-server.tsindex 18717282da..aaa76ad651 100644--- a/frontend/src/hooks/mutation/use-add-mcp-server.ts+++ b/frontend/src/hooks/mutation/use-add-mcp-server.ts@@ -64,7 +64,7 @@ export function useAddMcpServer() {}await SettingsService.saveSettings({- agent_settings: { mcp_config: toSdkMcpConfig(newConfig) },+ agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },});},onSuccess: () => {diff --git a/frontend/src/hooks/mutation/use-delete-mcp-server.ts b/frontend/src/hooks/mutation/use-delete-mcp-server.tsindex 90ff3b5b04..478fed462a 100644--- a/frontend/src/hooks/mutation/use-delete-mcp-server.ts+++ b/frontend/src/hooks/mutation/use-delete-mcp-server.ts@@ -33,7 +33,7 @@ export function useDeleteMcpServer() {}await SettingsService.saveSettings({- agent_settings: { mcp_config: toSdkMcpConfig(newConfig) },+ agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },});},onSuccess: () => {diff --git a/frontend/src/hooks/mutation/use-save-settings.ts b/frontend/src/hooks/mutation/use-save-settings.tsindex 3b0be83638..2f0060d488 100644--- a/frontend/src/hooks/mutation/use-save-settings.ts+++ b/frontend/src/hooks/mutation/use-save-settings.ts@@ -16,25 +16,27 @@ type SettingsUpdate = Partial<Settings> & Record<string, unknown>;const saveSettingsMutationFn = async (scope: SettingsScope,settings: SettingsUpdate,+ organizationId?: string | null,) => {const settingsToSave: SettingsUpdate = { ...settings };delete settingsToSave.agent_settings_schema;delete settingsToSave.conversation_settings_schema;- const conversationSettings: Record<string, SettingsValue> = {- ...((settingsToSave.conversation_settings as Record<+ const conversationSettings = {+ ...((settingsToSave.conversation_settings_diff as Record<string,SettingsValue>) ?? {}),};if (Object.keys(conversationSettings).length > 0) {- settingsToSave.conversation_settings = conversationSettings;+ settingsToSave.conversation_settings_diff = conversationSettings;} else {- delete settingsToSave.conversation_settings;+ delete settingsToSave.conversation_settings_diff;}+ delete settingsToSave.conversation_settings;- const agentSettings = settingsToSave.agent_settings as+ const agentSettings = settingsToSave.agent_settings_diff as| Record<string, unknown>| undefined;const llmSettings = agentSettings?.llm as Record<string, unknown> | undefined;@@ -42,6 +44,12 @@ const saveSettingsMutationFn = async (const apiKey = llmSettings.api_key.trim();llmSettings.api_key = apiKey === "" ? "" : apiKey;}+ if (agentSettings && Object.keys(agentSettings).length > 0) {+ settingsToSave.agent_settings_diff = agentSettings;+ } else {+ delete settingsToSave.agent_settings_diff;+ }+ delete settingsToSave.agent_settings;if (typeof settingsToSave.search_api_key === "string") {settingsToSave.search_api_key = settingsToSave.search_api_key.trim();@@ -54,7 +62,14 @@ const saveSettingsMutationFn = async (}if (scope === "org") {- await organizationService.saveOrganizationAgentSettings(settingsToSave);+ if (!organizationId) {+ throw new Error("Organization ID is required for org settings saves");+ }++ await organizationService.saveOrganizationSettings({+ orgId: organizationId,+ settings: settingsToSave,+ });return;}@@ -82,7 +97,7 @@ export const useSaveSettings = (scope: SettingsScope = "personal") => {});}- await saveSettingsMutationFn(scope, settings);+ await saveSettingsMutationFn(scope, settings, organizationId);},onSuccess: async () => {await queryClient.invalidateQueries({diff --git a/frontend/src/hooks/mutation/use-update-mcp-server.ts b/frontend/src/hooks/mutation/use-update-mcp-server.tsindex 16713f1770..15b0bb1406 100644--- a/frontend/src/hooks/mutation/use-update-mcp-server.ts+++ b/frontend/src/hooks/mutation/use-update-mcp-server.ts@@ -72,7 +72,7 @@ export function useUpdateMcpServer() {}await SettingsService.saveSettings({- agent_settings: { mcp_config: toSdkMcpConfig(newConfig) },+ agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },});},onSuccess: () => {diff --git a/frontend/src/hooks/mutation/use-update-organization.ts b/frontend/src/hooks/mutation/use-update-organization.tsindex a7ba9f1dfc..a55500663b 100644--- a/frontend/src/hooks/mutation/use-update-organization.ts+++ b/frontend/src/hooks/mutation/use-update-organization.ts@@ -15,11 +15,6 @@ export const useUpdateOrganization = () => {});},onSuccess: () => {- // Invalidate the specific organization query- queryClient.invalidateQueries({- queryKey: ["organizations", organizationId],- });- // Invalidate the organizations list to refresh org-selectorqueryClient.invalidateQueries({queryKey: ["organizations"],});diff --git a/frontend/src/hooks/query/use-organization.ts b/frontend/src/hooks/query/use-organization.tsindex 337eb8601a..522a79adb9 100644--- a/frontend/src/hooks/query/use-organization.ts+++ b/frontend/src/hooks/query/use-organization.ts@@ -1,14 +1,21 @@-import { useQuery } from "@tanstack/react-query";-import { organizationService } from "#/api/organization-service/organization-service.api";+import { useMemo } from "react";import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { useOrganizations } from "#/hooks/query/use-organizations";export const useOrganization = () => {const { organizationId } = useSelectedOrganizationId();+ const organizationsQuery = useOrganizations();- return useQuery({- queryKey: ["organizations", organizationId],- queryFn: () =>- organizationService.getOrganization({ orgId: organizationId! }),- enabled: !!organizationId,- });+ const organization = useMemo(+ () =>+ organizationsQuery.data?.organizations.find(+ (candidate) => candidate.id === organizationId,+ ),+ [organizationId, organizationsQuery.data?.organizations],+ );++ return {+ ...organizationsQuery,+ data: organization,+ };};diff --git a/frontend/src/hooks/query/use-settings.ts b/frontend/src/hooks/query/use-settings.tsindex a1aa5f26fd..3201be60f6 100644--- a/frontend/src/hooks/query/use-settings.ts+++ b/frontend/src/hooks/query/use-settings.ts@@ -109,10 +109,13 @@ const normalizeSettingsResponse = (settings: Partial<Settings>): Settings => {export const getSettingsQueryFn = async (scope: SettingsScope = "personal",+ organizationId?: string | null,): Promise<Settings> => {const settings =scope === "org"- ? await organizationService.getOrganizationAgentSettings()+ ? await organizationService.getOrganizationSettings({+ orgId: organizationId!,+ }): await SettingsService.getSettings();return normalizeSettingsResponse(settings);@@ -128,7 +131,7 @@ export const useSettings = (scope: SettingsScope = "personal") => {const query = useQuery({queryKey: ["settings", scope, organizationId],- queryFn: () => getSettingsQueryFn(scope),+ queryFn: () => getSettingsQueryFn(scope, organizationId),retry: (_, error) => error.status !== 404,refetchOnWindowFocus: false,staleTime: 1000 * 60 * 5,diff --git a/frontend/src/mocks/settings-handlers.ts b/frontend/src/mocks/settings-handlers.tsindex 7c8784777a..c27d85a008 100644--- a/frontend/src/mocks/settings-handlers.ts+++ b/frontend/src/mocks/settings-handlers.ts@@ -444,33 +444,46 @@ export const SETTINGS_HANDLERS = [MOCK_USER_PREFERENCES.settings ||structuredClone(MOCK_DEFAULT_USER_SETTINGS);+ if ("agent_settings" in body || "conversation_settings" in body) {+ return HttpResponse.json(+ {+ error: "Use *_diff nested settings payloads instead of legacy keys",+ keys: ["agent_settings", "conversation_settings"].filter(+ (key) => key in body,+ ),+ },+ { status: 422 },+ );+ }+const nextSettings: Settings = { ...current };- // Deep-merge nested agent_settings- if (body.agent_settings && typeof body.agent_settings === "object") {+ const agentSettingsPatch = body.agent_settings_diff as+ | Record<string, unknown>+ | undefined;+ if (agentSettingsPatch) {const merged = deepMerge((current.agent_settings ?? {}) as Record<string, unknown>,- body.agent_settings as Record<string, unknown>,+ agentSettingsPatch,);nextSettings.agent_settings = merged as Settings["agent_settings"];}- // Deep-merge nested conversation_settings- if (- body.conversation_settings &&- typeof body.conversation_settings === "object"- ) {+ const conversationSettingsPatch = body.conversation_settings_diff as+ | Record<string, SettingsValue>+ | undefined;+ if (conversationSettingsPatch) {nextSettings.conversation_settings = {...(current.conversation_settings ?? {}),- ...(body.conversation_settings as Record<string, SettingsValue>),+ ...conversationSettingsPatch,};}// Apply top-level fields (excluding nested settings)for (const [key, value] of Object.entries(body)) {if (- key !== "agent_settings" &&- key !== "conversation_settings" &&+ key !== "agent_settings_diff" &&+ key !== "conversation_settings_diff" &&key !== "agent_settings_schema" &&key !== "conversation_settings_schema") {diff --git a/frontend/src/routes/llm-settings.tsx b/frontend/src/routes/llm-settings.tsxindex 67b0cddfdf..6e94322e58 100644--- a/frontend/src/routes/llm-settings.tsx+++ b/frontend/src/routes/llm-settings.tsx@@ -378,7 +378,7 @@ export function LlmSettingsScreen({agentSettings.llm = llm;}- return { agent_settings: agentSettings };+ return { agent_settings_diff: agentSettings };},[isSaasMode, schema, selectedProvider],);diff --git a/frontend/src/routes/verification-settings.tsx b/frontend/src/routes/verification-settings.tsxindex 3c11bcad42..2e40acee8e 100644--- a/frontend/src/routes/verification-settings.tsx+++ b/frontend/src/routes/verification-settings.tsx@@ -160,7 +160,7 @@ export function VerificationSettingsScreen({payload.security_analyzer = securityAnalyzer;}- return { conversation_settings: payload };+ return { conversation_settings_diff: payload };},[confirmationMode,diff --git a/frontend/src/types/org.ts b/frontend/src/types/org.tsindex e9c56a8e95..5b0af4fc46 100644--- a/frontend/src/types/org.ts+++ b/frontend/src/types/org.ts@@ -18,7 +18,7 @@ export interface Organization {max_budget_per_task: number;enable_solvability_analysis: boolean;v1_enabled: boolean;- credits: number;+ credits: number | null;is_personal?: boolean;}diff --git a/frontend/src/utils/settings-utils.ts b/frontend/src/utils/settings-utils.tsindex e42d37ccef..4346a90986 100644--- a/frontend/src/utils/settings-utils.ts+++ b/frontend/src/utils/settings-utils.ts@@ -49,7 +49,7 @@ export const extractSettings = (return {...(Object.keys(agentSettings).length > 0- ? { agent_settings: agentSettings }+ ? { agent_settings_diff: agentSettings }: {}),...(language ? { language } : {}),};diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.pyindex ad722dbed0..90b556ea8f 100644--- a/openhands/app_server/settings/settings_router.py+++ b/openhands/app_server/settings/settings_router.py@@ -165,6 +165,10 @@ async def load_settings(response_model=None,responses={200: {'description': 'Settings stored successfully', 'model': dict},+ 422: {+ 'description': 'Legacy nested settings keys are not accepted',+ 'model': dict,+ },500: {'description': 'Error storing settings', 'model': dict},},)@@ -174,14 +178,27 @@ async def store_settings() -> JSONResponse:"""Store user settings.- Accepts a partial payload and deep-merges ``agent_settings`` and- ``conversation_settings`` with the existing persisted values so that+ Accepts a partial payload and deep-merges ``agent_settings_diff`` and+ ``conversation_settings_diff`` with the existing persisted values so thatsaving one settings page never overwrites fields owned by another.Returns:200: Settings stored successfully+ 422: Legacy nested settings keys are rejected500: Error storing settings"""+ legacy_nested_keys = sorted(+ key for key in ('agent_settings', 'conversation_settings') if key in payload+ )+ if legacy_nested_keys:+ return JSONResponse(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ content={+ 'error': 'Use *_diff nested settings payloads instead of legacy keys',+ 'keys': legacy_nested_keys,+ },+ )+try:existing_settings = await settings_store.load()settings = existing_settings.model_copy() if existing_settings else Settings()diff --git a/openhands/storage/data_models/settings.py b/openhands/storage/data_models/settings.pyindex a865e40476..db5d1902fd 100644--- a/openhands/storage/data_models/settings.py+++ b/openhands/storage/data_models/settings.py@@ -146,54 +146,59 @@ class Settings(BaseModel):def update(self, payload: dict[str, Any]) -> None:"""Apply a batch of changes from a nested dict.- ``agent_settings`` values use nested dict shape (matching model_dump).- ``conversation_settings`` values likewise.- Top-level keys are set directly on the model.+ ``agent_settings_diff`` and ``conversation_settings_diff`` use nested+ dict shape (matching model_dump). Top-level keys are set directly on the+ model."""- if 'agent_settings' in payload:- agent_update = payload['agent_settings']- if isinstance(agent_update, dict):- coerced: dict[str, Any] = {}- for key, value in agent_update.items():- coerced[key] = (- _coerce_value(value) if not isinstance(value, dict) else value- )-- replace_mcp_config = 'mcp_config' in agent_update- mcp_config = (- coerced.pop('mcp_config', None) if replace_mcp_config else None- )+ legacy_nested_keys = [+ key for key in ('agent_settings', 'conversation_settings') if key in payload+ ]+ if legacy_nested_keys:+ raise ValueError(+ 'Use *_diff nested settings payloads instead of legacy '+ + ', '.join(sorted(legacy_nested_keys))+ )- merged = deep_merge(- self.agent_settings.model_dump(- mode='json', context={'expose_secrets': True}- ),- coerced,+ agent_update = payload.get('agent_settings_diff')+ if isinstance(agent_update, dict):+ coerced: dict[str, Any] = {}+ for key, value in agent_update.items():+ coerced[key] = (+ _coerce_value(value) if not isinstance(value, dict) else value)- if replace_mcp_config:- merged['mcp_config'] = mcp_config- # Use object.__setattr__ to avoid validate_assignment- # side-effects on other fields.- object.__setattr__(- self, 'agent_settings', AgentSettings.model_validate(merged)- )+ replace_mcp_config = 'mcp_config' in agent_update+ mcp_config = coerced.pop('mcp_config', None) if replace_mcp_config else None- if 'conversation_settings' in payload:- conv_update = payload['conversation_settings']- if isinstance(conv_update, dict):- merged = deep_merge(- self.conversation_settings.model_dump(mode='json'),- conv_update,- )- object.__setattr__(- self,- 'conversation_settings',- ConversationSettings.model_validate(merged),- )+ merged = deep_merge(+ self.agent_settings.model_dump(+ mode='json', context={'expose_secrets': True}+ ),+ coerced,+ )+ if replace_mcp_config:+ merged['mcp_config'] = mcp_config++ # Use object.__setattr__ to avoid validate_assignment+ # side-effects on other fields.+ object.__setattr__(+ self, 'agent_settings', AgentSettings.model_validate(merged)+ )++ conv_update = payload.get('conversation_settings_diff')+ if isinstance(conv_update, dict):+ merged = deep_merge(+ self.conversation_settings.model_dump(mode='json'),+ conv_update,+ )+ object.__setattr__(+ self,+ 'conversation_settings',+ ConversationSettings.model_validate(merged),+ )for key, value in payload.items():- if key in ('agent_settings', 'conversation_settings'):+ if key in ('agent_settings_diff', 'conversation_settings_diff'):continueif key in Settings.model_fields and key not in _SETTINGS_FROZEN_FIELDS:field_info = Settings.model_fields[key]diff --git a/tests/unit/app_server/test_settings_api.py b/tests/unit/app_server/test_settings_api.pyindex 6549f77aeb..d4e7cf9b8c 100644--- a/tests/unit/app_server/test_settings_api.py+++ b/tests/unit/app_server/test_settings_api.py@@ -31,6 +31,16 @@ def _dump(settings: Settings) -> dict:return settings.model_dump(mode='json', context=_EXPOSE, exclude_unset=True)+def _dump_update(settings: Settings) -> dict:+ """Dump a settings update payload using diff-only nested keys."""+ payload = _dump(settings)+ if 'agent_settings' in payload:+ payload['agent_settings_diff'] = payload.pop('agent_settings')+ if 'conversation_settings' in payload:+ payload['conversation_settings_diff'] = payload.pop('conversation_settings')+ return payload++class MockUserAuth(UserAuth):"""Mock implementation of UserAuth for testing."""@@ -162,7 +172,7 @@ async def test_settings_api_endpoints(test_client):)# Make the POST request to store settings (V1 endpoint)- response = test_client.post('/api/v1/settings', json=_dump(settings))+ response = test_client.post('/api/v1/settings', json=_dump_update(settings))# We're not checking the exact response, just that it doesn't errorassert response.status_code == 200@@ -204,13 +214,30 @@ async def test_settings_api_endpoints(test_client):assert response.json()['agent_settings']['llm']['timeout'] == 123+async def test_store_settings_rejects_legacy_nested_payload_keys(test_client):+ response = test_client.post(+ '/api/v1/settings',+ json={+ 'agent_settings': {'llm': {'model': 'legacy-model'}},+ 'conversation_settings': {'max_iterations': 5},+ },+ )++ assert response.status_code == 422+ assert response.json() == {+ 'error': 'Use *_diff nested settings payloads instead of legacy keys',+ 'keys': ['agent_settings', 'conversation_settings'],+ }++@pytest.mark.asyncioasync def test_saving_settings_with_frozen_secrets_store(test_client):"""Regression: POSTing settings must not fail with `secrets_store`.See https://github.com/OpenHands/OpenHands/issues/13306."""- payload = _dump(+ payload = _dump_update(Settings(language='en',agent_settings=AgentSettings(llm=LLM(model='gpt-4')),@@ -227,7 +254,7 @@ async def test_search_api_key_explicit_clear(test_client):"""Explicit empty search_api_key payloads should clear the stored secret."""response = test_client.post('/api/v1/settings',- json=_dump(+ json=_dump_update(Settings(search_api_key='initial-secret-key',agent_settings=AgentSettings(llm=LLM(model='gpt-4')),@@ -242,7 +269,7 @@ async def test_search_api_key_explicit_clear(test_client):response = test_client.post('/api/v1/settings',- json=_dump(+ json=_dump_update(Settings(search_api_key='',agent_settings=AgentSettings(llm=LLM(model='claude-3-opus')),@@ -262,7 +289,7 @@ async def test_disabled_skills_persistence(test_client):"""Test that disabled_skills can be saved and retrieved via the settings API."""response = test_client.post('/api/v1/settings',- json=_dump(+ json=_dump_update(Settings(disabled_skills=['skill_a', 'skill_b'],agent_settings=AgentSettings(llm=LLM(model='test-model')),diff --git a/tests/unit/storage/data_models/test_settings.py b/tests/unit/storage/data_models/test_settings.pyindex b202861eb2..687199ca9d 100644--- a/tests/unit/storage/data_models/test_settings.py+++ b/tests/unit/storage/data_models/test_settings.py@@ -1,6 +1,7 @@import warningsfrom unittest.mock import patch+import pytestfrom fastmcp.mcp_config import MCPConfigfrom pydantic import SecretStr@@ -112,7 +113,7 @@ def test_settings_update_deep_merges_agent_settings():),)- settings.update({'agent_settings': {'condenser': {'max_size': 300}}})+ settings.update({'agent_settings_diff': {'condenser': {'max_size': 300}}})assert settings.agent_settings.llm.model == 'existing-model'assert settings.agent_settings.llm.api_key.get_secret_value() == 'existing-key'@@ -205,7 +206,7 @@ def test_settings_update_mcp_config():settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'mcp_config': {'mcpServers': {'custom': {@@ -242,7 +243,7 @@ def test_settings_update_replaces_existing_mcp_servers():settings.update({- 'agent_settings': {+ 'agent_settings_diff': {'mcp_config': {'mcpServers': {'fresh': {@@ -276,7 +277,7 @@ def test_settings_update_can_clear_mcp_config():))- settings.update({'agent_settings': {'mcp_config': None}})+ settings.update({'agent_settings_diff': {'mcp_config': None}})assert settings.agent_settings.mcp_config is None@@ -286,11 +287,11 @@ def test_settings_update_batch():settings.update({'language': 'fr',- 'agent_settings': {+ 'agent_settings_diff': {'agent': 'TestAgent','llm': {'model': 'new-model', 'api_key': 'new-key'},},- 'conversation_settings': {+ 'conversation_settings_diff': {'max_iterations': 200,},}@@ -302,6 +303,33 @@ def test_settings_update_batch():assert settings.conversation_settings.max_iterations == 200+def test_settings_update_batch_accepts_diff_keys():+ settings = Settings()+ settings.update(+ {+ 'agent_settings_diff': {+ 'agent': 'DiffAgent',+ 'llm': {'model': 'diff-model', 'api_key': 'diff-key'},+ },+ 'conversation_settings_diff': {+ 'max_iterations': 123,+ },+ }+ )++ assert settings.agent_settings.agent == 'DiffAgent'+ assert settings.agent_settings.llm.model == 'diff-model'+ assert settings.agent_settings.llm.api_key.get_secret_value() == 'diff-key'+ assert settings.conversation_settings.max_iterations == 123+++def test_settings_update_rejects_legacy_nested_keys():+ settings = Settings()++ with pytest.raises(ValueError, match=r'Use \*_diff nested settings payloads'):+ settings.update({'agent_settings': {'agent': 'LegacyAgent'}})++def test_settings_no_pydantic_frozen_field_warning():"""Test that Settings model does not trigger Pydantic UnsupportedFieldAttributeWarning."""with warnings.catch_warnings(record=True) as w: