Skip to content

🙌 OpenHands: AI-Driven Development

fix(enterprise): return agent-settings union instead of coercing ACP→OpenHands (#14675)

simonrosenberg5a3d1a484408
diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.py
index 4d264579ec..e03caf3c7a 100644
--- a/enterprise/server/routes/org_models.py
+++ b/enterprise/server/routes/org_models.py
@@ -19,26 +19,11 @@ from openhands.app_server.settings.settings_models import (
_load_persisted_conversation_settings,
)
from openhands.app_server.utils.llm import MASKED_API_KEY, resolve_llm_base_url
-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.
-
- Routes the raw payload through the shared SDK loader so any schema
- migrations registered with the SDK are applied first. Older rows carry
- the legacy ``agent_kind: 'llm'`` discriminator from the pre-rename SDK;
- force ``'openhands'`` after migration 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).
- """
- loaded = _load_persisted_agent_settings(raw or {})
- payload = loaded.model_dump(mode='json', context={'expose_secrets': True})
- payload['agent_kind'] = 'openhands'
- return OpenHandsAgentSettings.model_validate(payload)
+from openhands.sdk.settings import (
+ AgentSettingsConfig,
+ ConversationSettings,
+ OpenHandsAgentSettings,
+)
class OrgCreationError(Exception):
@@ -188,9 +173,7 @@ class OrgResponse(BaseModel):
sandbox_base_container_image: str | None = None
sandbox_runtime_container_image: str | None = None
org_version: int = 0
- agent_settings: OpenHandsAgentSettings = Field(
- default_factory=OpenHandsAgentSettings
- )
+ agent_settings: AgentSettingsConfig = Field(default_factory=OpenHandsAgentSettings)
conversation_settings: ConversationSettings = Field(
default_factory=ConversationSettings
)
@@ -220,7 +203,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=_validate_persisted_agent_settings(org.agent_settings),
+ agent_settings=_load_persisted_agent_settings(org.agent_settings),
conversation_settings=_load_persisted_conversation_settings(
org.conversation_settings
),
@@ -404,9 +387,7 @@ class OrgUpdate(BaseModel):
class OrgDefaultsSettingsResponse(BaseModel):
"""Response model for organization default settings."""
- agent_settings: OpenHandsAgentSettings = Field(
- default_factory=OpenHandsAgentSettings
- )
+ agent_settings: AgentSettingsConfig = Field(default_factory=OpenHandsAgentSettings)
conversation_settings: ConversationSettings = Field(
default_factory=ConversationSettings
)
@@ -437,7 +418,7 @@ class OrgDefaultsSettingsResponse(BaseModel):
``org_member.agent_settings_diff`` and this response always carry
the same value.
"""
- agent_settings = _validate_persisted_agent_settings(org.agent_settings)
+ agent_settings = _load_persisted_agent_settings(org.agent_settings)
cls._denormalize_llm_for_response(agent_settings)
return cls(
agent_settings=agent_settings,
@@ -449,7 +430,7 @@ class OrgDefaultsSettingsResponse(BaseModel):
)
@staticmethod
- def _denormalize_llm_for_response(agent_settings: OpenHandsAgentSettings) -> None:
+ def _denormalize_llm_for_response(agent_settings: AgentSettingsConfig) -> None:
"""Rewrite ``agent_settings.llm`` in-place for UI consumption.
* ``litellm_proxy/X`` → ``openhands/X`` so the basic-view provider
diff --git a/enterprise/server/routes/org_profiles.py b/enterprise/server/routes/org_profiles.py
index 90fc58bc60..398fa3e198 100644
--- a/enterprise/server/routes/org_profiles.py
+++ b/enterprise/server/routes/org_profiles.py
@@ -17,10 +17,7 @@ from uuid import UUID
from fastapi import APIRouter, Body, Depends, HTTPException, Path, status
from pydantic import BaseModel, Field, ValidationError
from server.constants import LITE_LLM_API_URL
-from server.routes.org_models import (
- OrgNotFoundError,
- _validate_persisted_agent_settings,
-)
+from server.routes.org_models import OrgNotFoundError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from storage.database import a_session_maker
@@ -35,6 +32,9 @@ from openhands.app_server.settings.llm_profiles import (
ProfileNotFoundError,
StrictLLM,
)
+from openhands.app_server.settings.settings_models import (
+ _load_persisted_agent_settings,
+)
from openhands.app_server.utils.llm import MASKED_API_KEY, is_openhands_model
from openhands.app_server.utils.logger import openhands_logger as logger
@@ -220,7 +220,7 @@ async def save_profile(
# Snapshot current org LLM settings. Route through the persisted
# loader so legacy/canonical ``agent_kind`` discriminator values
# ('llm' vs 'openhands') both validate.
- agent_settings = _validate_persisted_agent_settings(org.agent_settings)
+ agent_settings = _load_persisted_agent_settings(org.agent_settings)
profiles.save(
name, agent_settings.llm, include_secrets=request.include_secrets
)
diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.py
index 6adc7819aa..775a38ac28 100644
--- a/enterprise/storage/org_store.py
+++ b/enterprise/storage/org_store.py
@@ -35,7 +35,12 @@ from openhands.app_server.settings.settings_models import (
from openhands.app_server.utils.jsonpatch_compat import deep_merge
from openhands.app_server.utils.llm import is_openhands_model
from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.sdk.settings import ConversationSettings, OpenHandsAgentSettings
+from openhands.sdk.settings import (
+ AgentSettingsConfig,
+ ConversationSettings,
+ OpenHandsAgentSettings,
+ validate_agent_settings,
+)
_ORG_SETTINGS_EXCLUDED_FIELDS = {
'id',
@@ -56,16 +61,13 @@ class OrgStore:
"""Store for managing organizations."""
@staticmethod
- def get_agent_settings_from_org(org: Org) -> OpenHandsAgentSettings:
- # Apply persisted-settings migrations via the shared SDK loader,
- # then coerce the legacy ``agent_kind: 'llm'`` discriminator onto
- # the canonical class. Some saved entries still carry that
- # pre-rename shape and would otherwise validate as
- # ``LLMAgentSettings``.
- loaded = _load_persisted_agent_settings(dict(org.agent_settings))
- payload = loaded.model_dump(mode='json', context={'expose_secrets': True})
- payload['agent_kind'] = 'openhands'
- return OpenHandsAgentSettings.model_validate(payload)
+ def get_agent_settings_from_org(org: Org) -> AgentSettingsConfig:
+ # Route through the shared SDK loader: it applies persisted-settings
+ # migrations (incl. the legacy ``agent_kind: 'llm'`` -> ``'openhands'``
+ # rename) and returns the actual variant. ACP settings are returned as
+ # ``ACPAgentSettings``, not coerced into the OpenHands shape — that
+ # coercion 500s on ACP's nullable ``agent_context``.
+ return _load_persisted_agent_settings(dict(org.agent_settings))
@staticmethod
def get_conversation_settings_from_org(org: Org) -> ConversationSettings:
@@ -259,22 +261,31 @@ class OrgStore:
current_settings: dict[str, Any],
settings_diff: dict[str, Any],
settings_type: type[OpenHandsAgentSettings] | type[ConversationSettings],
- ) -> OpenHandsAgentSettings | ConversationSettings:
+ ) -> AgentSettingsConfig | ConversationSettings:
"""Deep-merge a sparse settings diff and validate the merged result.
- The persisted base is routed through the SDK ``from_persisted`` loader
- first so any registered schema migrations are applied before the diff
- is merged. Agent settings additionally coerce the legacy
- ``agent_kind: 'llm'`` discriminator onto the canonical class.
+ The persisted base is routed through the SDK loader first so any
+ registered schema migrations are applied before the diff is merged.
+ Agent settings are validated against the discriminated union, so the
+ result is the correct variant (OpenHands or ACP) rather than a coerced
+ OpenHands shape.
"""
if settings_type is OpenHandsAgentSettings:
base_settings = _load_persisted_agent_settings(current_settings or {})
- merged_settings = deep_merge(
- base_settings.model_dump(mode='json', context={'expose_secrets': True}),
- settings_diff,
- )
- merged_settings['agent_kind'] = 'openhands'
- return OpenHandsAgentSettings.model_validate(merged_settings)
+ new_kind = settings_diff.get('agent_kind')
+ if new_kind and new_kind != base_settings.agent_kind:
+ # Variant switch: deep-merging the new kind's fields onto the
+ # outgoing kind's dump yields an invalid mongrel. Start from a
+ # fresh base and let the diff populate it.
+ merged_settings = {'agent_kind': new_kind, **settings_diff}
+ else:
+ merged_settings = deep_merge(
+ base_settings.model_dump(
+ mode='json', context={'expose_secrets': True}
+ ),
+ settings_diff,
+ )
+ return validate_agent_settings(merged_settings)
base_settings = _load_persisted_conversation_settings(current_settings) # type: ignore[assignment]
merged_settings = deep_merge(
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 da8846f138..3648eda83f 100644
--- a/enterprise/tests/unit/server/routes/test_org_defaults_settings.py
+++ b/enterprise/tests/unit/server/routes/test_org_defaults_settings.py
@@ -11,6 +11,8 @@ from server.routes.org_models import (
)
from storage.org import Org
+from openhands.sdk.settings import ACPAgentSettings
+
def test_org_update_keeps_sparse_diff_dicts():
"""OrgUpdate should preserve sparse org-default diffs as dictionaries."""
@@ -115,6 +117,31 @@ def test_from_org_validates_persisted_openhands_agent_kind():
assert response.agent_settings.llm.model == 'openhands/claude'
+def test_from_org_preserves_acp_agent_settings_without_500():
+ """GIVEN: An org on ACP — persisted ``agent_kind: 'acp'`` with a null
+ ``agent_context`` (the exact shape behind the /api/organizations 500s).
+ WHEN: ``OrgDefaultsSettingsResponse.from_org`` serializes the org.
+ THEN: It returns the ``ACPAgentSettings`` variant instead of force-casting
+ to ``OpenHandsAgentSettings`` (which 500'd on the non-nullable
+ ``agent_context``).
+ """
+ org = MagicMock(spec=Org)
+ org.agent_settings = {
+ 'agent_kind': 'acp',
+ 'acp_server': 'claude-code',
+ 'llm': {'model': 'litellm_proxy/anthropic/claude-sonnet-4'},
+ }
+ org.conversation_settings = {}
+ org.llm_api_key = None
+ org.search_api_key = None
+
+ response = OrgDefaultsSettingsResponse.from_org(org)
+
+ assert isinstance(response.agent_settings, ACPAgentSettings)
+ assert response.agent_settings.agent_kind == 'acp'
+ assert response.agent_settings.agent_context is None
+
+
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/test_org_store.py b/enterprise/tests/unit/test_org_store.py
index f7be58c4d9..f531c8dbef 100644
--- a/enterprise/tests/unit/test_org_store.py
+++ b/enterprise/tests/unit/test_org_store.py
@@ -14,7 +14,11 @@ from storage.role import Role
from storage.user import User
from openhands.app_server.settings.settings_models import Settings
-from openhands.sdk.settings import ConversationSettings, OpenHandsAgentSettings
+from openhands.sdk.settings import (
+ ACPAgentSettings,
+ ConversationSettings,
+ OpenHandsAgentSettings,
+)
@pytest.fixture
@@ -159,6 +163,41 @@ def test_get_org_settings_from_org_use_persisted_loaders():
conversation_loader.assert_called_once_with({'legacy': True})
+def test_get_agent_settings_from_org_preserves_acp_variant():
+ """Regression: ACP org settings (``agent_kind: 'acp'``, null
+ ``agent_context``) must load as ``ACPAgentSettings`` rather than being
+ coerced into ``OpenHandsAgentSettings`` — that coercion 500'd on the
+ non-nullable ``agent_context``.
+ """
+ org = MagicMock(spec=Org)
+ org.agent_settings = {
+ 'agent_kind': 'acp',
+ 'acp_server': 'claude-code',
+ 'llm': {'model': 'litellm_proxy/anthropic/claude-sonnet-4'},
+ }
+
+ settings = OrgStore.get_agent_settings_from_org(org)
+
+ assert isinstance(settings, ACPAgentSettings)
+ assert settings.agent_kind == 'acp'
+ assert settings.agent_context is None
+
+
+def test_merge_and_validate_settings_switches_variant_without_mongrel():
+ """Switching ``agent_kind`` replaces the variant instead of deep-merging
+ incompatible fields across the discriminated-union boundary (which would
+ produce an invalid ``llm``-plus-``acp_server`` mongrel).
+ """
+ merged = OrgStore._merge_and_validate_settings(
+ {'agent_kind': 'openhands', 'llm': {'model': 'gpt'}},
+ {'agent_kind': 'acp', 'acp_server': 'claude-code'},
+ OpenHandsAgentSettings,
+ )
+
+ assert isinstance(merged, ACPAgentSettings)
+ assert merged.acp_server == 'claude-code'
+
+
@pytest.mark.asyncio
async def test_update_org_not_found(async_session_maker):
# Test updating org that doesn't exist
diff --git a/openhands/app_server/settings/settings_models.py b/openhands/app_server/settings/settings_models.py
index 687a79438f..20e3d624b1 100644
--- a/openhands/app_server/settings/settings_models.py
+++ b/openhands/app_server/settings/settings_models.py
@@ -67,8 +67,19 @@ def _load_persisted_agent_settings(
Routes the raw payload through :func:`validate_agent_settings` so any
schema migrations registered with the SDK are applied before validation
against the discriminated :data:`AgentSettingsConfig` union.
+
+ The legacy ``agent_kind: 'llm'`` tag (pre-rename, field-compatible with
+ ``openhands``) is normalized to ``'openhands'`` first. The SDK migration
+ only rewrites it while advancing ``schema_version``, so an ``'llm'`` payload
+ already at the current version would otherwise validate as the deprecated
+ ``LLMAgentSettings``. Doing it here keeps every read on the canonical
+ ``{openhands, acp}`` variants, without the cross-variant coercion that 500'd
+ ACP settings (``agent_kind: 'acp'`` is left untouched).
"""
- return validate_agent_settings(data or {})
+ payload = data or {}
+ if isinstance(payload, dict) and payload.get('agent_kind') == 'llm':
+ payload = {**payload, 'agent_kind': 'openhands'}
+ return validate_agent_settings(payload)
def _load_persisted_conversation_settings(data: Any) -> ConversationSettings:
diff --git a/tests/unit/app_server/test_settings_agent_kind_switch.py b/tests/unit/app_server/test_settings_agent_kind_switch.py
index a7ca31f771..fd00d44493 100644
--- a/tests/unit/app_server/test_settings_agent_kind_switch.py
+++ b/tests/unit/app_server/test_settings_agent_kind_switch.py
@@ -13,7 +13,11 @@ is tracked as a follow-up.
from __future__ import annotations
-from openhands.app_server.settings.settings_models import Settings
+from openhands.app_server.settings.settings_models import (
+ Settings,
+ _load_persisted_agent_settings,
+)
+from openhands.sdk.settings.model import AGENT_SETTINGS_SCHEMA_VERSION
def _set_acp(
@@ -99,3 +103,44 @@ def test_replace_mcp_config_in_kind_switch():
s.update(_set_openhands(mcp_config={'mcpServers': {'foo': {'command': 'foo-bin'}}}))
assert s.agent_settings.mcp_config is not None
assert 'foo' in s.agent_settings.mcp_config.mcpServers
+
+
+def test_loader_normalizes_legacy_llm_tag_at_current_schema_version():
+ """A persisted ``agent_kind: 'llm'`` row already at the current
+ ``schema_version`` must read back as ``openhands``.
+
+ The SDK's ``llm -> openhands`` rename only fires while advancing the
+ schema version, so an ``'llm'`` payload already at the current version is
+ not migrated and would otherwise validate as the deprecated
+ ``LLMAgentSettings`` (``agent_kind == 'llm'``). The loader normalizes it so
+ every read stays on the canonical ``{openhands, acp}`` variants — this is
+ the one legitimate job the deleted force-cast used to do.
+ """
+ loaded = _load_persisted_agent_settings(
+ {
+ 'agent_kind': 'llm',
+ 'schema_version': AGENT_SETTINGS_SCHEMA_VERSION,
+ 'llm': {'model': 'anthropic/claude-sonnet-4-5'},
+ }
+ )
+
+ assert loaded.agent_kind == 'openhands'
+ assert loaded.llm.model == 'anthropic/claude-sonnet-4-5'
+
+
+def test_loader_preserves_acp_variant_without_coercion():
+ """The loader must leave ``agent_kind: 'acp'`` alone — the ``llm``
+ normalization must not regress into the cross-variant coercion that 500'd
+ ACP settings (``ACPAgentSettings.agent_context`` is nullable; the OpenHands
+ shape rejects ``None``).
+ """
+ loaded = _load_persisted_agent_settings(
+ {
+ 'agent_kind': 'acp',
+ 'acp_server': 'claude-code',
+ 'llm': {'model': 'litellm_proxy/anthropic/claude-sonnet-4'},
+ }
+ )
+
+ assert loaded.agent_kind == 'acp'
+ assert loaded.agent_context is None