Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: handle persisted agent_kind='openhands' in org responses (#14306)

Hiep Lea848ba1bccfb
diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.py
index 610a328605..3410701ab4 100644
--- a/enterprise/server/routes/org_models.py
+++ b/enterprise/server/routes/org_models.py
@@ -15,7 +15,22 @@ from storage.org_member import OrgMember
from storage.role import Role
from openhands.app_server.utils.llm import MASKED_API_KEY, resolve_llm_base_url
-from openhands.sdk.settings import AgentSettings, ConversationSettings
+from openhands.sdk.settings import ConversationSettings, OpenHandsAgentSettings
+
+
+def _validate_persisted_agent_settings(
+ raw: dict[str, Any] | None,
+) -> OpenHandsAgentSettings:
+ """Validate persisted ``org.agent_settings`` against the canonical schema.
+
+ Older rows carry the legacy ``agent_kind: 'llm'`` discriminator from the
+ pre-rename SDK; force ``'openhands'`` so the canonical class accepts both
+ shapes. Mirrors :func:`OrgStore.get_agent_settings_from_org` β€” kept inline
+ to avoid a circular import (``org_store`` already imports from this module).
+ """
+ kwargs = dict(raw) if raw else {}
+ kwargs['agent_kind'] = 'openhands'
+ return OpenHandsAgentSettings.model_validate(kwargs)
class OrgCreationError(Exception):
@@ -155,7 +170,9 @@ class OrgResponse(BaseModel):
sandbox_base_container_image: str | None = None
sandbox_runtime_container_image: str | None = None
org_version: int = 0
- agent_settings: AgentSettings = Field(default_factory=AgentSettings)
+ agent_settings: OpenHandsAgentSettings = Field(
+ default_factory=OpenHandsAgentSettings
+ )
conversation_settings: ConversationSettings = Field(
default_factory=ConversationSettings
)
@@ -185,9 +202,7 @@ class OrgResponse(BaseModel):
sandbox_base_container_image=org.sandbox_base_container_image,
sandbox_runtime_container_image=org.sandbox_runtime_container_image,
org_version=org.org_version if org.org_version is not None else 0,
- agent_settings=AgentSettings.model_validate(
- dict(org.agent_settings) if org.agent_settings else {}
- ),
+ agent_settings=_validate_persisted_agent_settings(org.agent_settings),
conversation_settings=ConversationSettings.model_validate(
dict(org.conversation_settings) if org.conversation_settings else {}
),
@@ -371,7 +386,9 @@ class OrgUpdate(BaseModel):
class OrgDefaultsSettingsResponse(BaseModel):
"""Response model for organization default settings."""
- agent_settings: AgentSettings = Field(default_factory=AgentSettings)
+ agent_settings: OpenHandsAgentSettings = Field(
+ default_factory=OpenHandsAgentSettings
+ )
conversation_settings: ConversationSettings = Field(
default_factory=ConversationSettings
)
@@ -402,9 +419,7 @@ class OrgDefaultsSettingsResponse(BaseModel):
``org_member.agent_settings_diff`` and this response always carry
the same value.
"""
- agent_settings = AgentSettings.model_validate(
- dict(org.agent_settings) if org.agent_settings else {}
- )
+ agent_settings = _validate_persisted_agent_settings(org.agent_settings)
cls._denormalize_llm_for_response(agent_settings)
return cls(
agent_settings=agent_settings,
@@ -416,7 +431,7 @@ class OrgDefaultsSettingsResponse(BaseModel):
)
@staticmethod
- def _denormalize_llm_for_response(agent_settings: AgentSettings) -> None:
+ def _denormalize_llm_for_response(agent_settings: OpenHandsAgentSettings) -> None:
"""Rewrite ``agent_settings.llm`` in-place for UI consumption.
* ``litellm_proxy/X`` β†’ ``openhands/X`` so the basic-view provider
diff --git a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py b/enterprise/tests/unit/server/routes/test_org_defaults_settings.py
index f3861639a6..da8846f138 100644
--- a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py
+++ b/enterprise/tests/unit/server/routes/test_org_defaults_settings.py
@@ -87,6 +87,34 @@ def test_normalize_agent_settings_fills_base_url_for_all_providers():
assert 'anthropic.com' in anthropic_base
+def test_from_org_validates_persisted_openhands_agent_kind():
+ """GIVEN: An org row whose persisted ``agent_settings`` carry the
+ canonical ``agent_kind: 'openhands'`` discriminator (the exact shape
+ from the 500-error log)
+ WHEN: ``OrgDefaultsSettingsResponse.from_org`` serializes the org
+ THEN: The response is built without a Pydantic literal-mismatch error
+ and exposes the expected canonical agent kind and llm model.
+ """
+ # Arrange
+ org = MagicMock(spec=Org)
+ org.agent_settings = {
+ 'schema_version': 1,
+ 'agent': 'CodeActAgent',
+ 'agent_kind': 'openhands',
+ 'llm': {'model': 'openhands/claude', 'base_url': LITE_LLM_API_URL},
+ }
+ org.conversation_settings = {}
+ org.llm_api_key = None
+ org.search_api_key = None
+
+ # Act
+ response = OrgDefaultsSettingsResponse.from_org(org)
+
+ # Assert
+ assert response.agent_settings.agent_kind == 'openhands'
+ assert response.agent_settings.llm.model == 'openhands/claude'
+
+
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)
diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.py
index 3273ef1286..fb6caed331 100644
--- a/enterprise/tests/unit/server/routes/test_orgs.py
+++ b/enterprise/tests/unit/server/routes/test_orgs.py
@@ -45,7 +45,7 @@ from server.routes.orgs import (
from storage.org import Org
from openhands.app_server.user_auth import get_user_id
-from openhands.sdk.settings import AgentSettings, ConversationSettings
+from openhands.sdk.settings import ConversationSettings, OpenHandsAgentSettings
# Test user ID constant (must be a valid UUID string)
TEST_USER_ID = str(uuid.uuid4())
@@ -552,6 +552,63 @@ async def test_list_user_orgs_success(mock_app_list):
assert response_data['items'][0]['credits'] is None
+ 'persisted_agent_settings',
+ [
+ {
+ 'agent_kind': 'openhands',
+ 'llm': {'model': 'anthropic/claude-3-haiku-20240307'},
+ },
+ {'agent_kind': 'llm', 'llm': {'model': 'anthropic/claude-3-haiku-20240307'}},
+ {'llm': {'model': 'anthropic/claude-3-haiku-20240307'}},
+ ],
+ ids=['agent_kind_openhands', 'agent_kind_llm_legacy', 'no_agent_kind'],
+)
+async def test_list_user_orgs_handles_persisted_agent_kind_variants(
+ mock_app_list, persisted_agent_settings
+):
+ """GIVEN: An org row whose persisted ``agent_settings`` carries any of the
+ three discriminator shapes seen in production (current ``'openhands'``,
+ legacy ``'llm'``, or no ``agent_kind`` at all)
+ WHEN: GET /api/organizations is called
+ THEN: The endpoint returns 200 and serializes the org without raising
+ a Pydantic literal-mismatch ``ValidationError``.
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ mock_org = Org(
+ id=org_id,
+ name='Org',
+ contact_name='Owner',
+ contact_email='[email protected]',
+ agent_settings=persisted_agent_settings,
+ )
+ mock_user = MagicMock()
+ mock_user.current_org_id = org_id
+
+ with (
+ patch(
+ 'server.routes.orgs.UserStore.get_user_by_id',
+ AsyncMock(return_value=mock_user),
+ ),
+ patch(
+ 'server.routes.orgs.OrgService.get_user_orgs_paginated',
+ AsyncMock(return_value=([mock_org], None)),
+ ),
+ ):
+ # Act
+ response = TestClient(mock_app_list).get('/api/organizations')
+
+ # Assert
+ assert response.status_code == status.HTTP_200_OK
+ items = response.json()['items']
+ assert (
+ items[0]['agent_settings']['llm']['model']
+ == 'anthropic/claude-3-haiku-20240307'
+ )
+
+
@pytest.mark.asyncio
async def test_list_user_orgs_returns_current_org_id(mock_app_list):
"""
@@ -1110,7 +1167,7 @@ async def test_get_org_defaults_settings_success():
"""
org_id = uuid.uuid4()
mock_org = MagicMock(spec=Org)
- mock_org.agent_settings = AgentSettings(
+ mock_org.agent_settings = OpenHandsAgentSettings(
agent='CodeActAgent',
llm={'model': 'openhands/claude-3', 'base_url': 'https://proxy.example'},
)
@@ -1138,7 +1195,7 @@ async def test_update_org_defaults_settings_forwards_through_org_service():
"""
org_id = uuid.uuid4()
updated_org = MagicMock(spec=Org)
- updated_org.agent_settings = AgentSettings(
+ updated_org.agent_settings = OpenHandsAgentSettings(
llm={
'model': 'openhands/claude-3.5-sonnet',
'base_url': 'https://proxy.example',