π OpenHands: AI-Driven Development
feat(saas): seed Default LLM profile from legacy config on profiles upgrade (#14586)
Vasco Schiavo1e32eeefb62e
diff --git a/enterprise/storage/saas_settings_store.py b/enterprise/storage/saas_settings_store.pyindex fb691383c0..7d3f90844e 100644--- a/enterprise/storage/saas_settings_store.py+++ b/enterprise/storage/saas_settings_store.py@@ -22,6 +22,7 @@ from storage.user import Userfrom storage.user_settings import UserSettingsfrom storage.user_store import UserStore+from openhands.app_server.settings.llm_profiles import LLMProfilesfrom openhands.app_server.settings.settings_models import Settingsfrom openhands.app_server.settings.settings_store import SettingsStorefrom openhands.app_server.utils.jsonpatch_compat import (@@ -220,6 +221,7 @@ class SaasSettingsStore(SettingsStore):# landing on an empty profiles UI (mirrors the OSS FileSettingsStore).# Covers both pre-migration rows (llm_profiles is None) and# already-migrated orgs whose profiles map is empty.+ seeded_default = Falseif not (kwargs.get('llm_profiles') or {}).get('profiles'):legacy_llm = merged_agent_settings.get('llm')if isinstance(legacy_llm, dict) and legacy_llm.get('model'):@@ -227,12 +229,63 @@ class SaasSettingsStore(SettingsStore):'profiles': {'Default': dict(legacy_llm)},'active': 'Default',}+ seeded_default = Trueelse:# No legacy LLM to seed; drop a None value so the non-nullable# Settings.llm_profiles falls back to its default_factory.kwargs.pop('llm_profiles', None)- return Settings(**kwargs)+ settings = Settings(**kwargs)++ # The seed above is in-memory only. Persist it onto the org row so the+ # legacy LLM becomes a real stored profile β otherwise the profiles+ # management API (server/routes/org_profiles.py, which reads+ # org.llm_profiles directly) would still see an empty list and the+ # user's previous model would never land "inside the profiles".+ # Persist is best-effort: a transient DB failure here must not block+ # returning settings the caller already has in memory.+ if seeded_default:+ try:+ await self._persist_seeded_default_profile(+ org_id, settings.llm_profiles+ )+ except Exception:+ logger.warning(+ 'Failed to persist seeded Default profile for org %s',+ org_id,+ exc_info=True,+ )++ return settings++ async def _persist_seeded_default_profile(+ self, org_id: UUID, llm_profiles: LLMProfiles+ ) -> None:+ """Backfill the seeded ``Default`` profile onto ``org.llm_profiles``.++ Runs once per org during the pre-llm_profiles β llm_profiles upgrade:+ ``load()`` seeds the profile in memory, and this writes it back so it+ becomes a real stored profile that the org-profiles management API can+ list and mutate. Re-checks emptiness under a row lock so a concurrent+ ``load()`` doesn't double-seed and so a profile a member just created+ through the management API is never clobbered.+ """+ serialized = llm_profiles.model_dump(+ mode='json', context={'expose_secrets': True}+ )+ async with a_session_maker() as session:+ result = await session.execute(+ select(Org).filter(Org.id == org_id).with_for_update()+ )+ org = result.scalars().first()+ if org is None:+ return+ # Only seed while the column is still empty β another request may+ # have populated it between this load() and acquiring the lock.+ if (org.llm_profiles or {}).get('profiles'):+ return+ org.llm_profiles = serialized+ await session.commit()async def store(self, item: Settings):async with a_session_maker() as session:diff --git a/enterprise/tests/unit/test_saas_settings_store.py b/enterprise/tests/unit/test_saas_settings_store.pyindex f6d2eab079..fee832f958 100644--- a/enterprise/tests/unit/test_saas_settings_store.py+++ b/enterprise/tests/unit/test_saas_settings_store.py@@ -945,6 +945,65 @@ async def test_load_with_null_or_empty_llm_profiles_seeds_default_profile(assert default.model == 'anthropic/claude-sonnet-4-5-20250929'+async def test_load_persists_seeded_default_profile_onto_org(+ async_session_maker, org_with_multiple_members_fixture+):+ """The seeded Default profile must be written back to org.llm_profiles.++ The seed is otherwise in-memory only, so the org-profiles management API+ (which reads org.llm_profiles directly) would still see an empty list.+ load() backfills it once so the user's last LLM becomes a real stored+ profile on first use of LLM profiles.+ """+ from sqlalchemy import select, update+ from storage.org import Org++ fixture = org_with_multiple_members_fixture+ admin_user_id = fixture['admin_user_id']+ org_id = fixture['org_id']+ admin_store = SaasSettingsStore(str(admin_user_id))++ seed_settings = _make_settings(+ model='anthropic/claude-sonnet-4-5-20250929',+ api_key='seed-key',+ base_url='https://api.anthropic.com/v1',+ )+ with patch('storage.saas_settings_store.a_session_maker', async_session_maker):+ await admin_store.store(seed_settings)++ # Simulate a pre-migration org: no profiles stored yet.+ async with async_session_maker() as session:+ await session.execute(+ update(Org).where(Org.id == org_id).values(llm_profiles=None)+ )+ await session.commit()++ with (+ patch('storage.saas_settings_store.a_session_maker', async_session_maker),+ patch('storage.user_store.a_session_maker', async_session_maker),+ patch('storage.org_store.a_session_maker', async_session_maker),+ ):+ await admin_store.load()++ async with async_session_maker() as session:+ org = (+ (await session.execute(select(Org).where(Org.id == org_id)))+ .scalars()+ .first()+ )++ assert org.llm_profiles is not None+ assert set(org.llm_profiles['profiles'].keys()) == {'Default'}+ assert org.llm_profiles['active'] == 'Default'+ persisted_default = org.llm_profiles['profiles']['Default']+ assert persisted_default['model'] == 'anthropic/claude-sonnet-4-5-20250929'+ assert persisted_default['base_url'] == 'https://api.anthropic.com/v1'+ # API key from the legacy config must survive the round-trip so the user+ # doesn't have to re-enter it after the profiles upgrade.+ assert persisted_default['api_key'] == 'seed-key'++@pytest.mark.asyncioasync def test_llm_profiles_are_encrypted_at_rest(async_session_maker, org_with_multiple_members_fixture