Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(enterprise): Agent Profiles on the cloud/SaaS backend (#15044) (#15060)

simonrosenbergc0c64bbbc667
diff --git a/enterprise/dev_config/python/.pre-commit-config.yaml b/enterprise/dev_config/python/.pre-commit-config.yaml
index 5c11038fcd..faa3fb04db 100644
--- a/enterprise/dev_config/python/.pre-commit-config.yaml
+++ b/enterprise/dev_config/python/.pre-commit-config.yaml
@@ -50,8 +50,8 @@ repos:
- ./
- stripe==11.5.0
- pygithub==2.6.1
- - openhands-sdk==1.31.2
- - openhands-tools==1.31.2
+ - openhands-sdk==1.33.0
+ - openhands-tools==1.33.0
- sqlalchemy>=2.0
# Use -p (package) to avoid dual module name conflict when using MYPYPATH
# MYPYPATH=enterprise allows resolving bare imports like "from integrations.xxx"
diff --git a/enterprise/integrations/resolver_context.py b/enterprise/integrations/resolver_context.py
index 798622e955..1cc03ed5c9 100644
--- a/enterprise/integrations/resolver_context.py
+++ b/enterprise/integrations/resolver_context.py
@@ -36,8 +36,16 @@ class ResolverUserContext(UserContext):
async def get_user_email(self) -> str | None:
return await self.saas_user_auth.get_user_email()
- async def get_user_info(self) -> UserInfo:
- user_settings = await self.saas_user_auth.get_user_settings()
+ async def get_user_info(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> UserInfo:
+ user_settings = await self.saas_user_auth.get_user_settings(
+ resolve_agent_profile=resolve_agent_profile,
+ override_agent_profile_id=override_agent_profile_id,
+ )
user_id = await self.saas_user_auth.get_user_id()
if user_settings:
return UserInfo(
diff --git a/enterprise/migrations/versions/132_add_agent_profiles.py b/enterprise/migrations/versions/132_add_agent_profiles.py
new file mode 100644
index 0000000000..3329c2b864
--- /dev/null
+++ b/enterprise/migrations/versions/132_add_agent_profiles.py
@@ -0,0 +1,49 @@
+"""Add agent_profiles to org and active_agent_profile_id to org_member.
+
+Agent Profiles (OpenHands/OpenHands#15044) are the named, reference-bearing
+launch specs one level up from LLM profiles. They are stored at the
+organization level exactly like ``org.llm_profiles``:
+
+- ``org.agent_profiles`` is an EncryptedJSON column (stored as String). Agent
+ profiles are reference-bearing and mostly secret-free, but the column is kept
+ encrypted for parity with ``llm_profiles`` and because ``skills[].mcp_tools``
+ env/headers ride in cleartext inside the encrypted blob (the column is the
+ at-rest boundary). Envelope: ``{profiles: {<id>: AgentProfile}, active}``.
+- ``org_member.active_agent_profile_id`` is the per-member pointer to the active
+ profile id β€” the sole launch authority β€” mirroring the per-member
+ ``_llm_api_key`` precedent.
+
+Data migration: no backfill. Existing rows read back with ``agent_profiles =
+NULL`` (treated as an empty collection) and ``active_agent_profile_id = NULL``
+(falls back to the legacy active-LLM materialization). No profile is
+auto-created: an org sees an empty list until someone with
+``EDIT_ORG_SETTINGS`` explicitly saves one, so no downtime or follow-up
+script is required.
+
+Revision ID: 132
+Revises: 131
+Create Date: 2026-06-30 00:00:00.000000
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = '132'
+down_revision: Union[str, None] = '131'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column('org', sa.Column('agent_profiles', sa.String(), nullable=True))
+ op.add_column(
+ 'org_member',
+ sa.Column('active_agent_profile_id', sa.String(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column('org_member', 'active_agent_profile_id')
+ op.drop_column('org', 'agent_profiles')
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index 4a61b3bbbf..fe1ca19672 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -34,6 +34,7 @@ from server.middleware import ( # noqa: E402
SetAuthCookieMiddleware,
)
from server.rate_limit import setup_rate_limit_handler # noqa: E402
+from server.routes.agent_profiles import router as agent_profiles_router # noqa: E402
from server.routes.analytics_events import analytics_events_router # noqa: E402
from server.routes.api_keys import api_router as api_keys_router # noqa: E402
from server.routes.auth import api_router, oauth_router # noqa: E402
@@ -167,6 +168,9 @@ if USER_PROVISIONING_ENABLED:
base_app.include_router(
org_profiles_router, prefix='/api/organizations'
) # Add routes for org LLM profiles
+base_app.include_router(
+ agent_profiles_router
+) # Add flat /api/agent-profiles routes for org Agent Profiles
base_app.include_router(
verified_models_router
) # Add routes for verified models management
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index f859ca504c..7fae2d3631 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -435,6 +435,20 @@ def require_permission(permission: Permission):
detail='User not authenticated',
)
+ # ``org_id`` is only trustworthy when the route actually declares an
+ # ``{org_id}`` path segment: FastAPI binds this parameter from the
+ # path in that case. Routes without that segment have no path source
+ # for it, so FastAPI silently falls back to binding it from an
+ # ordinary, client-controlled query string instead. Left unchecked, a
+ # caller could pass ``?org_id=<org-they-administer>`` to satisfy this
+ # permission check while the route handler itself operates on a
+ # *different* org (resolved separately from the ``X-Org-Id`` header
+ # via ``EFFECTIVE_ORG_ID``) -- a cross-org privilege escalation.
+ # Discard any such query-string value; routes with no path org_id
+ # always re-resolve the target org below instead.
+ if request.path_params.get('org_id') is None:
+ org_id = None
+
# Validate API key organization binding
api_key_org_id = await get_api_key_org_id_from_request(request)
if api_key_org_id is not None and org_id is not None:
diff --git a/enterprise/server/auth/saas_user_auth.py b/enterprise/server/auth/saas_user_auth.py
index bc01d10fa9..77dfd522ec 100644
--- a/enterprise/server/auth/saas_user_auth.py
+++ b/enterprise/server/auth/saas_user_auth.py
@@ -66,6 +66,7 @@ class SaasUserAuth(UserAuth):
settings_store: SaasSettingsStore | None = None
secrets_store: SaasSecretsStore | None = None
_settings: Settings | None = None
+ _resolved_settings: Settings | None = None
_secrets: Secrets | None = None
accepted_tos: bool | None = None
auth_type: AuthType = AuthType.COOKIE
@@ -114,6 +115,10 @@ class SaasUserAuth(UserAuth):
self.settings_store = None
self.secrets_store = None
self._settings = None
+ # Org-scoped like _settings: the resolved launch view carries the
+ # referenced LLM key + ref-filtered mcp_config of *this* org's active
+ # profile, so it must not survive a re-scope to another org.
+ self._resolved_settings = None
self._secrets = None
self.provider_tokens = None
self._org_id = None
@@ -418,7 +423,29 @@ class SaasUserAuth(UserAuth):
def get_auth_type(self) -> AuthType | None:
return self.auth_type
- async def get_user_settings(self) -> Settings | None:
+ async def get_user_settings(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> Settings | None:
+ if resolve_agent_profile or override_agent_profile_id is not None:
+ # Effective launch view (active Agent Profile resolved). Memoized
+ # separately from the persisted `_settings`; an explicit override
+ # is a one-off and is never memoized.
+ if override_agent_profile_id is None and self._resolved_settings:
+ return self._resolved_settings
+ settings_store = await self.get_user_settings_store()
+ settings = await settings_store.load(
+ resolve_agent_profile=True,
+ override_agent_profile_id=override_agent_profile_id,
+ )
+ if settings:
+ settings.email = await self.get_user_email()
+ settings.email_verified = self.email_verified
+ if override_agent_profile_id is None:
+ self._resolved_settings = settings
+ return settings
settings = self._settings
if settings:
return settings
diff --git a/enterprise/server/routes/agent_profiles.py b/enterprise/server/routes/agent_profiles.py
new file mode 100644
index 0000000000..10a24fd740
--- /dev/null
+++ b/enterprise/server/routes/agent_profiles.py
@@ -0,0 +1,477 @@
+"""Organization Agent Profiles router (cloud / SaaS).
+
+Serves the flat, member-facing ``/api/agent-profiles`` surface that
+agent-canvas's backend-agnostic ``AgentProfilesClient`` calls (the same wire
+contract as the local agent-server ``agent_profiles_router.py``). The org is
+derived from the authenticated session (``EFFECTIVE_ORG_ID``) rather than the
+path, because each member activates *their own* profile (#15044 Β§2); everything
+else β€” the org-owned column, the locked org-row transaction, the
+``VIEW``/``EDIT_ORG_SETTINGS`` permission model β€” mirrors the LLM-profile router
+``org_profiles.py``.
+
+Domain logic is **imported, never re-implemented** (the #3730 thin-boundary
+contract): validation β†’ ``validate_agent_profile``; id/revision stamping β†’
+``save_profile_preserving_identity``; the dry-run resolve β†’
+``resolve_agent_profile_dry_run``; the 422 redaction β†’
+``safe_validation_error_detail``. Agent profiles are secret-free at rest
+(software-agent-sdk#4017 dropped the last secret-bearing field, embedded
+``skills``) β€” unlike ``org_profiles``, there is no api-key lift/mask on
+activate, and GET/POST need no secret masking or restore-on-save at all.
+
+Activation is **pointer-only**: it writes the per-member
+``OrgMember.active_agent_profile_id`` and nothing else (the creation-time-only
+contract, #15044 Β§3). Resolution into ``agent_settings`` happens at
+conversation-start (``SaasSettingsStore.load``), not here.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from typing import Annotated, Any, AsyncIterator
+from uuid import UUID
+
+from fastapi import APIRouter, Body, Depends, HTTPException, Path, status
+from pydantic import BaseModel, Field, ValidationError
+from server.auth.authorization import Permission, require_permission
+from server.auth.org_context import EFFECTIVE_ORG_ID
+from server.routes.org_models import OrgNotFoundError
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+from storage.agent_profile_resolution import (
+ OrgLLMProfileLoader,
+ load_agent_profiles,
+ load_llm_profiles,
+ member_mcp_config,
+)
+from storage.database import a_session_maker
+from storage.org import Org
+from storage.org_member import OrgMember
+from storage.org_service import OrgService
+
+from openhands.app_server.settings.agent_profiles import (
+ MAX_AGENT_PROFILES,
+ AgentProfiles,
+)
+from openhands.app_server.utils.logger import openhands_logger as logger
+from openhands.sdk.profiles import (
+ AgentProfile,
+ AgentProfileDiagnostics,
+ ProfileLimitExceeded,
+ resolve_agent_profile_dry_run,
+ safe_validation_error_detail,
+ save_profile_preserving_identity,
+ validate_agent_profile,
+)
+from openhands.sdk.profiles.agent_profile_store import PROFILE_NAME_PATTERN
+
+router = APIRouter(prefix='/api/agent-profiles', tags=['Agent Profiles'])
+
+ProfileName = Annotated[
+ str, Path(min_length=1, max_length=64, pattern=PROFILE_NAME_PATTERN)
+]
+ProfileId = Annotated[str, Path(min_length=1, max_length=128)]
+
+
+# ── Request/Response Models (mirror the local agent_profiles_router contract) ──
+
+
+class AgentProfileInfo(BaseModel):
+ """Summary projection of a stored profile (no secret instantiation)."""
+
+ id: str | None = None
+ name: str
+ agent_kind: str = 'openhands'
+ revision: int | None = None
+ llm_profile_ref: str | None = None
+ mcp_server_refs: list[str] | None = None
+
+
+class AgentProfileListResponse(BaseModel):
+ profiles: list[AgentProfileInfo]
+ active_agent_profile_id: str | None = None
+
+
+class AgentProfileDetailResponse(BaseModel):
+ name: str
+ # The stored profile, secret-free at rest. Typed as the SDK discriminated
+ # union (not ``dict``) so the OpenAPI schema matches the ``AgentProfile``
+ # the ts-client consumes.
+ profile: AgentProfile
+
+
+class AgentProfileMutationResponse(BaseModel):
+ name: str
+ message: str
+
+
+class ActivateAgentProfileResponse(BaseModel):
+ id: str
+ message: str
+ # Always False: activation is pointer-only by contract. agent_settings is
+ # resolved at conversation-start, not on activate.
+ agent_settings_applied: bool = False
+
+
+class RenameAgentProfileRequest(BaseModel):
+ new_name: str = Field(
+ ..., min_length=1, max_length=64, pattern=PROFILE_NAME_PATTERN
+ )
+
+
+# ── Helpers ────────────────────────────────────────────────────────────────
+
+
+async def _get_org(org_id: UUID, user_id: str) -> Org:
+ """Load the org, raising 404 if the user is not a member / it is missing."""
+ try:
+ return await OrgService.get_org_by_id(org_id=org_id, user_id=user_id)
+ except OrgNotFoundError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+
+
+async def _get_member(
+ session: AsyncSession, org_id: UUID, user_id: str
+) -> OrgMember | None:
+ result = await session.execute(
+ select(OrgMember).filter(
+ OrgMember.org_id == org_id, OrgMember.user_id == UUID(user_id)
+ )
+ )
+ return result.scalars().first()
+
+
+async def _get_org_and_member(
+ org_id: UUID, user_id: str
+) -> tuple[Org, OrgMember | None]:
+ """Fetch the org (raising 404 if missing) and the acting member's row.
+
+ The member is read in its own short-lived session β€” matches the org read,
+ which resolves through ``OrgService.get_org_by_id`` rather than this
+ module's session directly.
+ """
+ org = await _get_org(org_id, user_id)
+ async with a_session_maker() as session:
+ member = await _get_member(session, org_id, user_id)
+ return org, member
+
+
+async def _agent_profiles_transaction(
+ org_id: UUID, user_id: str
+) -> AsyncIterator[tuple[AsyncSession, Org, AgentProfiles]]:
+ """Yield ``(session, org, agent_profiles)`` for a single locked mutation.
+
+ Mirrors ``org_profiles._org_profiles_transaction``: ``SELECT ... FOR UPDATE``
+ on the org row so concurrent profile mutations serialize at the DB level.
+ The caller mutates ``agent_profiles`` in place (and may also write the acting
+ member's ``active_agent_profile_id`` via the same session); on normal exit
+ the helper serializes the collection back onto the org row and commits. This
+ DB row lock *is* the store's ``lock()`` β€” hence the in-memory model's
+ re-entrant no-op ``lock()``.
+
+ The collection is written back ONLY when the caller actually changed it.
+ Loading is best-effort (``_skip_invalid_profiles`` drops entries that fail
+ to validate, e.g. after schema drift), so an unconditional write-back would
+ let a mutation-free call such as ``/activate`` silently erase a stored
+ profile it merely failed to parse.
+ """
+ await _get_org(org_id, user_id)
+ 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:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f'Organization {org_id} not found',
+ )
+ profiles = load_agent_profiles(org)
+ # The EncryptedJSON column is the at-rest boundary. expose_secrets=True
+ # is now a no-op for AgentProfile (secret-free since #4017), kept for
+ # parity with the write-back pattern the LLM-profile router shares.
+ before = profiles.model_dump(mode='json', context={'expose_secrets': True})
+ yield session, org, profiles
+ after = profiles.model_dump(mode='json', context={'expose_secrets': True})
+ if after != before:
+ org.agent_profiles = after
+ await session.commit()
+
+
+# ── Endpoints ────────────────────────────────────────────────────────────────
+
+
[email protected]('', response_model=AgentProfileListResponse)
+async def list_agent_profiles(
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),
+) -> AgentProfileListResponse:
+ """List agent profiles and the effective active pointer for this member.
+
+ No implicit writes: an org with no profiles yet just returns an empty
+ list. Profile creation is always an explicit ``save_agent_profile`` call
+ (``EDIT_ORG_SETTINGS``).
+ """
+ org, member = await _get_org_and_member(effective_org_id, user_id)
+ profiles = load_agent_profiles(org)
+ member_active = member.active_agent_profile_id if member is not None else None
+ active_id = member_active or profiles.active
+
+ return AgentProfileListResponse(
+ profiles=[AgentProfileInfo(**s) for s in profiles.list_summaries()],
+ active_agent_profile_id=active_id,
+ )
+
+
[email protected]('/{name}', response_model=AgentProfileDetailResponse)
+async def get_agent_profile(
+ name: ProfileName,
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),
+) -> AgentProfileDetailResponse:
+ """Get a stored profile β€” secret-free at rest, nothing to mask.
+
+ Unlike the LLM-profile GET in ``org_profiles``, there is no
+ ``X-Expose-Secrets`` handling here at all: the profile carries only
+ references (``llm_profile_ref``, ``mcp_server_refs``) and a
+ ``disabled_skills`` deny-list of names.
+ """
+ org = await _get_org(effective_org_id, user_id)
+ profiles = load_agent_profiles(org)
+ try:
+ profile = profiles.load(name)
+ except FileNotFoundError:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Agent profile '{name}' not found",
+ )
+ return AgentProfileDetailResponse(name=name, profile=profile)
+
+
+ '/{name}',
+ response_model=AgentProfileMutationResponse,
+ status_code=status.HTTP_201_CREATED,
+)
+async def save_agent_profile(
+ name: ProfileName,
+ body: dict[str, Any],
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),
+) -> AgentProfileMutationResponse:
+ """Create or update an agent profile under ``name`` (path name is authoritative).
+
+ Server-managed id/revision: overwrite keeps the namesake's id and bumps
+ revision; create mints a fresh id (``save_profile_preserving_identity``).
+ Returns 422 on invalid payloads (secret-safe detail) and 409 when creating a
+ new profile would exceed ``MAX_AGENT_PROFILES``.
+ """
+ async with _agent_profiles_transaction(effective_org_id, user_id) as (
+ _session,
+ _org,
+ profiles,
+ ):
+ try:
+ profile = validate_agent_profile({**body, 'name': name})
+ except ValidationError as e:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=safe_validation_error_detail(e),
+ )
+ except Exception:
+ # SkillValidationError / schema errors are client errors, never a
+ # 500; stay generic β€” these messages can embed the input.
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail='Invalid agent profile',
+ )
+
+ try:
+ save_profile_preserving_identity(
+ profiles, profile, max_profiles=MAX_AGENT_PROFILES
+ )
+ except ProfileLimitExceeded:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ f'Agent profile limit reached ({MAX_AGENT_PROFILES}). '
+ 'Delete a profile before saving a new one.'
+ ),
+ )
+
+ logger.info("Saved agent profile '%s' for org %s", name, effective_org_id)
+ return AgentProfileMutationResponse(
+ name=name, message=f"Agent profile '{name}' saved"
+ )
+
+
[email protected]('/{name}', response_model=AgentProfileMutationResponse)
+async def delete_agent_profile(
+ name: ProfileName,
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),
+) -> AgentProfileMutationResponse:
+ """Delete a profile (idempotent). Clears every org member's pointer to it.
+
+ A missing name resolves 200, matching the ts-client ``AgentProfilesClient``
+ contract and the local agent-server ``delete_profile`` (canvas's delete
+ mutation has no 404 branch).
+ """
+ async with _agent_profiles_transaction(effective_org_id, user_id) as (
+ session,
+ _org,
+ profiles,
+ ):
+ # Capture the id (if present) before deleting so the per-member pointer
+ # clear still runs; ``profiles.delete`` is itself a no-op when absent.
+ deleted_id: str | None = None
+ with contextlib.suppress(FileNotFoundError):
+ deleted_id = str(profiles.load(name).id)
+ profiles.delete(name)
+ if deleted_id is not None:
+ # Clear the pointer for every member who had this profile active, not
+ # just the acting member β€” activation is per-member, so any other
+ # member could be pointing at the now-deleted id.
+ await session.execute(
+ update(OrgMember)
+ .where(
+ OrgMember.org_id == effective_org_id,
+ OrgMember.active_agent_profile_id == deleted_id,
+ )
+ .values(active_agent_profile_id=None)
+ )
+
+ logger.info("Deleted agent profile '%s' for org %s", name, effective_org_id)
+ return AgentProfileMutationResponse(
+ name=name, message=f"Agent profile '{name}' deleted"
+ )
+
+
[email protected]('/{name}/rename', response_model=AgentProfileMutationResponse)
+async def rename_agent_profile(
+ name: ProfileName,
+ request: RenameAgentProfileRequest = Body(...),
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),
+) -> AgentProfileMutationResponse:
+ """Rename a profile atomically.
+
+ The stable id is preserved, so active pointers (keyed on id) survive
+ untouched.
+ """
+ async with _agent_profiles_transaction(effective_org_id, user_id) as (
+ _session,
+ _org,
+ profiles,
+ ):
+ try:
+ profiles.rename(name, request.new_name)
+ except FileNotFoundError:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Agent profile '{name}' not found",
+ )
+ except FileExistsError:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"Agent profile '{request.new_name}' already exists",
+ )
+
+ return AgentProfileMutationResponse(
+ name=request.new_name,
+ message=f"Agent profile renamed from '{name}' to '{request.new_name}'",
+ )
+
+
[email protected]('/{profile_id}/activate', response_model=ActivateAgentProfileResponse)
+async def activate_agent_profile(
+ profile_id: ProfileId,
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),
+) -> ActivateAgentProfileResponse:
+ """Activate a profile for the calling member β€” pointer only.
+
+ Writes the per-member ``OrgMember.active_agent_profile_id`` and nothing else
+ (no ``agent_settings`` materialization, and the profiles collection itself
+ is untouched β€” the transaction helper skips the write-back when nothing
+ mutated; #15044 Β§3). Member-facing, so it requires only
+ ``VIEW_ORG_SETTINGS`` (each member picks their own active profile); profile
+ CRUD requires ``EDIT_ORG_SETTINGS``. 404 if no stored profile has that id.
+ """
+ async with _agent_profiles_transaction(effective_org_id, user_id) as (
+ session,
+ _org,
+ profiles,
+ ):
+ known_ids = {s['id'] for s in profiles.list_summaries() if s.get('id')}
+ if profile_id not in known_ids:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Agent profile with id '{profile_id}' not found",
+ )
+ member = await _get_member(session, effective_org_id, user_id)
+ if member is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='Organization membership not found',
+ )
+ member.active_agent_profile_id = profile_id
+
+ logger.info(
+ "Activated agent profile id '%s' for member in org %s",
+ profile_id,
+ effective_org_id,
+ )
+ return ActivateAgentProfileResponse(
+ id=profile_id, message=f"Agent profile '{profile_id}' activated"
+ )
+
+
[email protected]('/{name}/materialize', response_model=AgentProfileDiagnostics)
+async def materialize_agent_profile(
+ name: ProfileName,
+ effective_org_id: UUID = EFFECTIVE_ORG_ID,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_SETTINGS)),
+) -> AgentProfileDiagnostics:
+ """Dry-run resolve a profile's LLM/MCP references into a diagnostics report.
+
+ Dangling refs are reported in the body (``valid=False``), not raised; the
+ only error status is 404 (unknown profile name). ``resolved_settings`` is
+ redacted. Delegates entirely to ``resolve_agent_profile_dry_run``.
+ """
+ org, member = await _get_org_and_member(effective_org_id, user_id)
+ profiles = load_agent_profiles(org)
+ try:
+ profile = profiles.load(name)
+ except FileNotFoundError:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Agent profile '{name}' not found",
+ )
+
+ mcp_config = member_mcp_config(member) if member is not None else {}
+ llm_store = OrgLLMProfileLoader(load_llm_profiles(org))
+
+ try:
+ return resolve_agent_profile_dry_run(
+ profile,
+ llm_store=llm_store,
+ mcp_config=mcp_config,
+ available_skills=None,
+ cipher=None,
+ )
+ except Exception as exc:
+ # The dry-run is contractually total, but SDK contract drift (e.g. a
+ # new required kwarg raising TypeError) must surface as an invalid
+ # diagnostics report, not a 500.
+ logger.warning(
+ "Agent profile dry-run resolve failed for '%s' in org %s: %s",
+ name,
+ effective_org_id,
+ exc,
+ )
+ return AgentProfileDiagnostics(
+ agent_kind=profile.agent_kind,
+ valid=False,
+ errors=[f'Failed to resolve profile: {exc}'],
+ )
diff --git a/enterprise/server/routes/org_profiles.py b/enterprise/server/routes/org_profiles.py
index 6150a19684..6cc95e1843 100644
--- a/enterprise/server/routes/org_profiles.py
+++ b/enterprise/server/routes/org_profiles.py
@@ -20,6 +20,10 @@ from server.constants import LITE_LLM_API_URL
from server.routes.org_models import OrgNotFoundError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from storage.agent_profile_resolution import (
+ OrgLLMProfileMutator,
+ load_agent_profiles,
+)
from storage.database import a_session_maker
from storage.org import Org
from storage.org_member import OrgMember
@@ -38,6 +42,12 @@ from openhands.app_server.settings.settings_models import (
from openhands.app_server.utils.llm import MASKED_API_KEY, is_openhands_model
from openhands.app_server.utils.logger import openhands_logger as logger
from openhands.sdk.llm import LLM
+from openhands.sdk.profiles import (
+ ProfileReferenced,
+ delete_llm_profile,
+ rename_llm_profile,
+)
+from openhands.sdk.profiles.agent_profile_store import PROFILE_NAME_PATTERN
from ..auth.authorization import Permission, require_permission
@@ -96,9 +106,21 @@ class SaveProfileRequest(BaseModel):
class RenameProfileRequest(BaseModel):
- """Request body for renaming a profile."""
+ """Request body for renaming a profile.
+
+ ``new_name`` is constrained to ``PROFILE_NAME_PATTERN`` because
+ ``rename_llm_profile`` (the SDK FK-cascade helper backing this endpoint)
+ validates the new name against that same pattern before renaming and
+ repointing any referencing Agent Profiles β€” a name outside it always 422s
+ there. Declaring the constraint here makes the schema honest and gives a
+ field-level 422 instead of one raised deep inside the handler. ``save``
+ (create/update) is intentionally left permissive: it never calls the FK
+ helper, so it has no such requirement.
+ """
- new_name: str = Field(..., min_length=1, max_length=100)
+ new_name: str = Field(
+ ..., min_length=1, max_length=64, pattern=PROFILE_NAME_PATTERN
+ )
# ── Helper Functions ────────────────────────────────────────────────────────
@@ -247,17 +269,28 @@ async def delete_profile(
name: str = Path(..., min_length=1),
user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),
) -> ProfileMutationResponse:
- """Delete an LLM profile."""
+ """Delete an LLM profile.
+
+ Blocked with 409 if any of the org's Agent Profiles still reference this LLM
+ profile by ``llm_profile_ref`` (the SDK ``find_referrers`` FK guard) β€” both
+ collections live on the same org row, so the ``SELECT ... FOR UPDATE`` lock
+ makes the referrer check and the delete atomic.
+ """
async with _org_profiles_transaction(org_id, user_id) as (
_session,
- _org,
+ org,
profiles,
):
- if not profiles.delete(name):
+ if not profiles.has(name):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Profile '{name}' not found",
)
+ agent_profiles = load_agent_profiles(org)
+ try:
+ delete_llm_profile(agent_profiles, OrgLLMProfileMutator(profiles), name)
+ except ProfileReferenced as exc:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
return ProfileMutationResponse(name=name, message=f"Profile '{name}' deleted")
@@ -359,18 +392,47 @@ async def rename_profile(
request: RenameProfileRequest = Body(...),
user_id: str = Depends(require_permission(Permission.EDIT_ORG_SETTINGS)),
) -> ProfileMutationResponse:
- """Rename an LLM profile."""
+ """Rename an LLM profile, cascading the rename to any Agent Profiles that
+ reference it.
+
+ The SDK ``rename_llm_profile`` renames the LLM profile and repoints every
+ ``agent_profiles.*.llm_profile_ref == name`` to ``new_name`` under the org
+ row lock, so a referencing Agent Profile never dangles. Both collections are
+ written back in the same transaction.
+ """
async with _org_profiles_transaction(org_id, user_id) as (
_session,
- _org,
+ org,
profiles,
):
+ agent_profiles = load_agent_profiles(org)
+ # Loading is best-effort (invalid entries are dropped), so only write
+ # the collection back when the cascade actually repointed a ref β€” an
+ # unconditional write-back would erase a stored profile that merely
+ # failed to parse.
+ before = agent_profiles.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
try:
- profiles.rename(name, request.new_name)
+ rename_llm_profile(
+ agent_profiles,
+ OrgLLMProfileMutator(profiles),
+ name,
+ request.new_name,
+ )
except ProfileNotFoundError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
except ProfileAlreadyExistsError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
+ except ValueError as exc:
+ # rename_llm_profile validates new_name against PROFILE_NAME_PATTERN.
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
+ )
+ # The cascade may have repointed agent-profile refs β€” persist them too.
+ after = agent_profiles.model_dump(mode='json', context={'expose_secrets': True})
+ if after != before:
+ org.agent_profiles = after
return ProfileMutationResponse(
name=request.new_name,
diff --git a/enterprise/storage/agent_profile_resolution.py b/enterprise/storage/agent_profile_resolution.py
new file mode 100644
index 0000000000..0ba27baa5e
--- /dev/null
+++ b/enterprise/storage/agent_profile_resolution.py
@@ -0,0 +1,114 @@
+"""Shared cloud adapters for resolving Agent Profiles against an org row.
+
+The thin glue (#15044) that lets the SDK profile substrate
+(``resolve_agent_profile`` / ``find_referrers`` / ``cascade_rename``) operate
+over the SaaS storage model. Everything domain-level is imported from
+``openhands.sdk.profiles``; this module only adapts the ``org.agent_profiles`` /
+``org.llm_profiles`` columns to the SDK's store/loader/mutator Protocols.
+
+Used by the ``/api/agent-profiles`` router, the LLM-profile FK guard in
+``org_profiles``, and ``SaasSettingsStore.load``.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from pydantic import ValidationError
+
+from openhands.app_server.settings.agent_profiles import AgentProfiles
+from openhands.app_server.settings.llm_profiles import LLMProfiles
+from openhands.app_server.utils.logger import openhands_logger as logger
+from openhands.sdk.mcp.config import MCPServer, coerce_mcp_config
+
+if TYPE_CHECKING:
+ from storage.org import Org
+ from storage.org_member import OrgMember
+
+ from openhands.sdk.llm import LLM
+ from openhands.sdk.utils.cipher import Cipher
+
+
+def load_agent_profiles(org: Org) -> AgentProfiles:
+ """Load ``AgentProfiles`` from the org row, defaulting to empty if unset.
+
+ Degrades to an empty collection on schema drift rather than 500-ing β€” the
+ same contract as ``org_profiles._load_profiles`` for ``llm_profiles``.
+ """
+ if org.agent_profiles is None:
+ return AgentProfiles()
+ try:
+ return AgentProfiles.model_validate(org.agent_profiles)
+ except ValidationError as exc:
+ logger.warning('Failed to load org agent profiles for %s: %s', org.id, exc)
+ return AgentProfiles()
+
+
+def load_llm_profiles(org: Org) -> LLMProfiles:
+ """Load ``LLMProfiles`` from the org row, defaulting to empty if unset."""
+ if org.llm_profiles is None:
+ return LLMProfiles()
+ try:
+ return LLMProfiles.model_validate(org.llm_profiles)
+ except ValidationError as exc:
+ logger.warning('Failed to load org LLM profiles for %s: %s', org.id, exc)
+ return LLMProfiles()
+
+
+class OrgLLMProfileLoader:
+ """``LLMProfileLoader`` over an org's LLM profiles β€” the resolver's ``llm_store``.
+
+ The ``org.llm_profiles`` ``EncryptedJSON`` column decrypts at the column
+ boundary, so the wrapped ``LLMProfiles`` already holds cleartext keys; the
+ ``cipher`` arg is accepted for Protocol parity and ignored.
+ """
+
+ def __init__(self, profiles: LLMProfiles) -> None:
+ self._profiles = profiles
+
+ def load(self, name: str, *, cipher: Cipher | None = None) -> LLM:
+ llm = self._profiles.get(name)
+ if llm is None:
+ # The resolver maps this to ProfileNotFound (HTTP 4xx).
+ raise FileNotFoundError(f'LLM profile {name!r} not found')
+ return llm
+
+
+class OrgLLMProfileMutator:
+ """``LLMProfileMutator`` over an org's LLM profiles β€” drives the FK delete/rename.
+
+ Mutates the in-memory ``LLMProfiles`` container; the caller persists it back
+ onto the org row under the same locked transaction.
+ """
+
+ def __init__(self, profiles: LLMProfiles) -> None:
+ self._profiles = profiles
+
+ def delete(self, name: str) -> None:
+ self._profiles.delete(name)
+
+ def rename(self, old_name: str, new_name: str) -> None:
+ self._profiles.rename(old_name, new_name)
+
+
+def member_mcp_config(member: OrgMember) -> dict[str, MCPServer]:
+ """The acting member's globally-configured MCP servers as a server map.
+
+ ``mcp_config`` is member-private (it lives only on the member's
+ ``agent_settings_diff``; the org dump strips it β€” see
+ ``MEMBER_PRIVATE_AGENT_KEYS``), so the member-effective set is exactly the
+ member diff's ``mcp_config``. Used to resolve / filter ``mcp_server_refs``.
+ Returns ``{}`` when the member configured no MCP servers.
+ """
+ raw = (member.agent_settings_diff or {}).get('mcp_config')
+ if not raw:
+ return {}
+ try:
+ return coerce_mcp_config(raw)
+ except Exception as exc:
+ # Catch broadly, not just ValidationError: coerce_mcp_config also raises
+ # on fastmcp normalization / contract drift, and a malformed member
+ # config must resolve to "no servers" rather than 500 the materialize
+ # endpoint. Matches _resolve_active_agent_profile's inline coerce.
+ logger.warning('Failed to parse member MCP config for resolve: %s', exc)
+ return {}
diff --git a/enterprise/storage/org.py b/enterprise/storage/org.py
index 855d40fd22..ed04e5b2ee 100644
--- a/enterprise/storage/org.py
+++ b/enterprise/storage/org.py
@@ -73,6 +73,13 @@ class Org(Base):
llm_profiles: Mapped[dict[str, Any] | None] = mapped_column(
EncryptedJSON, nullable=True
)
+ # Encrypted column for agent profiles. Mirrors llm_profiles: the column is
+ # the at-rest encryption boundary, so secret-bearing skills[].mcp_tools ride
+ # in cleartext inside the encrypted blob. Envelope is
+ # ``{profiles: {<id>: AgentProfile}, active: <id> | null}`` (see AgentProfiles).
+ agent_profiles: Mapped[dict[str, Any] | None] = mapped_column(
+ EncryptedJSON, nullable=True
+ )
# Marks the bootstrapped default org on OHE installs; a partial unique
# index allows at most one default org per install.
is_default: Mapped[bool] = mapped_column(nullable=False, default=False)
diff --git a/enterprise/storage/org_member.py b/enterprise/storage/org_member.py
index 581cd505fb..a9f9e5e912 100644
--- a/enterprise/storage/org_member.py
+++ b/enterprise/storage/org_member.py
@@ -31,6 +31,11 @@ class OrgMember(Base):
agent_settings_diff: Mapped[dict[str, Any]] = mapped_column(
JSON, nullable=False, default=dict
)
+ # Per-member pointer to the active AgentProfile id β€” the sole launch
+ # authority for Agent Profiles (mirrors the per-member _llm_api_key
+ # precedent). NULL falls back to the org default (org.agent_profiles.active)
+ # and, pre-migration, to the legacy active-LLM-profile materialization.
+ active_agent_profile_id: Mapped[str | None] = mapped_column(String, nullable=True)
conversation_settings_diff: Mapped[dict[str, Any]] = mapped_column(
JSON, nullable=False, default=dict
)
diff --git a/enterprise/storage/saas_settings_store.py b/enterprise/storage/saas_settings_store.py
index b7ff347232..cc12d7d553 100644
--- a/enterprise/storage/saas_settings_store.py
+++ b/enterprise/storage/saas_settings_store.py
@@ -12,6 +12,11 @@ from server.logger import logger
from server.routes.org_models import OrgMemberSettingsUpdate
from sqlalchemy import select
from sqlalchemy.orm import joinedload
+from storage.agent_profile_resolution import (
+ OrgLLMProfileLoader,
+ load_agent_profiles,
+ load_llm_profiles,
+)
from storage.database import a_session_maker
from storage.lite_llm_manager import LiteLlmManager, get_openhands_cloud_key_alias
from storage.org import Org
@@ -22,10 +27,8 @@ from storage.user import User
from storage.user_settings import UserSettings
from storage.user_store import UserStore
-from openhands.app_server.settings.llm_profiles import LLMProfiles
-from openhands.app_server.settings.settings_models import (
- Settings,
-)
+from openhands.app_server.settings.llm_profiles import LLMProfiles, resolve_profile_llm
+from openhands.app_server.settings.settings_models import Settings
from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.utils.jsonpatch_compat import (
WHOLESALE_REPLACEMENT_KEYS,
@@ -36,6 +39,8 @@ from openhands.app_server.utils.llm import is_openhands_model
from openhands.sdk.llm.utils.openhands_provider import (
canonicalize_openhands_llm_payload,
)
+from openhands.sdk.mcp.config import MCPServer, coerce_mcp_config
+from openhands.sdk.profiles import resolve_agent_profile
# Agent-settings keys private to each org member: never written to
# org-level defaults nor broadcast across the org. Covers ``mcp_config``
@@ -141,7 +146,144 @@ class SaasSettingsStore(SettingsStore):
def _get_persisted_agent_settings(item: Settings) -> dict[str, Any]:
return item.agent_settings.model_dump(mode='json')
- async def load(self) -> Settings | None:
+ def _resolve_active_agent_profile(
+ self,
+ org: Org,
+ org_member: OrgMember,
+ merged_agent_settings: dict[str, Any],
+ effective_llm_api_key: SecretStr | None,
+ override_agent_profile_id: str | None = None,
+ ) -> tuple[dict[str, Any], str, int] | None:
+ """Resolve an agent profile into an ``agent_settings`` dump.
+
+ Resolves ``override_agent_profile_id`` when given (a one-off,
+ non-persisted launch override β€” never written back to
+ ``org_member.active_agent_profile_id``), else the member's ambient
+ ``active_agent_profile_id``, else the org-wide default pointer
+ (``AgentProfiles.active``, if one has been set). Returns
+ ``(agent_settings_dump, profile_id, revision)``, or ``None`` to fall
+ back to the composed ``agent_settings``.
+ Delegates the ``llm_profile_ref`` + ``mcp_server_refs`` join entirely to
+ the SDK ``resolve_agent_profile``; only the cloud-specific glue (the
+ org-backed ``llm_store`` adapter, the member-effective ``mcp_config``,
+ and the managed-key / base-url overlay via ``resolve_profile_llm``)
+ lives here.
+
+ Fail-safe by design: a stale pointer (profile deleted) or any resolution
+ error returns ``None`` and logs, because bricking *every* settings load
+ on a dangling pointer is far worse than launching the composed default.
+ """
+ agent_profiles = load_agent_profiles(org)
+ active_id = (
+ override_agent_profile_id
+ or org_member.active_agent_profile_id
+ or agent_profiles.active
+ )
+ if not active_id:
+ return None
+
+ name = agent_profiles.name_for_id(active_id)
+ if name is None:
+ logger.warning(
+ 'Active agent profile %s not found for user %s in org %s; '
+ 'falling back to composed settings',
+ active_id,
+ self.user_id,
+ org.id,
+ )
+ return None
+ try:
+ profile = agent_profiles.load(name)
+ except FileNotFoundError:
+ return None
+
+ mcp_config: dict[str, MCPServer] = {}
+ mcp_raw = merged_agent_settings.get('mcp_config')
+ if mcp_raw:
+ try:
+ mcp_config = coerce_mcp_config(mcp_raw)
+ except Exception:
+ mcp_config = {}
+
+ llm_store = OrgLLMProfileLoader(load_llm_profiles(org))
+ try:
+ resolved = resolve_agent_profile(
+ profile,
+ llm_store=llm_store,
+ mcp_config=mcp_config,
+ available_skills=None,
+ cipher=None,
+ )
+
+ # Apply the cloud managed-key / base-url overlay to the resolved LLM
+ # (OpenHands kind only), so managed OpenHands keys and provider-default
+ # base URLs behave exactly as the non-profile path. Reuses the existing
+ # resolve_profile_llm helper rather than re-deriving key resolution.
+ if resolved.agent_kind == 'openhands':
+ resolved = resolved.model_copy(
+ update={
+ 'llm': resolve_profile_llm(
+ resolved.llm,
+ managed_proxy_url=LITE_LLM_API_URL,
+ fallback_api_key=effective_llm_api_key,
+ )
+ }
+ )
+
+ # expose_secrets so the resolved LLM key lands in agent_settings the
+ # same way the composed path sets
+ # merged_agent_settings['llm']['api_key'].
+ resolved_dump = resolved.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
+ # Canonicalize legacy managed OpenHands model names/base_urls on the
+ # resolved LLM, mirroring the composed path (merged_agent_settings
+ # ['llm'], line ~348) so a profile launch and a non-profile launch
+ # normalize an org's pre-canonical llm_profiles identically.
+ resolved_llm = resolved_dump.get('llm')
+ if isinstance(resolved_llm, dict):
+ resolved_dump['llm'] = canonicalize_openhands_llm_payload(resolved_llm)
+ except Exception as exc:
+ # Never-brick contract: catch broadly, not just the known resolver
+ # errors β€” SDK contract drift (e.g. a new required kwarg raising
+ # TypeError) must degrade to the composed settings, not 500 every
+ # settings load.
+ logger.warning(
+ 'Failed to resolve active agent profile %r for user %s: %s; '
+ 'falling back to composed settings',
+ name,
+ self.user_id,
+ exc,
+ )
+ return None
+ return resolved_dump, str(profile.id), profile.revision
+
+ async def load(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> Settings | None:
+ """Load settings; opt into the resolved Agent-Profile launch view.
+
+ The default returns the PERSISTED (composed org + member) settings β€”
+ the view every load() -> store() round-trip must operate on, so an
+ active Agent Profile's *resolved* dump (ref-filtered ``mcp_config``,
+ the referenced LLM profile's key) can never masquerade as
+ user-authored settings and get written back.
+
+ ``resolve_agent_profile=True`` is the conversation-start opt-in: the
+ active Agent Profile resolves and REPLACES ``agent_settings`` (the
+ sole launch authority, #15044 Β§3), and the result is marked
+ ``_resolved_view`` β€” ``store()`` refuses it. Falls back to the
+ composed settings when no pointer is set or the pointer is stale /
+ unresolvable, so a broken pointer can never brick the load.
+
+ ``override_agent_profile_id`` is a one-off launch override (e.g. a
+ per-conversation-start request): it implies resolution, changes which
+ profile resolves for *this call only*, and is never persisted to
+ ``org_member.active_agent_profile_id``.
+ """
user = await UserStore.get_user_by_id(self.user_id)
if not user:
logger.error(f'User not found for ID {self.user_id}')
@@ -283,7 +425,33 @@ class SaasSettingsStore(SettingsStore):
# Settings.llm_profiles falls back to its default_factory.
kwargs.pop('llm_profiles', None)
+ # Agent Profiles: only on a resolve-requested load (conversation
+ # start), resolve the active agent profile and let the result REPLACE
+ # the composed agent_settings β€” the active Agent Profile is the sole
+ # launch authority (#15044 Β§3). Plain loads keep the persisted
+ # composed settings so settings round-trips never see (and never
+ # write back) a profile's resolved dump.
+ resolution_requested = (
+ resolve_agent_profile or override_agent_profile_id is not None
+ )
+ if resolution_requested:
+ resolved = self._resolve_active_agent_profile(
+ org,
+ org_member,
+ merged_agent_settings,
+ effective_llm_api_key,
+ override_agent_profile_id,
+ )
+ if resolved is not None:
+ resolved_dump, resolved_id, resolved_revision = resolved
+ kwargs['agent_settings'] = resolved_dump
+ kwargs['active_agent_profile_id'] = resolved_id
+ kwargs['active_agent_profile_revision'] = resolved_revision
+
settings = Settings(**kwargs)
+ if resolution_requested:
+ # Launch view (even when resolution fell back): never persistable.
+ settings._resolved_view = True
# 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
@@ -336,6 +504,18 @@ class SaasSettingsStore(SettingsStore):
await session.commit()
async def store(self, item: Settings):
+ if item is not None and (
+ item._resolved_view or item.active_agent_profile_id is not None
+ ):
+ # A resolved Agent-Profile launch view (from
+ # load(resolve_agent_profile=True) / an override) is the profile's
+ # dump, not user-authored settings: persisting it would bake the
+ # ref-filtered mcp_config and the referenced LLM profile's key into
+ # the member/org rows. Only plain load() results may round-trip.
+ raise ValueError(
+ 'Refusing to persist a resolved Agent-Profile settings view; '
+ 'store() only accepts persisted settings from a plain load()'
+ )
async with a_session_maker() as session:
if not item:
return None
diff --git a/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
index 38835a0b3c..696691b3df 100644
--- a/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
+++ b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
@@ -256,6 +256,7 @@ class TestGetEffectiveOrgId:
user_auth.settings_store = object()
user_auth.secrets_store = object()
user_auth._settings = object()
+ user_auth._resolved_settings = object()
user_auth._secrets = object()
user_auth.provider_tokens = {}
user_auth._org_id = 'old-org'
@@ -272,6 +273,10 @@ class TestGetEffectiveOrgId:
assert user_auth.settings_store is None
assert user_auth.secrets_store is None
assert user_auth._settings is None
+ # The resolved launch view is org-scoped (referenced LLM key +
+ # ref-filtered mcp_config) and must not survive a re-scope to another
+ # org, or org B would read org A's resolved credentials.
+ assert user_auth._resolved_settings is None
assert user_auth._secrets is None
assert user_auth.provider_tokens is None
assert user_auth._org_id is None
diff --git a/enterprise/tests/unit/test_agent_profiles.py b/enterprise/tests/unit/test_agent_profiles.py
new file mode 100644
index 0000000000..dfe5290b40
--- /dev/null
+++ b/enterprise/tests/unit/test_agent_profiles.py
@@ -0,0 +1,1235 @@
+"""Unit + integration tests for the cloud Agent Profiles surface (#15044).
+
+Covers the ``AgentProfiles`` container (SDK ``AgentProfileStoreProtocol``
+conformance), the flat ``/api/agent-profiles`` router, the LLM-profile FK guard
+wired into ``org_profiles``, and ``SaasSettingsStore._resolve_active_agent_profile``.
+Mirrors the harness in ``test_org_profiles.py``: handlers are called directly
+(``Depends`` resolved as kwargs) against a real SQLite Org row.
+"""
+
+import uuid
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import FastAPI, HTTPException, status
+from fastapi.testclient import TestClient
+from sqlalchemy import select
+from storage.org import Org
+from storage.org_member import OrgMember
+from storage.role import Role
+from storage.user import User
+
+from openhands.app_server.settings.agent_profiles import (
+ MAX_AGENT_PROFILES,
+ AgentProfiles,
+)
+from openhands.app_server.user_auth import get_user_id
+from openhands.sdk.profiles import (
+ ACPAgentProfile,
+ AgentProfileStoreProtocol,
+ OpenHandsAgentProfile,
+ save_profile_preserving_identity,
+)
+
+# Mock the database module before importing the routers so module-level imports
+# don't touch a real engine (matches test_org_profiles.py).
+with patch('storage.database.a_session_maker'):
+ from server.routes.agent_profiles import (
+ ActivateAgentProfileResponse,
+ AgentProfileListResponse,
+ RenameAgentProfileRequest,
+ activate_agent_profile,
+ delete_agent_profile,
+ get_agent_profile,
+ list_agent_profiles,
+ materialize_agent_profile,
+ rename_agent_profile,
+ save_agent_profile,
+ )
+ from server.routes.agent_profiles import router as agent_profiles_router
+ from server.routes.org_profiles import (
+ RenameProfileRequest,
+ delete_profile,
+ rename_profile,
+ )
+ from storage.agent_profile_resolution import (
+ load_agent_profiles,
+ member_mcp_config,
+ )
+
+ORG_ID = uuid.UUID('6694c7b6-f959-4b81-92e9-b09c206f5081')
+USER_ID = uuid.UUID('6694c7b6-f959-4b81-92e9-b09c206f5082')
+
+
+# ── Container model ────────────────────────────────────────────────────────
+
+
+class TestAgentProfilesContainer:
+ def test_conforms_to_sdk_protocol(self):
+ assert isinstance(AgentProfiles(), AgentProfileStoreProtocol)
+ assert MAX_AGENT_PROFILES == 50
+
+ def test_id_lifecycle_and_name_keyed_protocol_ops(self):
+ store = AgentProfiles()
+ created = save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='gpt')
+ )
+ assert created.revision == 0
+ # overwrite keeps id, bumps revision; create mints a fresh id
+ again = save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='haiku')
+ )
+ assert again.id == created.id and again.revision == 1
+ assert store.load('reviewer').llm_profile_ref == 'haiku'
+ assert store.name_for_id(created.id) == 'reviewer'
+
+ save_profile_preserving_identity(
+ store, ACPAgentProfile(name='claude', acp_server='claude-code')
+ )
+ summaries = {s['name']: s for s in store.list_summaries()}
+ assert summaries['reviewer']['llm_profile_ref'] == 'haiku'
+ assert summaries['claude']['llm_profile_ref'] is None # ACP carries no ref
+
+ def test_rename_preserves_id_and_active_pointer(self):
+ store = AgentProfiles()
+ p = save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='a', llm_profile_ref='gpt')
+ )
+ store.active = str(p.id)
+ store.rename('a', 'b')
+ assert store.name_for_id(p.id) == 'b'
+ assert store.active == str(p.id) # id-keyed pointer survives rename
+ with pytest.raises(FileNotFoundError):
+ store.load('a')
+
+ def test_delete_clears_org_active_pointer(self):
+ store = AgentProfiles()
+ p = save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='a', llm_profile_ref='gpt')
+ )
+ store.active = str(p.id)
+ store.delete('a')
+ assert store.active is None
+
+ def test_limit_enforced(self):
+ store = AgentProfiles()
+ for i in range(MAX_AGENT_PROFILES):
+ save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name=f'p{i}', llm_profile_ref='gpt')
+ )
+ from openhands.sdk.profiles import ProfileLimitExceeded
+
+ with pytest.raises(ProfileLimitExceeded):
+ save_profile_preserving_identity(
+ store,
+ OpenHandsAgentProfile(name='over', llm_profile_ref='gpt'),
+ max_profiles=MAX_AGENT_PROFILES,
+ )
+
+ def test_encrypted_json_roundtrip_via_dict(self):
+ store = AgentProfiles()
+ save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='r', llm_profile_ref='gpt')
+ )
+ dumped = store.model_dump(mode='json', context={'expose_secrets': True})
+ reloaded = AgentProfiles.model_validate(dumped)
+ assert reloaded.load('r').llm_profile_ref == 'gpt'
+
+ def test_invalid_entry_is_skipped_not_fatal(self):
+ store = AgentProfiles.model_validate(
+ {'profiles': {'bad': {'agent_kind': 'nonsense'}}, 'active': None}
+ )
+ assert store.list_summaries() == []
+
+
+def test_load_agent_profiles_defaults_empty_and_degrades():
+ org = MagicMock(spec=Org)
+ org.id = ORG_ID
+ org.agent_profiles = None
+ assert load_agent_profiles(org).list_summaries() == []
+ # Garbage envelope degrades to empty rather than raising.
+ org.agent_profiles = {'profiles': 'not-a-dict'}
+ assert load_agent_profiles(org).list_summaries() == []
+
+
+def test_member_mcp_config_degrades_on_non_validation_error():
+ """coerce_mcp_config failures beyond ValidationError degrade to {}, not raise."""
+ member = MagicMock(spec=OrgMember)
+ member.agent_settings_diff = {'mcp_config': {'mcpServers': {}}}
+ with patch(
+ 'storage.agent_profile_resolution.coerce_mcp_config',
+ side_effect=TypeError('contract drift'),
+ ):
+ assert member_mcp_config(member) == {}
+
+
+# ── Router integration (real Org row over SQLite) ──────────────────────────
+
+
+def seeded_org(session_maker):
+ with session_maker() as session:
+ session.add(Role(id=20, name='member', rank=3))
+ session.add(
+ Org(
+ id=ORG_ID,
+ name='agent-profile-test-org',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ # An LLM profile the seed/resolve can reference.
+ llm_profiles={
+ 'profiles': {'Default': {'model': 'gpt-4o', 'api_key': 'k'}},
+ 'active': 'Default',
+ },
+ )
+ )
+ session.add(
+ User(id=USER_ID, current_org_id=ORG_ID, user_consents_to_analytics=True)
+ )
+ session.add(
+ OrgMember(
+ org_id=ORG_ID,
+ user_id=USER_ID,
+ role_id=20,
+ llm_api_key='initial-key',
+ agent_settings_diff={},
+ conversation_settings_diff={},
+ status='active',
+ )
+ )
+ session.commit()
+ return ORG_ID
+
+
+def patch_agent_routes(async_session_maker, seeded_org):
+ async def _fake_get_org(org_id, user_id): # noqa: ARG001
+ async with async_session_maker() as session:
+ result = await session.execute(select(Org).where(Org.id == org_id))
+ return result.scalars().first()
+
+ with (
+ patch('server.routes.agent_profiles.a_session_maker', async_session_maker),
+ patch(
+ 'server.routes.agent_profiles.OrgService.get_org_by_id',
+ side_effect=_fake_get_org,
+ ),
+ ):
+ yield seeded_org
+
+
+async def _read_member(async_session_maker, org_id, user_id):
+ async with async_session_maker() as session:
+ result = await session.execute(
+ select(OrgMember).where(
+ OrgMember.org_id == org_id, OrgMember.user_id == user_id
+ )
+ )
+ return result.scalars().first()
+
+
+class TestAgentProfileRouterLifecycle:
+ @pytest.mark.asyncio
+ async def test_save_list_get_rename_activate_delete(
+ self, async_session_maker, patch_agent_routes
+ ):
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ # save (create)
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ # list shows it
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ assert [p.name for p in listing.profiles] == ['reviewer']
+ profile_id = listing.profiles[0].id
+ assert profile_id is not None
+ assert listing.profiles[0].llm_profile_ref == 'Default'
+
+ # get detail (profile is the typed discriminated union, not a dict)
+ detail = await get_agent_profile(
+ name='reviewer', effective_org_id=org_id, user_id=uid
+ )
+ assert detail.profile.agent_kind == 'openhands'
+ assert detail.profile.llm_profile_ref == 'Default'
+
+ # overwrite bumps revision, keeps id
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default', 'tool_concurrency_limit': 3},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ assert listing.profiles[0].id == profile_id
+ assert listing.profiles[0].revision == 1
+
+ # rename preserves id
+ await rename_agent_profile(
+ name='reviewer',
+ request=RenameAgentProfileRequest(new_name='lead-reviewer'),
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ assert listing.profiles[0].name == 'lead-reviewer'
+ assert listing.profiles[0].id == profile_id
+
+ # activate writes the per-member pointer (pointer-only)
+ resp = await activate_agent_profile(
+ profile_id=profile_id, effective_org_id=org_id, user_id=uid
+ )
+ assert isinstance(resp, ActivateAgentProfileResponse)
+ assert resp.agent_settings_applied is False
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member.active_agent_profile_id == profile_id
+
+ # delete clears the pointer
+ await delete_agent_profile(
+ name='lead-reviewer', effective_org_id=org_id, user_id=uid
+ )
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member.active_agent_profile_id is None
+ # Read the row directly (calling list here would lazily re-seed a default).
+ async with async_session_maker() as session:
+ org = (
+ (await session.execute(select(Org).where(Org.id == org_id)))
+ .scalars()
+ .first()
+ )
+ assert load_agent_profiles(org).list_summaries() == []
+
+
+class TestDeleteClearsAllMemberPointers:
+ """Deleting a profile must clear every org member's pointer to it, not
+ just the acting member's (activation is per-member)."""
+
+ @pytest.mark.asyncio
+ async def test_delete_clears_other_members_active_pointer(
+ self, async_session_maker, patch_agent_routes
+ ):
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ other_user_id = uuid.UUID('6694c7b6-f959-4b81-92e9-b09c206f5099')
+
+ async with async_session_maker() as session:
+ session.add(
+ User(
+ id=other_user_id,
+ current_org_id=org_id,
+ user_consents_to_analytics=True,
+ )
+ )
+ session.add(
+ OrgMember(
+ org_id=org_id,
+ user_id=other_user_id,
+ role_id=20,
+ llm_api_key='other-initial-key',
+ agent_settings_diff={},
+ conversation_settings_diff={},
+ status='active',
+ )
+ )
+ await session.commit()
+
+ await save_agent_profile(
+ name='shared',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ profile_id = listing.profiles[0].id
+ assert profile_id is not None
+
+ # Both members activate the same profile independently.
+ await activate_agent_profile(
+ profile_id=profile_id, effective_org_id=org_id, user_id=uid
+ )
+ await activate_agent_profile(
+ profile_id=profile_id, effective_org_id=org_id, user_id=str(other_user_id)
+ )
+ other_member = await _read_member(async_session_maker, org_id, other_user_id)
+ assert other_member.active_agent_profile_id == profile_id
+
+ # The acting member deletes the profile.
+ await delete_agent_profile(name='shared', effective_org_id=org_id, user_id=uid)
+
+ acting_member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert acting_member.active_agent_profile_id is None
+ other_member = await _read_member(async_session_maker, org_id, other_user_id)
+ assert other_member.active_agent_profile_id is None, (
+ "other member's pointer must be cleared too"
+ )
+
+
+class TestAgentProfileRouterErrors:
+ @pytest.mark.asyncio
+ async def test_get_missing_404(self, patch_agent_routes):
+ with pytest.raises(HTTPException) as exc:
+ await get_agent_profile(
+ name='nope', effective_org_id=patch_agent_routes, user_id=str(USER_ID)
+ )
+ assert exc.value.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_delete_missing_is_idempotent_200(self, patch_agent_routes):
+ # A missing name resolves 200 (no raise), matching the ts-client
+ # AgentProfilesClient contract and the local agent-server delete_profile.
+ # Canvas's delete mutation has no 404 branch.
+ resp = await delete_agent_profile(
+ name='never-existed',
+ effective_org_id=patch_agent_routes,
+ user_id=str(USER_ID),
+ )
+ assert resp.name == 'never-existed'
+
+ @pytest.mark.asyncio
+ async def test_activate_unknown_id_404(self, patch_agent_routes):
+ with pytest.raises(HTTPException) as exc:
+ await activate_agent_profile(
+ profile_id=str(uuid.uuid4()),
+ effective_org_id=patch_agent_routes,
+ user_id=str(USER_ID),
+ )
+ assert exc.value.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_save_invalid_payload_422(self, patch_agent_routes):
+ with pytest.raises(HTTPException) as exc:
+ # cross-variant mongrel: acp_kind payload carrying llm_profile_ref
+ await save_agent_profile(
+ name='bad',
+ body={'agent_kind': 'acp', 'llm_profile_ref': 'x'},
+ effective_org_id=patch_agent_routes,
+ user_id=str(USER_ID),
+ )
+ assert exc.value.status_code == 422
+
+ @pytest.mark.asyncio
+ async def test_materialize_dangling_llm_ref_is_invalid_not_404(
+ self, patch_agent_routes
+ ):
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await save_agent_profile(
+ name='dangler',
+ body={'llm_profile_ref': 'does-not-exist'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ diag = await materialize_agent_profile(
+ name='dangler', effective_org_id=org_id, user_id=uid
+ )
+ assert diag.valid is False
+ assert any('does-not-exist' in e for e in diag.errors)
+
+ @pytest.mark.asyncio
+ async def test_materialize_valid_profile(self, patch_agent_routes):
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await save_agent_profile(
+ name='ok',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ diag = await materialize_agent_profile(
+ name='ok', effective_org_id=org_id, user_id=uid
+ )
+ assert diag.valid is True
+ assert diag.llm_profile_resolved is True
+
+
+class TestListAgentProfiles:
+ @pytest.mark.asyncio
+ async def test_empty_store_returns_empty_list_no_implicit_write(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """No auto-seed: an org with no profiles yet just gets an empty list,
+ and nothing is written (no shared profile, no pointer)."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+
+ assert isinstance(listing, AgentProfileListResponse)
+ assert listing.profiles == []
+ assert listing.active_agent_profile_id is None
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member.active_agent_profile_id is None
+
+ @pytest.mark.asyncio
+ async def test_lists_saved_profiles_and_member_pointer(
+ self, async_session_maker, patch_agent_routes
+ ):
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+
+ assert [p.name for p in listing.profiles] == ['reviewer']
+ assert listing.active_agent_profile_id is None
+
+ @pytest.mark.asyncio
+ async def test_falls_back_to_org_wide_active_pointer(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """A member with no pointer of their own resolves to the org-wide
+ default (set explicitly via activate, not by any implicit write)."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ store = AgentProfiles()
+ profile = save_profile_preserving_identity(
+ store, OpenHandsAgentProfile(name='default', llm_profile_ref='Default')
+ )
+ object.__setattr__(store, 'active', str(profile.id))
+ await _set_agent_profiles(async_session_maker, org_id, store)
+
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+
+ assert listing.active_agent_profile_id == str(profile.id)
+
+
+# ── FK guard wired into the LLM-profile router ─────────────────────────────
+
+
+def patch_org_profile_routes(async_session_maker, seeded_org):
+ async def _fake_get_org(org_id, user_id): # noqa: ARG001
+ async with async_session_maker() as session:
+ result = await session.execute(select(Org).where(Org.id == org_id))
+ return result.scalars().first()
+
+ with (
+ patch('server.routes.org_profiles.a_session_maker', async_session_maker),
+ patch(
+ 'server.routes.org_profiles.OrgService.get_org_by_id',
+ side_effect=_fake_get_org,
+ ),
+ ):
+ yield seeded_org
+
+
+async def _set_agent_profiles(async_session_maker, org_id, agent_profiles):
+ async with async_session_maker() as session:
+ org = (
+ (await session.execute(select(Org).where(Org.id == org_id)))
+ .scalars()
+ .first()
+ )
+ org.agent_profiles = agent_profiles.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
+ await session.commit()
+
+
+class TestLLMProfileFKGuard:
+ @pytest.mark.asyncio
+ async def test_delete_blocked_by_referencing_agent_profile(
+ self, async_session_maker, patch_org_profile_routes
+ ):
+ org_id = patch_org_profile_routes
+ # Reference the org's 'Default' LLM profile from an agent profile.
+ ap = AgentProfiles()
+ save_profile_preserving_identity(
+ ap, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ await _set_agent_profiles(async_session_maker, org_id, ap)
+
+ with pytest.raises(HTTPException) as exc:
+ await delete_profile(org_id=org_id, name='Default', user_id=str(USER_ID))
+ assert exc.value.status_code == 409
+ assert 'reviewer' in str(exc.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_rename_cascades_to_agent_profile_ref(
+ self, async_session_maker, patch_org_profile_routes
+ ):
+ org_id = patch_org_profile_routes
+ ap = AgentProfiles()
+ save_profile_preserving_identity(
+ ap, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ await _set_agent_profiles(async_session_maker, org_id, ap)
+
+ await rename_profile(
+ org_id=org_id,
+ name='Default',
+ request=RenameProfileRequest(new_name='Default-v2'),
+ user_id=str(USER_ID),
+ )
+
+ async with async_session_maker() as session:
+ org = (
+ (await session.execute(select(Org).where(Org.id == org_id)))
+ .scalars()
+ .first()
+ )
+ reloaded = load_agent_profiles(org)
+ assert reloaded.load('reviewer').llm_profile_ref == 'Default-v2'
+ assert 'Default-v2' in (org.llm_profiles or {}).get('profiles', {})
+
+
+# ── SaasSettingsStore resolution + provenance ──────────────────────────────
+
+
+class TestResolveActiveAgentProfile:
+ def _store(self):
+ with patch('storage.database.a_session_maker'):
+ from storage.saas_settings_store import SaasSettingsStore
+ return SaasSettingsStore(str(USER_ID))
+
+ def _org_with(self, agent_profile):
+ org = MagicMock(spec=Org)
+ org.id = ORG_ID
+ ap = AgentProfiles()
+ save_profile_preserving_identity(ap, agent_profile)
+ org.agent_profiles = ap.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
+ org.llm_profiles = {
+ 'profiles': {'Default': {'model': 'gpt-4o', 'api_key': 'orgkey'}},
+ 'active': 'Default',
+ }
+ return org, next(iter(ap.profiles))
+
+ def test_no_pointer_returns_none(self):
+ store = self._store()
+ org = MagicMock(spec=Org)
+ org.id = ORG_ID
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = None
+ assert store._resolve_active_agent_profile(org, member, {}, None) is None
+
+ def test_falls_back_to_org_wide_active_pointer_when_member_pointer_unset(self):
+ """A member with no per-member pointer of their own must still
+ resolve to the org-wide default (``AgentProfiles.active``), if one
+ happens to be set, rather than falling back to composed settings."""
+ store = self._store()
+ org, pid = self._org_with(
+ OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ ap = AgentProfiles.model_validate(org.agent_profiles)
+ ap.active = pid
+ org.agent_profiles = ap.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
+
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = None
+
+ result = store._resolve_active_agent_profile(org, member, {}, None)
+ assert result is not None
+ _dump, resolved_id, _revision = result
+ assert resolved_id == pid
+
+ def test_stale_pointer_falls_back_to_none(self):
+ store = self._store()
+ org = MagicMock(spec=Org)
+ org.id = ORG_ID
+ org.agent_profiles = None
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = str(uuid.uuid4())
+ # Profile deleted out from under the pointer -> graceful None, no raise.
+ assert store._resolve_active_agent_profile(org, member, {}, None) is None
+
+ def test_resolves_openhands_profile_and_returns_provenance(self):
+ store = self._store()
+ org, pid = self._org_with(
+ OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = pid
+
+ result = store._resolve_active_agent_profile(org, member, {}, None)
+ assert result is not None
+ dump, resolved_id, revision = result
+ assert resolved_id == pid
+ assert revision == 0
+ assert dump['agent_kind'] == 'openhands'
+ # The resolved LLM came from the referenced org LLM profile.
+ assert dump['llm']['model'] == 'gpt-4o'
+
+ def test_resolve_canonicalizes_legacy_litellm_proxy_llm(self):
+ """A profile referencing an org LLM profile with a legacy
+ ``litellm_proxy/`` managed name must resolve to the canonical
+ ``openhands/`` name (proxy base_url dropped), matching the non-profile
+ composed path so a profile launch and a plain launch normalize an
+ org's pre-canonical llm_profiles identically."""
+ from server.constants import LITE_LLM_API_URL
+
+ store = self._store()
+ org = MagicMock(spec=Org)
+ org.id = ORG_ID
+ ap = AgentProfiles()
+ save_profile_preserving_identity(
+ ap, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ pid = next(iter(ap.profiles))
+ org.agent_profiles = ap.model_dump(
+ mode='json', context={'expose_secrets': True}
+ )
+ org.llm_profiles = {
+ 'profiles': {
+ 'Default': {
+ 'model': 'litellm_proxy/claude-opus-4-8',
+ 'base_url': LITE_LLM_API_URL,
+ 'api_key': 'orgkey',
+ }
+ },
+ 'active': 'Default',
+ }
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = pid
+
+ result = store._resolve_active_agent_profile(org, member, {}, None)
+ assert result is not None
+ dump, _resolved_id, _revision = result
+ assert dump['llm']['model'] == 'openhands/claude-opus-4-8'
+ assert dump['llm'].get('base_url') is None
+
+ def test_override_id_wins_over_member_pointer(self):
+ store = self._store()
+ org, pid = self._org_with(
+ OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = None # no ambient pointer at all
+
+ result = store._resolve_active_agent_profile(
+ org, member, {}, None, override_agent_profile_id=pid
+ )
+ assert result is not None
+ _dump, resolved_id, _revision = result
+ assert resolved_id == pid
+
+ def test_override_id_does_not_mutate_member_pointer(self):
+ store = self._store()
+ org, pid = self._org_with(
+ OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ member = MagicMock(spec=OrgMember)
+ member.active_agent_profile_id = None
+
+ store._resolve_active_agent_profile(
+ org, member, {}, None, override_agent_profile_id=pid
+ )
+ # The override must never be written back to the member's own pointer.
+ assert member.active_agent_profile_id is None
+
+ @pytest.mark.asyncio
+ async def test_load_override_resolves_without_persisting_pointer(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """Loading with an explicit override_agent_profile_id resolves that
+ profile's settings and stamps its id as provenance, but leaves
+ org_member.active_agent_profile_id untouched in the database β€” the
+ one-off launch override must never persist as the new default."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ override_id = listing.profiles[0].id
+ assert override_id is not None
+ # The member has NO active pointer at all β€” the ambient default path
+ # would return composed settings, not this profile.
+ member_before = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member_before.active_agent_profile_id is None
+
+ # Settings.enable_sound_notifications is non-nullable but the User
+ # column defaults to NULL; seeded_org doesn't set it since no other
+ # test in this file exercises a full load().
+ async with async_session_maker() as session:
+ user = await session.get(User, USER_ID)
+ user.enable_sound_notifications = True
+ await session.commit()
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ 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),
+ ):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load(override_agent_profile_id=override_id)
+
+ assert settings is not None
+ assert settings.active_agent_profile_id == override_id
+
+ member_after = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member_after.active_agent_profile_id is None
+
+
+# ── Persisted vs resolved settings views ────────────────────────────────────
+
+
+async def _read_org_raw(async_session_maker, org_id):
+ async with async_session_maker() as session:
+ result = await session.execute(select(Org).where(Org.id == org_id))
+ return result.scalars().first()
+
+
+MEMBER_MCP_SERVERS = {
+ 'a': {'url': 'https://a.example/mcp'},
+ 'b': {'url': 'https://b.example/mcp'},
+ 'c': {'url': 'https://c.example/mcp'},
+}
+
+
+class TestPersistedVsResolvedSettingsView:
+ """Plain load() is the persisted view; resolution is a launch-only opt-in
+ whose result store() refuses, so a profile's resolved dump (ref-filtered
+ mcp_config, the referenced LLM profile's key) can never round-trip into
+ the member/org rows."""
+
+ async def _setup_active_profile(self, async_session_maker, org_id, mcp_server_refs):
+ """Profile with the given refs, member pointed at it, member
+ mcp_config with three servers, full load() viable."""
+ ap = AgentProfiles()
+ profile = save_profile_preserving_identity(
+ ap,
+ OpenHandsAgentProfile(
+ name='reviewer',
+ llm_profile_ref='Default',
+ mcp_server_refs=mcp_server_refs,
+ ),
+ )
+ await _set_agent_profiles(async_session_maker, org_id, ap)
+ async with async_session_maker() as session:
+ user = await session.get(User, USER_ID)
+ user.enable_sound_notifications = True
+ member = (
+ (
+ await session.execute(
+ select(OrgMember).where(
+ OrgMember.org_id == org_id,
+ OrgMember.user_id == USER_ID,
+ )
+ )
+ )
+ .scalars()
+ .first()
+ )
+ member.active_agent_profile_id = str(profile.id)
+ member.agent_settings_diff = {
+ 'llm': {
+ 'model': 'gpt-4o',
+ 'base_url': 'https://api.openai.com/v1',
+ },
+ 'mcp_config': {'mcpServers': dict(MEMBER_MCP_SERVERS)},
+ }
+ await session.commit()
+ return profile
+
+ def _store_patches(self, async_session_maker):
+ from contextlib import ExitStack
+
+ stack = ExitStack()
+ stack.enter_context(
+ patch('storage.saas_settings_store.a_session_maker', async_session_maker)
+ )
+ stack.enter_context(
+ patch('storage.user_store.a_session_maker', async_session_maker)
+ )
+ stack.enter_context(
+ patch('storage.org_store.a_session_maker', async_session_maker)
+ )
+ return stack
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize('refs', [['a'], []])
+ async def test_plain_load_round_trip_preserves_member_mcp_config(
+ self, async_session_maker, patch_agent_routes, refs
+ ):
+ """F1: a routine load() -> store() round-trip (e.g. a settings PATCH
+ touching an unrelated field) while a ref-filtering profile is active
+ must not rewrite the member's mcp_config with the filtered view."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await self._setup_active_profile(async_session_maker, org_id, refs)
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ with self._store_patches(async_session_maker):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load()
+
+ # The persisted view: no profile resolution happened.
+ assert settings is not None
+ assert settings.active_agent_profile_id is None
+ assert settings.agent_settings.mcp_config is not None
+ assert set(settings.agent_settings.mcp_config) == {
+ 'a',
+ 'b',
+ 'c',
+ }
+
+ settings.enable_sound_notifications = False # the unrelated edit
+ await store.store(settings)
+
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ stored_mcp = member.agent_settings_diff.get('mcp_config') or {}
+ assert set(stored_mcp) == {'a', 'b', 'c'}
+
+ @pytest.mark.asyncio
+ async def test_plain_round_trip_keeps_member_llm_key(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """F2: a routine save while a profile is active must not overwrite the
+ member's own LLM key with the referenced LLM profile's key."""
+ from storage.encrypt_utils import decrypt_value
+
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await self._setup_active_profile(async_session_maker, org_id, ['a'])
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ with self._store_patches(async_session_maker):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load()
+ assert settings is not None
+ # The persisted view carries the member's effective key, not the
+ # 'Default' LLM profile's key ('k').
+ assert settings.agent_settings.llm.api_key is not None
+ assert (
+ settings.agent_settings.llm.api_key.get_secret_value() == 'initial-key'
+ )
+
+ settings.enable_sound_notifications = False
+ await store.store(settings)
+
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert decrypt_value(member._llm_api_key) == 'initial-key'
+
+ @pytest.mark.asyncio
+ async def test_shared_agent_settings_edit_persists_while_profile_active(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """F3: with a profile active, org-level agent-settings edits made
+ through the settings API must still persist (no silent write-drop)."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await self._setup_active_profile(async_session_maker, org_id, ['a'])
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ with self._store_patches(async_session_maker):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load()
+ assert settings is not None
+ settings.agent_settings = settings.agent_settings.model_copy(
+ update={'enable_sub_agents': True}
+ )
+ await store.store(settings)
+
+ org = await _read_org_raw(async_session_maker, org_id)
+ assert (org.agent_settings or {}).get('enable_sub_agents') is True
+
+ @pytest.mark.asyncio
+ async def test_resolved_load_is_launch_view_and_store_refuses_it(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """resolve_agent_profile=True returns the resolved launch view (the
+ profile replaces agent_settings) and store() refuses that object."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ profile = await self._setup_active_profile(async_session_maker, org_id, ['a'])
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ with self._store_patches(async_session_maker):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load(resolve_agent_profile=True)
+
+ assert settings is not None
+ assert settings.active_agent_profile_id == str(profile.id)
+ assert settings.active_agent_profile_revision == profile.revision
+ # mcp_server_refs=['a'] filtered the member's three servers.
+ assert settings.agent_settings.mcp_config is not None
+ assert set(settings.agent_settings.mcp_config) == {'a'}
+ # The resolved LLM is the referenced 'Default' org LLM profile.
+ assert settings.agent_settings.llm.model == 'gpt-4o'
+
+ with pytest.raises(ValueError, match='resolved Agent-Profile'):
+ await store.store(settings)
+
+ @pytest.mark.asyncio
+ async def test_resolver_crash_falls_back_to_composed_settings(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """F5: an unexpected resolver exception (e.g. an SDK signature change
+ raising TypeError) degrades to the composed settings, never a 500."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+ await self._setup_active_profile(async_session_maker, org_id, ['a'])
+
+ from storage.saas_settings_store import SaasSettingsStore
+
+ with (
+ self._store_patches(async_session_maker),
+ patch(
+ 'storage.saas_settings_store.resolve_agent_profile',
+ side_effect=TypeError(
+ 'resolve_agent_profile() missing 1 required '
+ "keyword-only argument: 'available_skills'"
+ ),
+ ),
+ ):
+ store = SaasSettingsStore(uid, effective_org_id=org_id)
+ settings = await store.load(resolve_agent_profile=True)
+
+ assert settings is not None
+ assert settings.active_agent_profile_id is None
+ assert settings.agent_settings.mcp_config is not None
+ assert set(settings.agent_settings.mcp_config) == {'a', 'b', 'c'}
+
+
+# ── Best-effort load must not amplify into data loss ────────────────────────
+
+
+class TestNoWriteBackWithoutMutation:
+ @pytest.mark.asyncio
+ async def test_activate_preserves_unparseable_profile(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """F4: /activate is pointer-only β€” it must not serialize the (best-
+ effort loaded) collection back, which would silently erase a stored
+ profile that merely failed to parse."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+ listing = await list_agent_profiles(effective_org_id=org_id, user_id=uid)
+ valid_id = listing.profiles[0].id
+
+ # Simulate schema drift: a stored entry the current model rejects
+ # (name violates min_length) β€” _skip_invalid_profiles drops it on load.
+ invalid_id = str(uuid.uuid4())
+ org = await _read_org_raw(async_session_maker, org_id)
+ blob_before = dict(org.agent_profiles)
+ blob_before['profiles'] = {
+ **blob_before['profiles'],
+ invalid_id: {'name': '', 'agent_kind': 'openhands'},
+ }
+ async with async_session_maker() as session:
+ org = (
+ (await session.execute(select(Org).where(Org.id == org_id)))
+ .scalars()
+ .first()
+ )
+ org.agent_profiles = blob_before
+ await session.commit()
+
+ result = await activate_agent_profile(
+ profile_id=valid_id, effective_org_id=org_id, user_id=uid
+ )
+ assert isinstance(result, ActivateAgentProfileResponse)
+
+ member = await _read_member(async_session_maker, org_id, USER_ID)
+ assert member.active_agent_profile_id == valid_id
+ org = await _read_org_raw(async_session_maker, org_id)
+ # The blob is byte-for-byte untouched: the unparseable entry survives.
+ assert org.agent_profiles == blob_before
+ assert invalid_id in org.agent_profiles['profiles']
+
+ @pytest.mark.asyncio
+ async def test_materialize_survives_dry_run_crash(
+ self, async_session_maker, patch_agent_routes
+ ):
+ """F5 (router): a dry-run resolver crash surfaces as an invalid
+ diagnostics report, not a 500."""
+ org_id = patch_agent_routes
+ uid = str(USER_ID)
+
+ await save_agent_profile(
+ name='reviewer',
+ body={'llm_profile_ref': 'Default'},
+ effective_org_id=org_id,
+ user_id=uid,
+ )
+
+ with patch(
+ 'server.routes.agent_profiles.resolve_agent_profile_dry_run',
+ side_effect=TypeError(
+ 'resolve_agent_profile_dry_run() missing 1 required '
+ "keyword-only argument: 'available_skills'"
+ ),
+ ):
+ diagnostics = await materialize_agent_profile(
+ name='reviewer', effective_org_id=org_id, user_id=uid
+ )
+
+ assert diagnostics.valid is False
+ assert any('Failed to resolve profile' in e for e in diagnostics.errors)
+
+
+# ── Router permission-boundary integration (real HTTP, real Depends chain) ──
+#
+# Every other test above calls the route handler *functions* directly, so
+# ``require_permission``/``EFFECTIVE_ORG_ID`` never actually run -- the tests
+# supply ``user_id``/``effective_org_id`` as plain kwargs. These tests mount
+# the real router behind a ``TestClient`` so the actual FastAPI dependency
+# chain executes, proving the VIEW/EDIT_ORG_SETTINGS gate for real rather
+# than by inspection (mirrors ``test_org_git_claims.py``'s pattern, which
+# neither ``org_profiles.py`` nor ``agent_profiles.py`` had before).
+
+
+def agent_profiles_app():
+ """Real app mounting the actual router. ``get_user_id`` is overridden
+ (identity only); org resolution stays on the real code path but is
+ pinned to ``ORG_ID`` on both sides (``EFFECTIVE_ORG_ID`` and
+ ``require_permission``'s own no-path-org_id fallback) so they agree,
+ same as a legitimate single-org request would. ``get_user_org_role`` is
+ left unpatched here -- each test controls it to select the role under
+ test.
+ """
+ from server.auth.org_context import resolve_effective_org_id
+
+ app = FastAPI()
+ app.include_router(agent_profiles_router)
+ app.dependency_overrides[get_user_id] = lambda: str(USER_ID)
+ app.dependency_overrides[resolve_effective_org_id] = lambda: ORG_ID
+ with (
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(return_value=ORG_ID),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=None),
+ ),
+ ):
+ yield app
+
+
+def _role(name):
+ role = MagicMock()
+ role.name = name
+ return role
+
+
+class TestAgentProfilesRouterAuthorizationBoundary:
+ def test_member_gets_403_on_save(self, agent_profiles_app):
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_role('member')),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.post(
+ '/api/agent-profiles/reviewer', json={'llm_profile_ref': 'Default'}
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'edit_org_settings' in response.json()['detail'].lower()
+
+ def test_member_gets_403_on_delete(self, agent_profiles_app):
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_role('member')),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.delete('/api/agent-profiles/reviewer')
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'edit_org_settings' in response.json()['detail'].lower()
+
+ def test_member_gets_403_on_rename(self, agent_profiles_app):
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_role('member')),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.post(
+ '/api/agent-profiles/reviewer/rename', json={'new_name': 'renamed'}
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'edit_org_settings' in response.json()['detail'].lower()
+
+ def test_non_member_gets_403_on_list(self, agent_profiles_app):
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.get('/api/agent-profiles')
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'not a member' in response.json()['detail'].lower()
+
+ def test_non_member_gets_403_on_save(self, agent_profiles_app):
+ """A non-admin lacking even VIEW_ORG_SETTINGS must not reach the
+ EDIT_ORG_SETTINGS check via some other path either."""
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.post(
+ '/api/agent-profiles/reviewer', json={'llm_profile_ref': 'Default'}
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'not a member' in response.json()['detail'].lower()
+
+ @pytest.mark.asyncio
+ async def test_member_can_list_profiles_200(
+ self, agent_profiles_app, async_session_maker, patch_agent_routes
+ ):
+ """A MEMBER has VIEW_ORG_SETTINGS -- the read path must stay open;
+ the fix for the write-side gap must not overshoot into blocking
+ legitimate reads."""
+ org_id = patch_agent_routes
+ ap = AgentProfiles()
+ save_profile_preserving_identity(
+ ap, OpenHandsAgentProfile(name='reviewer', llm_profile_ref='Default')
+ )
+ await _set_agent_profiles(async_session_maker, org_id, ap)
+
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_role('member')),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.get('/api/agent-profiles')
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [p['name'] for p in response.json()['profiles']] == ['reviewer']
+
+ @pytest.mark.asyncio
+ async def test_admin_can_save_profile_201(
+ self, agent_profiles_app, async_session_maker, patch_agent_routes
+ ):
+ """An ADMIN has EDIT_ORG_SETTINGS -- the write path must stay open."""
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_role('admin')),
+ ):
+ client = TestClient(agent_profiles_app)
+ response = client.post(
+ '/api/agent-profiles/reviewer', json={'llm_profile_ref': 'Default'}
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
diff --git a/enterprise/tests/unit/test_authorization.py b/enterprise/tests/unit/test_authorization.py
index d93a7ab71b..1c7d5cfd2d 100644
--- a/enterprise/tests/unit/test_authorization.py
+++ b/enterprise/tests/unit/test_authorization.py
@@ -145,6 +145,8 @@ class TestRolePermissions:
assert Permission.MANAGE_MCP in owner_perms
assert Permission.VIEW_LLM_SETTINGS in owner_perms
assert Permission.EDIT_LLM_SETTINGS in owner_perms
+ assert Permission.VIEW_ORG_SETTINGS in owner_perms
+ assert Permission.EDIT_ORG_SETTINGS in owner_perms
assert Permission.VIEW_BILLING in owner_perms
assert Permission.ADD_CREDITS in owner_perms
assert Permission.INVITE_USER_TO_ORGANIZATION in owner_perms
@@ -168,6 +170,8 @@ class TestRolePermissions:
assert Permission.MANAGE_MCP in admin_perms
assert Permission.VIEW_LLM_SETTINGS in admin_perms
assert Permission.EDIT_LLM_SETTINGS in admin_perms
+ assert Permission.VIEW_ORG_SETTINGS in admin_perms
+ assert Permission.EDIT_ORG_SETTINGS in admin_perms
assert Permission.VIEW_BILLING in admin_perms
assert Permission.ADD_CREDITS in admin_perms
assert Permission.INVITE_USER_TO_ORGANIZATION in admin_perms
@@ -199,6 +203,7 @@ class TestRolePermissions:
assert Permission.VIEW_ORG_SETTINGS in member_perms
# Member should NOT have admin/owner permissions
assert Permission.EDIT_LLM_SETTINGS not in member_perms
+ assert Permission.EDIT_ORG_SETTINGS not in member_perms
assert Permission.MANAGE_INTEGRATION_PROVIDERS not in member_perms
assert Permission.VIEW_BILLING not in member_perms
assert Permission.ADD_CREDITS not in member_perms
@@ -728,6 +733,143 @@ class TestRequirePermission:
assert 'not a member' in exc_info.value.detail
[email protected]('_no_super_role')
+class TestRequirePermissionQueryStringOrgIdBypass:
+ """Regression tests for a cross-org privilege-escalation bypass.
+
+ On routes with no ``{org_id}`` path segment (e.g. the flat
+ ``EFFECTIVE_ORG_ID``-scoped routes), FastAPI has no path value to bind
+ ``permission_checker``'s own ``org_id`` parameter to, so it silently
+ falls back to binding it from an ordinary, client-controlled query
+ string. Previously that query-string value was trusted directly,
+ letting a caller supply ``?org_id=<org they administer>`` to pass the
+ permission check while the route handler itself operates on a
+ *different* org (resolved separately from ``X-Org-Id`` via
+ ``EFFECTIVE_ORG_ID``). These tests pin the fix: such a route must
+ always ignore query-string ``org_id`` and re-resolve the target org via
+ ``resolve_target_org_id_for_permission_check`` -- the same resolver
+ ``EFFECTIVE_ORG_ID`` uses -- so the two can never diverge.
+ """
+
+ @pytest.mark.asyncio
+ async def test_query_string_org_id_is_ignored_without_path_org_id(self):
+ """
+ GIVEN: A route with no {org_id} path segment; the caller is only a
+ MEMBER of org_a (the request's real effective org) but is
+ OWNER of org_b
+ WHEN: The caller supplies ?org_id=<org_b> as a query-string override
+ THEN: org_b is discarded -- the permission check queries org_a (via
+ resolve_target_org_id_for_permission_check) and denies the
+ member-role caller EDIT_ORG_SETTINGS
+ """
+ user_id = str(uuid4())
+ org_a = uuid4() # the request's real effective org; caller is a mere member
+ org_b = uuid4() # an org the caller owns -- smuggled in via ?org_id=
+
+ mock_request = _create_mock_request()
+ mock_request.path_params = {}
+
+ member_role = MagicMock()
+ member_role.name = 'member'
+
+ async def fake_get_user_org_role(_user_id, queried_org_id):
+ assert queried_org_id == org_a, (
+ 'permission check queried the attacker-supplied org_id '
+ "instead of the request's real effective org"
+ )
+ return member_role
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(side_effect=fake_get_user_org_role),
+ ),
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(return_value=org_a),
+ ),
+ ):
+ permission_checker = require_permission(Permission.EDIT_ORG_SETTINGS)
+ with pytest.raises(HTTPException) as exc_info:
+ await permission_checker(
+ request=mock_request, org_id=org_b, user_id=user_id
+ )
+
+ assert exc_info.value.status_code == 403
+
+ @pytest.mark.asyncio
+ async def test_legitimate_no_query_org_id_still_resolves_effective_org(self):
+ """
+ GIVEN: A route with no {org_id} path segment and no query-string
+ org_id supplied (the only legitimate shape before this fix)
+ WHEN: Permission checker runs
+ THEN: It still falls through to
+ resolve_target_org_id_for_permission_check -- unchanged
+ pre-existing behavior for the honest case
+ """
+ user_id = str(uuid4())
+ org_a = uuid4()
+
+ mock_request = _create_mock_request()
+ mock_request.path_params = {}
+
+ admin_role = MagicMock()
+ admin_role.name = 'admin'
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=admin_role),
+ ) as mock_get_role,
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(return_value=org_a),
+ ),
+ ):
+ permission_checker = require_permission(Permission.EDIT_ORG_SETTINGS)
+ result = await permission_checker(
+ request=mock_request, org_id=None, user_id=user_id
+ )
+
+ assert result == user_id
+ mock_get_role.assert_awaited_once_with(user_id, org_a)
+
+ @pytest.mark.asyncio
+ async def test_path_scoped_org_id_is_still_trusted_directly(self):
+ """
+ GIVEN: A route WITH an {org_id} path segment (path_params carries it)
+ WHEN: Permission checker runs
+ THEN: The path-bound org_id is used directly with no fallback
+ resolver call -- preserving org_profiles.py-style semantics
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+
+ mock_request = _create_mock_request()
+ mock_request.path_params = {'org_id': str(org_id)}
+
+ admin_role = MagicMock()
+ admin_role.name = 'admin'
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=admin_role),
+ ) as mock_get_role,
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(side_effect=AssertionError('should not be called')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.EDIT_ORG_SETTINGS)
+ result = await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+
+ assert result == user_id
+ mock_get_role.assert_awaited_once_with(user_id, org_id)
+
+
# =============================================================================
# Tests for permission-based access control scenarios
# =============================================================================
diff --git a/enterprise/tests/unit/test_org_profiles.py b/enterprise/tests/unit/test_org_profiles.py
index fd18bafad6..d0c3caaf14 100644
--- a/enterprise/tests/unit/test_org_profiles.py
+++ b/enterprise/tests/unit/test_org_profiles.py
@@ -155,16 +155,26 @@ class TestRenameProfileRequest:
def test_name_validation(self):
"""Test name length validation."""
# Should accept reasonable names
- request = RenameProfileRequest(new_name='a' * 100)
- assert len(request.new_name) == 100
+ request = RenameProfileRequest(new_name='a' * 64)
+ assert len(request.new_name) == 64
# Should reject empty names (min_length=1)
with pytest.raises(ValueError):
RenameProfileRequest(new_name='')
- # Should reject too-long names (max_length=100)
+ # Should reject too-long names (max_length=64, matching the SDK's
+ # PROFILE_NAME_PATTERN enforced by rename_llm_profile).
with pytest.raises(ValueError):
- RenameProfileRequest(new_name='a' * 101)
+ RenameProfileRequest(new_name='a' * 65)
+
+ def test_name_pattern_validation(self):
+ """new_name must satisfy PROFILE_NAME_PATTERN, matching what
+ rename_llm_profile actually enforces (else this 422s deep in the
+ handler instead of at the request-schema boundary)."""
+ with pytest.raises(ValueError):
+ RenameProfileRequest(new_name='has a space')
+ with pytest.raises(ValueError):
+ RenameProfileRequest(new_name='has/slash')
# ── Integration tests ──────────────────────────────────────────────────────
diff --git a/enterprise/tests/unit/test_saas_settings_store.py b/enterprise/tests/unit/test_saas_settings_store.py
index cf3aee5861..52b891c659 100644
--- a/enterprise/tests/unit/test_saas_settings_store.py
+++ b/enterprise/tests/unit/test_saas_settings_store.py
@@ -631,6 +631,71 @@ async def test_store_updates_org_defaults_and_all_members_for_shared_keys(
assert decrypt_value(member._llm_api_key) == 'shared-external-api-key'
+async def test_store_rejects_resolved_profile_settings_view(
+ session_maker, async_session_maker, org_with_multiple_members_fixture
+):
+ """``store()`` refuses a resolved Agent-Profile launch view outright.
+
+ A resolved view (``load(resolve_agent_profile=True)`` / an override) is
+ the profile's dump β€” ref-filtered ``mcp_config``, the referenced LLM
+ profile's key β€” not user-authored settings. Persisting it would corrupt
+ the member/org rows, so ``store()`` raises before writing anything.
+ """
+ from sqlalchemy import select
+ from storage.org import Org
+ from storage.org_member import OrgMember
+
+ fixture = org_with_multiple_members_fixture
+ org_id = fixture['org_id']
+ admin_user_id = str(fixture['admin_user_id'])
+
+ store = SaasSettingsStore(admin_user_id)
+ resolved_settings = _make_settings(
+ model='anthropic/claude-sonnet-4',
+ base_url='https://api.anthropic.com/v1',
+ api_key='profile-resolved-secret-key',
+ )
+ # Marks agent_settings as profile-resolved, exactly as load() would when
+ # the caller requested resolution and the member has an active profile.
+ resolved_settings.active_agent_profile_id = 'profile-1'
+ resolved_settings.active_agent_profile_revision = 3
+ resolved_settings.enable_sound_notifications = True
+
+ with patch('storage.saas_settings_store.a_session_maker', async_session_maker):
+ with pytest.raises(ValueError, match='resolved Agent-Profile'):
+ await store.store(resolved_settings)
+
+ # The private marker alone (a resolved load that fell back carries no
+ # active_agent_profile_id) must also be refused.
+ marked_settings = _make_settings(model='gpt-4o')
+ marked_settings._resolved_view = True
+ with pytest.raises(ValueError, match='resolved Agent-Profile'):
+ await store.store(marked_settings)
+
+ with session_maker() as session:
+ org = session.execute(select(Org).where(Org.id == org_id)).scalars().first()
+ assert org is not None
+ # Nothing was written before the guard fired.
+ assert (org.agent_settings or {}).get('llm', {}).get('model') != (
+ 'anthropic/claude-sonnet-4'
+ )
+
+ members = {
+ str(member.user_id): member
+ for member in session.execute(
+ select(OrgMember).where(OrgMember.org_id == org_id)
+ )
+ .scalars()
+ .all()
+ }
+ member1 = members[str(fixture['member1_user_id'])]
+ member2 = members[str(fixture['member2_user_id'])]
+ # Other members keep their own pre-existing LLM, untouched.
+ assert member1.agent_settings_diff['llm']['model'] == 'old-model-v2'
+ assert member2.agent_settings_diff['llm']['model'] == 'old-model-v3'
+
+
@pytest.mark.asyncio
async def test_store_keeps_openhands_managed_keys_member_specific(
session_maker, async_session_maker, org_with_multiple_members_fixture
diff --git a/openhands/app_server/app_conversation/app_conversation_models.py b/openhands/app_server/app_conversation/app_conversation_models.py
index ac668ec450..ccf6ca0c44 100644
--- a/openhands/app_server/app_conversation/app_conversation_models.py
+++ b/openhands/app_server/app_conversation/app_conversation_models.py
@@ -23,6 +23,7 @@ from openhands.app_server.settings.settings_models import SandboxGroupingStrateg
from openhands.sdk.conversation import ConversationExecutionStatus
from openhands.sdk.llm import MetricsSnapshot
from openhands.sdk.plugin import PluginSource
+from openhands.sdk.profiles import LaunchedAgentProfile
__all__ = ['SandboxGroupingStrategy']
@@ -38,6 +39,13 @@ ACP_SERVER_TAG_KEY = 'acpserver'
# rule β€” no underscores.
ARCHIVE_WORKSPACE_PATH_TAG_KEY = 'archiveworkspacepath'
+# Conversation-tag keys recording which Agent Profile launched the conversation
+# (provenance). Ride the tags dict + a @computed_field exactly like
+# ``acp_server`` so the projection is zero-migration. The SDK ^[a-z0-9]+$
+# tag-key rule forbids underscores, hence the squashed keys.
+AGENT_PROFILE_ID_TAG_KEY = 'agentprofileid'
+AGENT_PROFILE_REVISION_TAG_KEY = 'agentprofilerevision'
+
class ConversationTrigger(Enum):
RESOLVER = 'resolver'
@@ -145,6 +153,30 @@ class AppConversationInfo(BaseModel):
return None
return self.tags.get(ACP_SERVER_TAG_KEY)
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def launched_agent_profile(self) -> LaunchedAgentProfile | None:
+ """Provenance of the Agent Profile that launched this conversation, else None.
+
+ A typed projection of the ``agentprofileid`` / ``agentprofilerevision``
+ tags (same pattern as ``acp_server``), so it round-trips through the DB
+ ``tags`` column for free. Canvas reads exactly
+ ``launched_agent_profile { agent_profile_id, revision }``.
+ """
+ pid = self.tags.get(AGENT_PROFILE_ID_TAG_KEY)
+ if not pid:
+ return None
+ rev_raw = self.tags.get(AGENT_PROFILE_REVISION_TAG_KEY)
+ try:
+ revision = int(rev_raw) if rev_raw is not None else 0
+ except (TypeError, ValueError):
+ revision = 0
+ try:
+ return LaunchedAgentProfile(agent_profile_id=UUID(pid), revision=revision)
+ except ValueError:
+ # Malformed id tag β€” surface no provenance rather than 500 the list.
+ return None
+
class AppConversationSortOrder(Enum):
CREATED_AT = 'CREATED_AT'
@@ -200,6 +232,10 @@ class AppConversationStartRequest(OpenHandsModel):
system_message_suffix: str | None = None
processors: list[EventCallbackProcessor] | None = Field(default=None)
llm_model: str | None = None
+ # One-off launch override: run THIS conversation from a specific Agent
+ # Profile (by id) without changing the member's active pointer. When unset,
+ # the member's active_agent_profile_id is used.
+ agent_profile_id: str | None = None
# Git parameters
selected_repository: str | None = None
diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
index b426b72f97..6d04114ad4 100644
--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py
+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
@@ -26,6 +26,8 @@ from openhands.app_server.app_conversation.app_conversation_info_service import
)
from openhands.app_server.app_conversation.app_conversation_models import (
ACP_SERVER_TAG_KEY,
+ AGENT_PROFILE_ID_TAG_KEY,
+ AGENT_PROFILE_REVISION_TAG_KEY,
ARCHIVE_WORKSPACE_PATH_TAG_KEY,
AgentType,
AppConversation,
@@ -215,6 +217,25 @@ def append_system_context(existing: str | None, block: str) -> str:
return f'{existing.rstrip()}\n\n{block}'
+def effective_disabled_skills(user: UserInfo) -> list[str]:
+ """Union of the member-level and launched-profile-level skill deny-lists.
+
+ A skill disabled at EITHER level stays off. The member's deny-list rides
+ ``user.disabled_skills``; the launched Agent Profile's rides the resolved
+ ``agent_settings.agent_context.disabled_skills`` (the SDK resolver stamps the
+ profile's ``disabled_skills`` there β€” #4017). On a non-profile launch the
+ resolved context's deny-list is empty, so this is just the member's list.
+ Order-preserving de-dup. Because it is a deny-list, a name absent from the
+ discovered catalog is a harmless no-op, so no reconciliation is needed
+ between the two sources.
+ """
+ member = list(user.disabled_skills or [])
+ agent_settings = getattr(user, 'agent_settings', None)
+ agent_context = getattr(agent_settings, 'agent_context', None)
+ profile = list(getattr(agent_context, 'disabled_skills', None) or [])
+ return list(dict.fromkeys([*member, *profile]))
+
+
@dataclass
class LiveStatusAppConversationService(AppConversationServiceBase):
"""AppConversationService which combines live status info from the sandbox with stored data."""
@@ -431,6 +452,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
selected_branch=request.selected_branch,
plugins=request.plugins,
api_secrets=request.secrets,
+ agent_profile_id=request.agent_profile_id,
)
)
@@ -494,6 +516,25 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
# archive captures the right directory without re-deriving the path
# from settings (e.g. grouping) that may change before delete.
tags[ARCHIVE_WORKSPACE_PATH_TAG_KEY] = working_dir
+ # Stamp Agent Profile provenance. The launched profile resolved into
+ # the launched ``agent_settings`` (a resolve-requested load carries
+ # its id + revision onto UserInfo); ride the tags dict so it
+ # round-trips and surfaces as the ``launched_agent_profile``
+ # computed field. Resolves with the same override the launch itself
+ # used, so provenance reflects what actually ran even when the
+ # request carried a one-off ``agent_profile_id``.
+ profile_user = await self.user_context.get_user_info(
+ resolve_agent_profile=True,
+ override_agent_profile_id=request.agent_profile_id,
+ )
+ launched_profile_id = getattr(profile_user, 'active_agent_profile_id', None)
+ if isinstance(launched_profile_id, str) and launched_profile_id:
+ tags[AGENT_PROFILE_ID_TAG_KEY] = launched_profile_id
+ launched_revision = getattr(
+ profile_user, 'active_agent_profile_revision', None
+ )
+ if isinstance(launched_revision, int):
+ tags[AGENT_PROFILE_REVISION_TAG_KEY] = str(launched_revision)
if request_agent.agent_kind == 'acp':
llm_model = request_agent.acp_model
agent_kind = 'acp'
@@ -501,9 +542,12 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
# can resolve a brand label ("Claude Code", "Codex", …) via
# the SDK registry without keeping a per-conversation column.
# Surfaced to the UI as the projected ``acp_server`` field.
- acp_user = await self.user_context.get_user_info()
- if isinstance(acp_user.agent_settings, ACPAgentSettings):
- tags[ACP_SERVER_TAG_KEY] = acp_user.agent_settings.acp_server
+ # Reuses ``profile_user`` (resolved above with the same
+ # override) rather than re-fetching β€” a second fetch would
+ # both double the settings-resolution cost and risk a
+ # different profile resolving if it changed in between.
+ if isinstance(profile_user.agent_settings, ACPAgentSettings):
+ tags[ACP_SERVER_TAG_KEY] = profile_user.agent_settings.acp_server
else:
llm_model = request_agent.llm.model
agent_kind = 'openhands'
@@ -1245,10 +1289,12 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
Args:
mcp_servers: Dictionary to add servers to
user: User information containing custom MCP config
- """
- if isinstance(user.agent_settings, ACPAgentSettings):
- return
+ Handles both OpenHands and ACP agent settings: a resolved ACP profile's
+ ref-filtered ``mcp_config`` rides on ``ACPAgentSettings.mcp_config`` and
+ must reach ``create_agent`` (the ACP-only early-return that previously
+ dropped it is gone β€” SDK#3705 remainder, #15044 Β§7).
+ """
user_mcp = user.agent_settings.mcp_config
if not user_mcp:
return
@@ -1577,6 +1623,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
selected_branch: str | None = None,
plugins: list[PluginSpec] | None = None,
api_secrets: dict[str, SecretStr] | None = None,
+ agent_profile_id: str | None = None,
) -> StartConversationRequest:
"""Build a complete StartConversationRequest for a user.
@@ -1606,8 +1653,17 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
These are merged with existing secrets (from database
and git providers), with API-provided secrets taking
precedence.
+ agent_profile_id: One-off Agent Profile override for this
+ conversation only (cloud-only; does not change the member's
+ active pointer). ``None`` uses the ambient active profile.
"""
- user = await self.user_context.get_user_info()
+ # Conversation start builds the agent, so it consumes the RESOLVED
+ # (effective launch) view; plain settings reads/round-trips elsewhere
+ # stay on the persisted view.
+ user = await self.user_context.get_user_info(
+ resolve_agent_profile=True,
+ override_agent_profile_id=agent_profile_id,
+ )
# Compose instance + org + user marketplaces once for both arms below.
# Enabled by default; inert (None) only when ENABLE_MARKETPLACE_PLUGIN_LOADING
@@ -1629,6 +1685,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
remote_workspace=remote_workspace,
plugins=plugins,
api_secrets=api_secrets,
+ agent_profile_id=agent_profile_id,
)
if remote_workspace:
acp_request = await self._load_skills_onto_request(
@@ -1637,7 +1694,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
remote_workspace,
selected_repository,
get_project_dir(working_dir, selected_repository),
- user.disabled_skills,
+ effective_disabled_skills(user),
registered_marketplaces,
)
return acp_request
@@ -1854,7 +1911,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
remote_workspace,
selected_repository,
project_dir,
- user.disabled_skills,
+ effective_disabled_skills(user),
registered_marketplaces,
)
@@ -1932,6 +1989,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
remote_workspace: AsyncRemoteWorkspace | None = None,
plugins: list[PluginSpec] | None = None,
api_secrets: dict[str, SecretStr] | None = None,
+ agent_profile_id: str | None = None,
) -> StartConversationRequest:
"""Build a StartConversationRequest for ACP agent conversations.
@@ -1959,8 +2017,14 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
resolve the HEAD commit for the Laminar trace metadata.
plugins: Optional list of plugins to load
api_secrets: Optional secrets passed directly via the API.
+ agent_profile_id: One-off Agent Profile override for this
+ conversation only (cloud-only; does not change the member's
+ active pointer). ``None`` uses the ambient active profile.
"""
- user = await self.user_context.get_user_info()
+ user = await self.user_context.get_user_info(
+ resolve_agent_profile=True,
+ override_agent_profile_id=agent_profile_id,
+ )
project_dir = get_project_dir(working_dir, selected_repository)
workspace = LocalWorkspace(working_dir=project_dir)
@@ -2040,6 +2104,14 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
update={'api_key': None, 'base_url': None}
),
}
+ # Forward the resolved profile's / user's custom MCP servers to the ACP
+ # subprocess (#15044 Β§7). Only custom servers β€” the system OpenHands MCP
+ # server (Tavily proxy) is runtime-internal and unreachable by an external
+ # ACP CLI, so it is intentionally not injected here.
+ acp_mcp_servers: dict[str, MCPServer] = {}
+ self._merge_custom_mcp_config(acp_mcp_servers, user)
+ if acp_mcp_servers:
+ settings_update['mcp_config'] = acp_mcp_servers
if system_message_suffix:
settings_update['agent_context'] = AgentContext(
system_message_suffix=system_message_suffix
diff --git a/openhands/app_server/settings/agent_profiles.py b/openhands/app_server/settings/agent_profiles.py
new file mode 100644
index 0000000000..9c877c66ad
--- /dev/null
+++ b/openhands/app_server/settings/agent_profiles.py
@@ -0,0 +1,236 @@
+"""Cloud container for saved ``AgentProfile`` launch specs.
+
+The Agent-Profile analogue of :class:`~openhands.app_server.settings.llm_profiles.LLMProfiles`,
+one level up: an :class:`~openhands.sdk.profiles.AgentProfile` *references* an LLM
+profile (``llm_profile_ref``) and a subset of the user's MCP servers
+(``mcp_server_refs``) rather than embedding the resolved ``llm`` / ``mcp_config``.
+
+Two responsibilities, kept deliberately thin:
+
+* a pydantic envelope ``{profiles: {<id>: AgentProfile}, active: <id> | null}`` stored
+ on the ``org.agent_profiles`` ``EncryptedJSON`` column (mirrors ``org.llm_profiles``);
+* an :class:`~openhands.sdk.profiles.AgentProfileStoreProtocol` implementation, so the
+ SDK FK / seed / id-stamping helpers (``find_referrers`` / ``cascade_rename`` /
+ ``save_profile_preserving_identity`` / ``build_seed_profile``) drive a cloud DB store
+ verbatim β€” never re-implemented here (the #3730 thin-boundary contract).
+
+The collection is **id-keyed** (the active pointer and ``LaunchedAgentProfile`` key on
+the stable UUID), but the Protocol's mutation surface (``load`` / ``rename`` / ``delete``
+/ ``set_llm_profile_ref``) is **name-based** β€” names are the user-facing, FK-referenced
+keys β€” so those methods look profiles up by ``name`` across the id-keyed dict. Names are
+unique because every write goes through ``save_profile_preserving_identity``, which keys
+identity on ``name``.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Any, Final, TypeAlias
+from uuid import UUID
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SerializationInfo,
+ field_serializer,
+ field_validator,
+ model_validator,
+)
+
+from openhands.app_server.utils.logger import openhands_logger as logger
+from openhands.sdk.profiles import (
+ ACPAgentProfile,
+ OpenHandsAgentProfile,
+ ProfileLimitExceeded,
+ validate_agent_profile,
+)
+
+# Mirrors ``MAX_AGENT_PROFILES`` in the local agent-server router
+# (openhands-agent-server/.../agent_profiles_router.py) so both backends share
+# one cap and ``save_profile_preserving_identity`` enforces it identically.
+MAX_AGENT_PROFILES: Final[int] = 50
+
+_AgentProfile: TypeAlias = OpenHandsAgentProfile | ACPAgentProfile
+# Return-type aliases for the ``list`` / ``list_summaries`` Protocol methods:
+# the ``list()`` method shadows the ``list`` builtin in the class body, so a
+# bare ``list[...]`` return annotation resolves to the method under mypy.
+# Bind the builtin here at module scope instead.
+_ProfileNames: TypeAlias = list[str]
+_ProfileSummaries: TypeAlias = list[dict[str, Any]]
+
+
+class AgentProfiles(BaseModel):
+ """Id-keyed collection of ``AgentProfile``\\ s + an org-default active pointer.
+
+ Conforms to :class:`~openhands.sdk.profiles.AgentProfileStoreProtocol`: the
+ SDK FK / identity / seed helpers operate over this model with no filesystem
+ access. ``lock()`` is a re-entrant no-op because the router holds the
+ ``org`` row transaction (``SELECT ... FOR UPDATE``) for the whole mutation,
+ exactly as ``org_profiles._org_profiles_transaction`` does for LLM profiles.
+
+ Invariants (enforced on validate + assignment):
+ - ``active`` is either ``None`` or a key (id) of ``profiles``.
+ - Individual profiles that fail to parse (schema drift) are dropped with a
+ warning rather than failing the whole ``Settings`` load β€” mirrors
+ ``LLMProfiles._skip_invalid_profiles``.
+ """
+
+ model_config = ConfigDict(validate_assignment=True)
+
+ # Keyed by ``str(profile.id)`` β€” the stable UUID the active pointer and
+ # ``LaunchedAgentProfile.agent_profile_id`` reference.
+ profiles: dict[str, _AgentProfile] = Field(default_factory=dict)
+ active: str | None = None
+
+ # ── Validation ─────────────────────────────────────────────────
+
+ @field_validator('profiles', mode='before')
+ @classmethod
+ def _skip_invalid_profiles(cls, value: Any) -> Any:
+ """Best-effort per-profile load: skip entries that fail to validate.
+
+ Guards against schema drift β€” one stored profile going invalid after an
+ SDK upgrade must not fail the whole ``Settings`` load. Delegates parsing
+ to the SDK's :func:`validate_agent_profile` (never re-validated here).
+ """
+ if not isinstance(value, dict):
+ return value
+ valid: dict[str, Any] = {}
+ for key, raw in value.items():
+ try:
+ valid[key] = validate_agent_profile(raw)
+ except Exception as exc: # noqa: BLE001 - schema drift is non-fatal
+ logger.warning('Skipping invalid agent profile %r: %s', key, exc)
+ return valid
+
+ @model_validator(mode='after')
+ def _reconcile_active(self) -> AgentProfiles:
+ if self.active is not None and self.active not in self.profiles:
+ # Bypass validate_assignment to avoid re-entering this validator.
+ object.__setattr__(self, 'active', None)
+ return self
+
+ # ── Internal name↔id helpers ───────────────────────────────────
+
+ def _entry_for_name(self, name: str) -> tuple[str, _AgentProfile] | None:
+ for pid, profile in self.profiles.items():
+ if profile.name == name:
+ return pid, profile
+ return None
+
+ # ── AgentProfileStoreProtocol ──────────────────────────────────
+
+ @contextmanager
+ def lock(self, timeout: float = 30.0) -> Iterator[None]:
+ """Re-entrant no-op β€” the router holds the ``org`` row transaction."""
+ yield
+
+ def list(self) -> _ProfileNames:
+ """Profile "filenames" (``<name>.json``) β€” used only for emptiness checks."""
+ return [f'{profile.name}.json' for profile in self.profiles.values()]
+
+ def list_summaries(self) -> _ProfileSummaries:
+ """Metadata projection ``{id, name, agent_kind, revision, llm_profile_ref,
+ mcp_server_refs}`` per profile β€” the shape the SDK FK scans and the list
+ endpoint consume. ``llm_profile_ref`` is ``None`` for ACP profiles."""
+ summaries: list[dict[str, Any]] = []
+ for pid, profile in self.profiles.items():
+ summaries.append(
+ {
+ 'id': pid,
+ 'name': profile.name,
+ 'agent_kind': profile.agent_kind,
+ 'revision': profile.revision,
+ 'llm_profile_ref': (
+ profile.llm_profile_ref
+ if isinstance(profile, OpenHandsAgentProfile)
+ else None
+ ),
+ 'mcp_server_refs': profile.mcp_server_refs,
+ }
+ )
+ return summaries
+
+ def save(
+ self,
+ profile: _AgentProfile,
+ *,
+ max_profiles: int | None = None,
+ ) -> None:
+ """Store ``profile`` under ``str(profile.id)``, overwriting any namesake.
+
+ The id is set by the caller (``save_profile_preserving_identity``). No
+ cipher is involved β€” the profile is secret-free at rest (#4017), and
+ the ``org.agent_profiles`` ``EncryptedJSON`` column is the encryption
+ boundary regardless (parity with ``org.llm_profiles``).
+ """
+ pid = str(profile.id)
+ if (
+ max_profiles is not None
+ and pid not in self.profiles
+ and len(self.profiles) >= max_profiles
+ ):
+ raise ProfileLimitExceeded(f'Profile limit reached ({max_profiles}).')
+ self.profiles[pid] = profile
+
+ def load(self, name: str) -> _AgentProfile:
+ entry = self._entry_for_name(name)
+ if entry is None:
+ raise FileNotFoundError(f'Agent profile {name!r} not found')
+ return entry[1]
+
+ def delete(self, name: str) -> None:
+ """Remove the profile named ``name`` (idempotent). Clears the org-default
+ ``active`` pointer if it referenced the deleted profile."""
+ entry = self._entry_for_name(name)
+ if entry is None:
+ return
+ pid = entry[0]
+ del self.profiles[pid]
+ if self.active == pid:
+ object.__setattr__(self, 'active', None)
+
+ def rename(self, old_name: str, new_name: str) -> None:
+ entry = self._entry_for_name(old_name)
+ if entry is None:
+ raise FileNotFoundError(f'Agent profile {old_name!r} not found')
+ if old_name == new_name:
+ return
+ if self._entry_for_name(new_name) is not None:
+ raise FileExistsError(f'Agent profile {new_name!r} already exists')
+ pid, profile = entry
+ # Preserve the id (and thus the slot + active pointer): rename is a
+ # ``name`` edit only.
+ self.profiles[pid] = profile.model_copy(update={'name': new_name})
+
+ def set_llm_profile_ref(self, name: str, new_ref: str) -> None:
+ """Repoint one OpenHands profile's ``llm_profile_ref`` (the FK cascade
+ write primitive). No-op for a missing or ACP-kind profile."""
+ entry = self._entry_for_name(name)
+ if entry is None:
+ return
+ pid, profile = entry
+ if isinstance(profile, OpenHandsAgentProfile):
+ self.profiles[pid] = profile.model_copy(update={'llm_profile_ref': new_ref})
+
+ def name_for_id(self, profile_id: str | UUID) -> str | None:
+ profile = self.profiles.get(str(profile_id))
+ return profile.name if profile is not None else None
+
+ # ── Serialization ──────────────────────────────────────────────
+
+ @field_serializer('profiles')
+ def _profiles_serializer(
+ self,
+ profiles: dict[str, _AgentProfile],
+ info: SerializationInfo,
+ ) -> dict[str, Any]:
+ # Thread the serialization context through β€” a no-op for AgentProfile
+ # today (secret-free since #4017), kept for parity with LLMProfiles'
+ # write-back pattern.
+ return {
+ pid: profile.model_dump(mode='json', context=info.context)
+ for pid, profile in profiles.items()
+ }
diff --git a/openhands/app_server/settings/file_settings_store.py b/openhands/app_server/settings/file_settings_store.py
index 663fb0f6c4..5de98b4a4a 100644
--- a/openhands/app_server/settings/file_settings_store.py
+++ b/openhands/app_server/settings/file_settings_store.py
@@ -14,7 +14,14 @@ class FileSettingsStore(SettingsStore):
file_store: FileStore
path: str = 'settings.json'
- async def load(self) -> Settings | None:
+ async def load(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> Settings | None:
+ # No Agent Profile concept in the local file store; nothing to resolve.
+ del resolve_agent_profile, override_agent_profile_id
try:
json_str = await call_sync_from_async(self.file_store.read, self.path)
kwargs = json.loads(json_str)
diff --git a/openhands/app_server/settings/settings_models.py b/openhands/app_server/settings/settings_models.py
index d4b2cd379e..9d8a1eaffe 100644
--- a/openhands/app_server/settings/settings_models.py
+++ b/openhands/app_server/settings/settings_models.py
@@ -21,6 +21,7 @@ from pydantic import (
BaseModel,
ConfigDict,
Field,
+ PrivateAttr,
SecretStr,
SerializationInfo,
ValidationError,
@@ -328,7 +329,19 @@ def grouped_workspace_dir(
# inputs, enforce the count cap, and take the per-user lock. Accepting a
# raw dict here both bypassed those guards and crashed downstream
# serialisation.
-_SETTINGS_UPDATE_IGNORED_FIELDS = frozenset(['secrets_store', 'llm_profiles'])
+# - ``active_agent_profile_id`` / ``active_agent_profile_revision`` are launch
+# provenance, not persisted settings β€” ``store()`` refuses instances that
+# carry them. The pointer is set via the agent-profiles activate endpoint, so
+# a client echoing a non-null value back on a settings PUT must be ignored,
+# not written (which would 500 in ``store()``).
+_SETTINGS_UPDATE_IGNORED_FIELDS = frozenset(
+ [
+ 'secrets_store',
+ 'llm_profiles',
+ 'active_agent_profile_id',
+ 'active_agent_profile_revision',
+ ]
+)
class Settings(BaseModel):
@@ -375,6 +388,24 @@ class Settings(BaseModel):
'See ``LLMProfiles`` for the profile-management API.'
),
)
+ # Active Agent Profile provenance (cloud SaaS), surfaced by
+ # ``SaasSettingsStore.load`` only when the caller requested profile
+ # resolution (``resolve_agent_profile=True`` / an explicit override).
+ # ``active_agent_profile_id`` mirrors the SDK persisted-settings pointer;
+ # the revision rides alongside so conversation-start can stamp
+ # ``LaunchedAgentProfile``. Neither is a persisted setting β€” they default to
+ # None and ``store()`` refuses instances that carry them (no backing column).
+ active_agent_profile_id: str | None = None
+ active_agent_profile_revision: int | None = None
+
+ # True when this instance came from a resolve-requested load: its
+ # agent_settings are the *effective* launch view (possibly an Agent
+ # Profile's resolved dump), not user-authored persisted settings, so it
+ # must never be passed back to ``store()``. Survives ``model_copy`` but
+ # not dump/reconstruct β€” ``store()`` also guards on
+ # ``active_agent_profile_id`` for reconstructed copies.
+ _resolved_view: bool = PrivateAttr(default=False)
+
# Marketplace registrations for plugin resolution
# Users can register multiple marketplaces with different auto-load behaviors
registered_marketplaces: list[MarketplaceRegistration] = Field(
diff --git a/openhands/app_server/settings/settings_store.py b/openhands/app_server/settings/settings_store.py
index c9b671c53b..ea78711b9d 100644
--- a/openhands/app_server/settings/settings_store.py
+++ b/openhands/app_server/settings/settings_store.py
@@ -20,8 +20,23 @@ class SettingsStore(ABC):
"""
@abstractmethod
- async def load(self) -> Settings | None:
- """Load session init data."""
+ async def load(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> Settings | None:
+ """Load session init data.
+
+ By default returns the PERSISTED (user-authored) settings β€” the view
+ every load() -> store() round-trip must operate on.
+ ``resolve_agent_profile=True`` opts into the *effective* launch view:
+ the active Agent Profile (cloud-only concept) resolves and replaces
+ ``agent_settings``; the result must never be passed to ``store()``.
+ ``override_agent_profile_id`` is a one-off launch override and implies
+ resolution. Implementations without the Agent Profile concept ignore
+ both.
+ """
@abstractmethod
async def store(self, settings: Settings) -> None:
diff --git a/openhands/app_server/user/auth_user_context.py b/openhands/app_server/user/auth_user_context.py
index 70cb3710a6..b61a2ab726 100644
--- a/openhands/app_server/user/auth_user_context.py
+++ b/openhands/app_server/user/auth_user_context.py
@@ -31,6 +31,7 @@ class AuthUserContext(UserContext):
user_auth: UserAuth
_user_info: UserInfo | None = None
+ _resolved_user_info: UserInfo | None = None
_provider_handler: ProviderHandler | None = None
async def get_user_id(self) -> str | None:
@@ -42,16 +43,44 @@ class AuthUserContext(UserContext):
async def get_user_email(self) -> str | None:
return await self.user_auth.get_user_email()
- async def get_user_info(self) -> UserInfo:
+ @staticmethod
+ def _user_info_from_settings(user_id: str | None, settings: Any | None) -> UserInfo:
+ if settings is None:
+ return UserInfo(id=user_id)
+ return UserInfo(
+ id=user_id,
+ **settings.model_dump(context={'expose_secrets': True}),
+ )
+
+ async def get_user_info(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> UserInfo:
+ if override_agent_profile_id is not None:
+ # One-off launch override: never memoized in either direction.
+ user_id = await self.get_user_id()
+ settings = await self.user_auth.get_user_settings(
+ resolve_agent_profile=True,
+ override_agent_profile_id=override_agent_profile_id,
+ )
+ return self._user_info_from_settings(user_id, settings)
+ if resolve_agent_profile:
+ user_info = self._resolved_user_info
+ if user_info is None:
+ user_id = await self.get_user_id()
+ settings = await self.user_auth.get_user_settings(
+ resolve_agent_profile=True
+ )
+ user_info = self._user_info_from_settings(user_id, settings)
+ self._resolved_user_info = user_info
+ return user_info
user_info = self._user_info
if user_info is None:
user_id = await self.get_user_id()
settings = await self.user_auth.get_user_settings()
- assert settings is not None
- user_info = UserInfo(
- id=user_id,
- **settings.model_dump(context={'expose_secrets': True}),
- )
+ user_info = self._user_info_from_settings(user_id, settings)
self._user_info = user_info
return user_info
diff --git a/openhands/app_server/user/specifiy_user_context.py b/openhands/app_server/user/specifiy_user_context.py
index 1957410594..e4f7de3b79 100644
--- a/openhands/app_server/user/specifiy_user_context.py
+++ b/openhands/app_server/user/specifiy_user_context.py
@@ -22,7 +22,12 @@ class SpecifyUserContext(UserContext):
async def get_user_email(self) -> str | None:
return None
- async def get_user_info(self) -> UserInfo:
+ async def get_user_info(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> UserInfo:
raise NotImplementedError()
async def get_authenticated_git_url(
diff --git a/openhands/app_server/user/user_context.py b/openhands/app_server/user/user_context.py
index 52555d9d4d..f24fcd661c 100644
--- a/openhands/app_server/user/user_context.py
+++ b/openhands/app_server/user/user_context.py
@@ -38,8 +38,20 @@ class UserContext(ABC):
"""
@abstractmethod
- async def get_user_info(self) -> UserInfo:
- """Get the user info."""
+ async def get_user_info(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> UserInfo:
+ """Get the user info.
+
+ Defaults to the PERSISTED settings view. ``resolve_agent_profile=True``
+ opts into the effective launch view (the active Agent Profile resolved
+ into ``agent_settings`` β€” cloud-only concept);
+ ``override_agent_profile_id`` is a one-off launch override and implies
+ resolution. Implementations without the concept ignore both.
+ """
@abstractmethod
async def get_authenticated_git_url(
diff --git a/openhands/app_server/user_auth/default_user_auth.py b/openhands/app_server/user_auth/default_user_auth.py
index 891697e0ea..f509d76630 100644
--- a/openhands/app_server/user_auth/default_user_auth.py
+++ b/openhands/app_server/user_auth/default_user_auth.py
@@ -52,15 +52,6 @@ class DefaultUserAuth(UserAuth):
self._settings_store = settings_store
return settings_store
- async def get_user_settings(self) -> Settings | None:
- settings = self._settings
- if settings:
- return settings
- settings_store = await self.get_user_settings_store()
- settings = await settings_store.load()
- self._settings = settings
- return settings
-
async def get_secrets_store(self) -> SecretsStore:
secrets_store = self._secrets_store
if secrets_store:
diff --git a/openhands/app_server/user_auth/user_auth.py b/openhands/app_server/user_auth/user_auth.py
index 554f4e8aa8..1be3c3256e 100644
--- a/openhands/app_server/user_auth/user_auth.py
+++ b/openhands/app_server/user_auth/user_auth.py
@@ -45,6 +45,9 @@ class UserAuth(ABC):
"""
_settings: Settings | None
+ # Separate memo for the resolved (effective launch) view; a class-level
+ # default so subclasses need not declare it.
+ _resolved_settings: Settings | None = None
@abstractmethod
async def get_user_id(self) -> str | None:
@@ -66,8 +69,37 @@ class UserAuth(ABC):
async def get_user_settings_store(self) -> SettingsStore:
"""Get the settings store for the current user."""
- async def get_user_settings(self) -> Settings | None:
- """Get the user settings for the current user"""
+ async def get_user_settings(
+ self,
+ *,
+ resolve_agent_profile: bool = False,
+ override_agent_profile_id: str | None = None,
+ ) -> Settings | None:
+ """Get the user settings for the current user.
+
+ The default is the PERSISTED settings view (memoized in
+ ``_settings``) β€” what settings round-trips edit and ``store()``
+ accepts. ``resolve_agent_profile=True`` returns the *effective*
+ launch view (the active Agent Profile resolved into
+ ``agent_settings``), memoized separately in ``_resolved_settings``.
+ ``override_agent_profile_id`` is a one-off launch override: it
+ implies resolution and bypasses both memos in both directions, so a
+ later call still gets the ordinary ambient result.
+ """
+ if override_agent_profile_id is not None:
+ settings_store = await self.get_user_settings_store()
+ return await settings_store.load(
+ resolve_agent_profile=True,
+ override_agent_profile_id=override_agent_profile_id,
+ )
+ if resolve_agent_profile:
+ settings = self._resolved_settings
+ if settings:
+ return settings
+ settings_store = await self.get_user_settings_store()
+ settings = await settings_store.load(resolve_agent_profile=True)
+ self._resolved_settings = settings
+ return settings
settings = self._settings
if settings:
return settings
diff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.py
index 91d7275d9b..e05bdfd3d0 100644
--- a/tests/unit/app_server/test_live_status_app_conversation_service.py
+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py
@@ -30,6 +30,7 @@ from openhands.app_server.app_conversation.app_conversation_service import (
)
from openhands.app_server.app_conversation.live_status_app_conversation_service import (
LiveStatusAppConversationService,
+ effective_disabled_skills,
)
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import SuggestedTask, TaskType
@@ -152,6 +153,46 @@ class _TestUserInfo(SimpleNamespace):
return self.agent_settings
+class TestEffectiveDisabledSkills:
+ """effective_disabled_skills() unions the member- and profile-level deny-lists.
+
+ A skill disabled at either level stays off. The profile's deny-list rides the
+ resolved agent_settings.agent_context.disabled_skills (stamped by the SDK
+ resolver, #4017); the member's rides user.disabled_skills.
+ """
+
+ def _user(self, member, profile_disabled):
+ user = _TestUserInfo(disabled_skills=member)
+ user.agent_settings = OpenHandsAgentSettings(
+ agent_context=AgentContext(disabled_skills=profile_disabled)
+ )
+ return user
+
+ def test_unions_member_and_profile_dedup_order_preserving(self):
+ assert effective_disabled_skills(self._user(['a', 'b'], ['b', 'c'])) == [
+ 'a',
+ 'b',
+ 'c',
+ ]
+
+ def test_profile_only(self):
+ assert effective_disabled_skills(self._user([], ['x'])) == ['x']
+
+ def test_member_only_on_non_profile_launch(self):
+ # Non-profile launch: resolved context carries no profile deny-list.
+ user = _TestUserInfo(disabled_skills=['m'])
+ user.agent_settings = OpenHandsAgentSettings(agent_context=AgentContext())
+ assert effective_disabled_skills(user) == ['m']
+
+ def test_missing_name_carried_as_noop_never_raises(self):
+ # A disabled name absent from any catalog is still returned; the deny is a
+ # no-op at load time (nothing to remove), never an error.
+ assert effective_disabled_skills(self._user([], ['nope'])) == ['nope']
+
+ def test_empty_when_nothing_disabled(self):
+ assert effective_disabled_skills(self._user([], [])) == []
+
+
# Env var used by openhands SDK LLM to skip context-window validation (e.g. for gpt-4 in tests)
_ALLOW_SHORT_CONTEXT_WINDOWS = 'ALLOW_SHORT_CONTEXT_WINDOWS'
@@ -971,6 +1012,47 @@ class TestLiveStatusAppConversationService:
assert result.conversation_id == conversation_id
self.service._load_skills_and_update_agent.assert_called_once()
+ @patch(
+ 'openhands.app_server.app_conversation.live_status_app_conversation_service.get_default_tools',
+ return_value=[],
+ )
+ @pytest.mark.asyncio
+ async def test_build_request_passes_profile_and_member_disabled_skills(
+ self, _mock_tools
+ ):
+ """Skill loading gets member βˆͺ launched-profile disabled_skills (#4017)."""
+ # Member disables one skill; the launched profile (resolved agent_context)
+ # disables another. Both must reach _load_skills_and_update_agent.
+ self.mock_user.disabled_skills = ['member-skill']
+ self.mock_user.agent_settings = OpenHandsAgentSettings(
+ llm=LLM(model='gpt-4', api_key=SecretStr('test-key')),
+ agent_context=AgentContext(disabled_skills=['profile-skill']),
+ )
+ self.mock_user_context.get_user_info.return_value = self.mock_user
+
+ real_llm = LLM(model='gpt-4', api_key=SecretStr('test-key'))
+ mock_agent = Mock(spec=Agent)
+ mock_agent.llm = real_llm
+ mock_agent.condenser = None
+
+ self.service._setup_secrets_for_git_providers = AsyncMock(return_value={})
+ self.service._configure_llm_and_mcp = AsyncMock(return_value=(real_llm, {}))
+ self.service._load_skills_and_update_agent = AsyncMock(return_value=mock_agent)
+
+ await self.service._build_start_conversation_request_for_user(
+ sandbox=self.mock_sandbox,
+ conversation_id=uuid4(),
+ initial_message=None,
+ system_message_suffix=None,
+ git_provider=None,
+ working_dir='/test/dir',
+ remote_workspace=Mock(spec=AsyncRemoteWorkspace),
+ selected_repository='test_repo',
+ )
+
+ kwargs = self.service._load_skills_and_update_agent.call_args.kwargs
+ assert set(kwargs['disabled_skills']) == {'member-skill', 'profile-skill'}
+
@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.get_default_tools',
return_value=[],
diff --git a/tests/unit/app_server/test_profiles_api.py b/tests/unit/app_server/test_profiles_api.py
index 1a4d4a0ab4..6a3033a998 100644
--- a/tests/unit/app_server/test_profiles_api.py
+++ b/tests/unit/app_server/test_profiles_api.py
@@ -1001,6 +1001,30 @@ async def test_main_settings_endpoint_ignores_llm_profiles_payload(
assert 'ATTACKER' not in {p['name'] for p in listing['profiles']}
+async def test_main_settings_endpoint_ignores_active_agent_profile_pointer(
+ test_client, settings_store
+):
+ """The generic settings POST must ignore the agent-profile launch pointer.
+
+ ``active_agent_profile_id`` / ``active_agent_profile_revision`` are launch
+ provenance, not persisted settings β€” ``store()`` refuses instances that
+ carry them. A client echoing a non-null value back on a settings PUT must
+ be silently dropped (200), not written through to a 500 in ``store()``.
+ """
+ await _seed(settings_store, _base_settings())
+
+ resp = test_client.post(
+ '/api/v1/settings',
+ json={
+ 'active_agent_profile_id': 'deadbeef-0000-0000-0000-000000000000',
+ 'active_agent_profile_revision': 7,
+ },
+ )
+
+ assert resp.status_code == 200 # silently ignored, not a 500 from store()
+
+
@pytest.mark.asyncio
async def test_delete_active_profile_clears_active_and_allows_recovery(
test_client, settings_store