From 93d363a6e5d75f55dd7af981efcf1d09b68897a1 Mon Sep 17 00:00:00 2001 From: emmanuel-adu Date: Thu, 30 Jul 2026 17:48:40 -0700 Subject: [PATCH 1/4] fix: PATCH /api/settings loads the profile's LLM when setting active_profile active_profile could be set via PATCH /api/settings without touching agent_settings.llm, letting the two silently disagree - unlike POST /api/profiles/{name}/activate, which updates both atomically. Now PATCH loads and applies the named profile's LLM the same way, unless the caller already supplied an explicit agent_settings_diff.llm. 404s on an unknown profile instead of accepting a dangling pointer. Fixes #4314 --- .../openhands/agent_server/settings_router.py | 56 +++++++++++++ tests/agent_server/test_settings_router.py | 79 +++++++++++++++++++ 2 files changed, 135 insertions(+) diff --git a/openhands-agent-server/openhands/agent_server/settings_router.py b/openhands-agent-server/openhands/agent_server/settings_router.py index 85a5496d905..f0675579901 100644 --- a/openhands-agent-server/openhands/agent_server/settings_router.py +++ b/openhands-agent-server/openhands/agent_server/settings_router.py @@ -7,6 +7,7 @@ from openhands.agent_server._secrets_exposure import ( build_expose_context, + get_cipher, get_config, parse_expose_secrets_header, translate_missing_cipher, @@ -14,10 +15,12 @@ from openhands.agent_server.persistence import ( SECRET_NAME_PATTERN, PersistedSettings, + get_llm_profile_store, get_secrets_store, get_settings_store, ) from openhands.agent_server.persistence.models import SettingsUpdatePayload +from openhands.agent_server.profiles_router import _store_errors from openhands.agent_server.telemetry import notify_misc_settings_changed from openhands.sdk.logger import get_logger from openhands.sdk.mcp.config import MCPServer @@ -179,6 +182,15 @@ async def update_settings( Accepts ``agent_settings_diff``, ``conversation_settings_diff``, ``misc_settings_diff``, and/or ``active_profile`` for incremental updates. + + Setting ``active_profile`` to a profile name (without an explicit + ``agent_settings_diff.llm``) loads that profile and applies its LLM + config, the same as ``POST /api/profiles/{name}/activate`` - so + ``active_profile`` can't silently disagree with ``agent_settings.llm``. + Returns 404 if the named profile doesn't exist. Pass an explicit + ``agent_settings_diff.llm`` alongside ``active_profile`` to opt out and + set both independently. + The three ``*_settings_diff`` fields are deep-merged; nested objects merge recursively, and a ``null`` value **inside a nested map deletes that entry** — the "unset" primitive that lets a client remove a single map key without @@ -226,11 +238,55 @@ async def update_settings( ) +def _resolve_active_profile_llm( + request: Request, update_data: SettingsUpdatePayload +) -> SettingsUpdatePayload: + """Fold the named profile's LLM into ``agent_settings_diff`` when the + caller sets ``active_profile`` without an explicit ``llm`` diff. + + ``PATCH /api/settings`` used to accept ``active_profile`` as a bare label + with no side effects, letting it silently disagree with + ``agent_settings.llm`` - unlike ``POST /api/profiles/{name}/activate``, + which updates both atomically. This mirrors that endpoint's behavior + (load the profile, apply its LLM) so the two code paths can't diverge. + See #4314. + """ + profile_name = update_data.get("active_profile") + agent_diff = update_data.get("agent_settings_diff") + explicit_llm_diff = isinstance(agent_diff, dict) and "llm" in agent_diff + if not profile_name or explicit_llm_diff: + return update_data + + cipher = get_cipher(request) + profile_store = get_llm_profile_store() + try: + with _store_errors(): + llm = profile_store.load(profile_name, cipher=cipher) + except FileNotFoundError: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Profile '{profile_name}' not found", + ) + + return cast( + SettingsUpdatePayload, + { + **update_data, + "agent_settings_diff": { + **(agent_diff if isinstance(agent_diff, dict) else {}), + "llm": llm.model_dump(mode="json", context={"expose_secrets": True}), + }, + }, + ) + + def _apply_settings_update( request: Request, update_data: SettingsUpdatePayload, before_update: Callable[[PersistedSettings], None] | None = None, ) -> SettingsResponse: + update_data = _resolve_active_profile_llm(request, update_data) + # Apply updates atomically with file locking def apply_update(settings: PersistedSettings) -> PersistedSettings: if before_update is not None: diff --git a/tests/agent_server/test_settings_router.py b/tests/agent_server/test_settings_router.py index 0794bbe063c..4ae5f5e1594 100644 --- a/tests/agent_server/test_settings_router.py +++ b/tests/agent_server/test_settings_router.py @@ -14,6 +14,7 @@ PERSISTED_SETTINGS_SCHEMA_VERSION, FileSettingsStore, PersistedSettings, + get_llm_profile_store, reset_stores, ) from openhands.agent_server.persistence.models import _deep_merge @@ -625,6 +626,8 @@ def test_patch_settings_updates_llm_config(client_with_settings): def test_patch_settings_updates_active_profile(client_with_settings): """PATCH /api/settings can update and clear the active LLM profile.""" + get_llm_profile_store().save("fast-profile", LLM(model="gpt-4o-mini")) + response = client_with_settings.patch( "/api/settings", json={"active_profile": "fast-profile"}, @@ -662,6 +665,8 @@ def test_patch_settings_rejects_invalid_active_profile(client_with_settings): def test_patch_settings_active_agent_profile_id_independent(client_with_settings): """active_agent_profile_id sets/clears independently of active_profile.""" + get_llm_profile_store().save("fast-profile", LLM(model="gpt-4o-mini")) + agent_id = "12345678-1234-1234-1234-1234567890ab" set_response = client_with_settings.patch( "/api/settings", @@ -687,6 +692,80 @@ def test_patch_settings_active_agent_profile_id_independent(client_with_settings assert refetch["active_profile"] == "fast-profile" +def test_patch_settings_active_profile_applies_llm(client_with_settings): + """PATCH active_profile loads and applies that profile's LLM, matching + POST /api/profiles/{name}/activate - so it can't silently desync + active_profile from agent_settings.llm (#4314).""" + get_llm_profile_store().save("fast-profile", LLM(model="claude-haiku")) + + response = client_with_settings.patch( + "/api/settings", + json={"active_profile": "fast-profile"}, + ) + + assert response.status_code == 200 + body = response.json() + assert body["active_profile"] == "fast-profile" + assert body["agent_settings"]["llm"]["model"] == "claude-haiku" + + refetch = client_with_settings.get("/api/settings").json() + assert refetch["active_profile"] == "fast-profile" + assert refetch["agent_settings"]["llm"]["model"] == "claude-haiku" + + +def test_patch_settings_switching_active_profile_updates_llm(client_with_settings): + """Switching active_profile a second time re-applies the new profile's + LLM, not the first profile's.""" + get_llm_profile_store().save("profile-a", LLM(model="model-a")) + get_llm_profile_store().save("profile-b", LLM(model="model-b")) + + client_with_settings.patch("/api/settings", json={"active_profile": "profile-a"}) + response = client_with_settings.patch( + "/api/settings", json={"active_profile": "profile-b"} + ) + + assert response.status_code == 200 + body = response.json() + assert body["active_profile"] == "profile-b" + assert body["agent_settings"]["llm"]["model"] == "model-b" + + +def test_patch_settings_active_profile_not_found_returns_404(client_with_settings): + """PATCH active_profile with an unknown profile name 404s instead of + silently accepting a dangling pointer.""" + response = client_with_settings.patch( + "/api/settings", + json={"active_profile": "does-not-exist"}, + ) + + assert response.status_code == 404 + + # Nothing should have been persisted - active_profile stays unset. + refetch = client_with_settings.get("/api/settings").json() + assert refetch["active_profile"] is None + + +def test_patch_settings_explicit_llm_diff_overrides_profile_autoload( + client_with_settings, +): + """An explicit agent_settings_diff.llm alongside active_profile is + respected as-is; the named profile's LLM is not auto-loaded over it.""" + get_llm_profile_store().save("fast-profile", LLM(model="claude-haiku")) + + response = client_with_settings.patch( + "/api/settings", + json={ + "active_profile": "fast-profile", + "agent_settings_diff": {"llm": {"model": "explicitly-chosen-model"}}, + }, + ) + + assert response.status_code == 200 + body = response.json() + assert body["active_profile"] == "fast-profile" + assert body["agent_settings"]["llm"]["model"] == "explicitly-chosen-model" + + def test_patch_settings_rejects_malformed_active_agent_profile_id(client_with_settings): """A non-UUID active_agent_profile_id is rejected at the HTTP layer.""" response = client_with_settings.patch( From a215ffc1cb0456ba6b8909c9ad852d14c72b38f3 Mon Sep 17 00:00:00 2001 From: emmanuel-adu Date: Fri, 31 Jul 2026 07:26:34 -0700 Subject: [PATCH 2/4] docs: trim comments and docstrings per review feedback Reduce docstrings/comments added in this PR to the minimal form, per maintainer request. --- .../openhands/agent_server/settings_router.py | 23 ++++--------------- tests/agent_server/test_settings_router.py | 14 ++++------- 2 files changed, 9 insertions(+), 28 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/settings_router.py b/openhands-agent-server/openhands/agent_server/settings_router.py index f0675579901..75408ff7d4d 100644 --- a/openhands-agent-server/openhands/agent_server/settings_router.py +++ b/openhands-agent-server/openhands/agent_server/settings_router.py @@ -182,14 +182,9 @@ async def update_settings( Accepts ``agent_settings_diff``, ``conversation_settings_diff``, ``misc_settings_diff``, and/or ``active_profile`` for incremental updates. - - Setting ``active_profile`` to a profile name (without an explicit - ``agent_settings_diff.llm``) loads that profile and applies its LLM - config, the same as ``POST /api/profiles/{name}/activate`` - so - ``active_profile`` can't silently disagree with ``agent_settings.llm``. - Returns 404 if the named profile doesn't exist. Pass an explicit - ``agent_settings_diff.llm`` alongside ``active_profile`` to opt out and - set both independently. + Setting ``active_profile`` loads and applies that profile's LLM, same as + ``POST /api/profiles/{name}/activate``, unless ``agent_settings_diff.llm`` + is also given. The three ``*_settings_diff`` fields are deep-merged; nested objects merge recursively, and a ``null`` value **inside a nested map deletes that entry** @@ -241,16 +236,8 @@ async def update_settings( def _resolve_active_profile_llm( request: Request, update_data: SettingsUpdatePayload ) -> SettingsUpdatePayload: - """Fold the named profile's LLM into ``agent_settings_diff`` when the - caller sets ``active_profile`` without an explicit ``llm`` diff. - - ``PATCH /api/settings`` used to accept ``active_profile`` as a bare label - with no side effects, letting it silently disagree with - ``agent_settings.llm`` - unlike ``POST /api/profiles/{name}/activate``, - which updates both atomically. This mirrors that endpoint's behavior - (load the profile, apply its LLM) so the two code paths can't diverge. - See #4314. - """ + """Fold the named profile's LLM into ``agent_settings_diff`` unless the + caller already gave one explicitly. Mirrors ``/activate``. See #4314.""" profile_name = update_data.get("active_profile") agent_diff = update_data.get("agent_settings_diff") explicit_llm_diff = isinstance(agent_diff, dict) and "llm" in agent_diff diff --git a/tests/agent_server/test_settings_router.py b/tests/agent_server/test_settings_router.py index 4ae5f5e1594..7df81ad624a 100644 --- a/tests/agent_server/test_settings_router.py +++ b/tests/agent_server/test_settings_router.py @@ -693,9 +693,7 @@ def test_patch_settings_active_agent_profile_id_independent(client_with_settings def test_patch_settings_active_profile_applies_llm(client_with_settings): - """PATCH active_profile loads and applies that profile's LLM, matching - POST /api/profiles/{name}/activate - so it can't silently desync - active_profile from agent_settings.llm (#4314).""" + """PATCH active_profile applies that profile's LLM (#4314).""" get_llm_profile_store().save("fast-profile", LLM(model="claude-haiku")) response = client_with_settings.patch( @@ -714,8 +712,7 @@ def test_patch_settings_active_profile_applies_llm(client_with_settings): def test_patch_settings_switching_active_profile_updates_llm(client_with_settings): - """Switching active_profile a second time re-applies the new profile's - LLM, not the first profile's.""" + """Switching active_profile re-applies the new profile's LLM.""" get_llm_profile_store().save("profile-a", LLM(model="model-a")) get_llm_profile_store().save("profile-b", LLM(model="model-b")) @@ -731,8 +728,7 @@ def test_patch_settings_switching_active_profile_updates_llm(client_with_setting def test_patch_settings_active_profile_not_found_returns_404(client_with_settings): - """PATCH active_profile with an unknown profile name 404s instead of - silently accepting a dangling pointer.""" + """PATCH active_profile with an unknown profile name 404s.""" response = client_with_settings.patch( "/api/settings", json={"active_profile": "does-not-exist"}, @@ -740,7 +736,6 @@ def test_patch_settings_active_profile_not_found_returns_404(client_with_setting assert response.status_code == 404 - # Nothing should have been persisted - active_profile stays unset. refetch = client_with_settings.get("/api/settings").json() assert refetch["active_profile"] is None @@ -748,8 +743,7 @@ def test_patch_settings_active_profile_not_found_returns_404(client_with_setting def test_patch_settings_explicit_llm_diff_overrides_profile_autoload( client_with_settings, ): - """An explicit agent_settings_diff.llm alongside active_profile is - respected as-is; the named profile's LLM is not auto-loaded over it.""" + """An explicit agent_settings_diff.llm overrides profile autoload.""" get_llm_profile_store().save("fast-profile", LLM(model="claude-haiku")) response = client_with_settings.patch( From 17c2a134797c469a78b76fe1876b148d35ffa974 Mon Sep 17 00:00:00 2001 From: emmanuel-adu Date: Sat, 1 Aug 2026 07:32:27 -0700 Subject: [PATCH 3/4] Address review: hoist _store_errors, trim docstring, add encrypted-secret test - Move the duplicated _store_errors context manager into _secrets_exposure.py as a shared store_errors(), used by settings_router, profiles_router, and agent_profiles_router instead of each keeping (or importing) a private copy. - Drop the stray issue reference from _resolve_active_profile_llm's docstring. - Add a regression test covering PATCH /api/settings applying a profile whose api_key is encrypted at rest. --- .../agent_server/_secrets_exposure.py | 19 +++++++ .../agent_server/agent_profiles_router.py | 49 ++++++------------- .../openhands/agent_server/profiles_router.py | 32 +++--------- .../openhands/agent_server/settings_router.py | 6 +-- tests/agent_server/test_settings_router.py | 26 ++++++++++ 5 files changed, 71 insertions(+), 61 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/_secrets_exposure.py b/openhands-agent-server/openhands/agent_server/_secrets_exposure.py index fa86d0bdb61..c3f2f79458b 100644 --- a/openhands-agent-server/openhands/agent_server/_secrets_exposure.py +++ b/openhands-agent-server/openhands/agent_server/_secrets_exposure.py @@ -120,3 +120,22 @@ def translate_missing_cipher() -> Iterator[None]: ), ) raise + + +@contextmanager +def store_errors() -> Iterator[None]: + """Map profile-store errors (``LLMProfileStore``/``AgentProfileStore``) to + HTTP responses. Shared by the settings, profiles, and agent-profiles + routers.""" + try: + yield + except TimeoutError: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Profile store is busy. Please retry.", + ) + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=str(e), + ) diff --git a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py index 1633c57768c..9a448c05e7a 100644 --- a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py @@ -12,14 +12,16 @@ """ import asyncio -from collections.abc import Iterator -from contextlib import contextmanager from typing import Annotated, Any from fastapi import APIRouter, HTTPException, Path, Request, status from pydantic import BaseModel, Field, ValidationError -from openhands.agent_server._secrets_exposure import get_cipher, get_config +from openhands.agent_server._secrets_exposure import ( + get_cipher, + get_config, + store_errors, +) from openhands.agent_server.persistence import ( PersistedSettings, get_agent_profile_store, @@ -105,25 +107,6 @@ class RenameAgentProfileRequest(BaseModel): ) -@contextmanager -def _store_errors() -> Iterator[None]: - """Map ``AgentProfileStore`` errors to HTTP responses. - - Mirrors ``profiles_router._store_errors``: ``TimeoutError`` and - ``ValueError`` only. ``FileNotFoundError`` / ``FileExistsError`` are handled - inline per-endpoint so each gets a clean, resource-specific message. - """ - try: - yield - except TimeoutError: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Agent profile store is busy. Please retry.", - ) - except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - - def _llm_has_real_config(llm: LLM) -> bool: """True when ``llm`` carries real, user-provided configuration. @@ -173,7 +156,7 @@ def _seed_default_llm_profile(llm: LLM, cipher: Cipher | None) -> str: silently clobber it. """ llm_store = get_llm_profile_store() - with _store_errors(): + with store_errors(): try: llm_store.load(SEED_PROFILE_NAME, cipher=cipher) return SEED_PROFILE_NAME @@ -227,7 +210,7 @@ def _seed_default_profile( The lock spans empty-check + save + pointer write so concurrent first requests seed exactly once and the pointer matches the persisted id. """ - with _store_errors(), store.lock(): + with store_errors(), store.lock(): # Double-checked under the lock: a concurrent first request may have # already seeded (the outer emptiness check in the list endpoint is # unlocked). @@ -261,7 +244,7 @@ def set_pointer(s: PersistedSettings) -> PersistedSettings: def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None: """Return the stable id of the profile stored under ``name``, if present.""" - with _store_errors(): + with store_errors(): for summary in store.list_summaries(): if summary.get("name") == name: sid = summary.get("id") @@ -282,14 +265,14 @@ async def list_agent_profiles(request: Request) -> AgentProfileListResponse: settings = settings_store.load() or PersistedSettings() store = get_agent_profile_store() - with _store_errors(): + with store_errors(): existing = store.list() if not existing and settings.active_agent_profile_id is None: _seed_default_profile(store, request, settings, get_cipher(request)) settings = settings_store.load() or settings - with _store_errors(): + with store_errors(): summaries = store.list_summaries() return AgentProfileListResponse( @@ -308,7 +291,7 @@ async def get_agent_profile(name: ProfileName) -> AgentProfileDetailResponse: """ store = get_agent_profile_store() try: - with _store_errors(): + with store_errors(): profile = store.load(name) except FileNotFoundError: raise HTTPException( @@ -361,7 +344,7 @@ async def save_agent_profile( # holds the store lock across read + mint + save so two concurrent creates # of the same new name can't both mint an id and clobber each other. try: - with _store_errors(): + with store_errors(): save_profile_preserving_identity( store, profile, max_profiles=MAX_AGENT_PROFILES ) @@ -392,7 +375,7 @@ async def delete_agent_profile( store = get_agent_profile_store() deleted_id = _summary_id_for_name(store, name) - with _store_errors(): + with store_errors(): store.delete(name) if deleted_id is not None: @@ -428,7 +411,7 @@ async def rename_agent_profile( """ store = get_agent_profile_store() try: - with _store_errors(): + with store_errors(): store.rename(name, body.new_name) except FileNotFoundError: raise HTTPException( @@ -462,7 +445,7 @@ async def activate_agent_profile( creation-time-only contract). Returns 404 if no stored profile has that id. """ store = get_agent_profile_store() - with _store_errors(): + with store_errors(): known_ids = { str(s["id"]) for s in store.list_summaries() if s.get("id") is not None } @@ -515,7 +498,7 @@ async def materialize_agent_profile( """ store = get_agent_profile_store() try: - with _store_errors(): + with store_errors(): profile = store.load(name) except FileNotFoundError: raise HTTPException( diff --git a/openhands-agent-server/openhands/agent_server/profiles_router.py b/openhands-agent-server/openhands/agent_server/profiles_router.py index d9c6a2f85e9..cea019baee2 100644 --- a/openhands-agent-server/openhands/agent_server/profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/profiles_router.py @@ -1,7 +1,5 @@ """HTTP endpoints for managing named LLM configurations (profiles).""" -from collections.abc import Iterator -from contextlib import contextmanager from typing import Annotated, Any from fastapi import APIRouter, HTTPException, Path, Request, status @@ -13,6 +11,7 @@ get_cipher, get_config, parse_expose_secrets_header, + store_errors, translate_missing_cipher, ) from openhands.agent_server.persistence import ( @@ -88,23 +87,6 @@ class RenameProfileRequest(BaseModel): ) -@contextmanager -def _store_errors() -> Iterator[None]: - """Map ``LLMProfileStore`` errors to HTTP responses.""" - try: - yield - except TimeoutError: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Profile store is busy. Please retry.", - ) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) - - def _has_api_key(llm: LLM) -> bool: if not isinstance(llm.api_key, SecretStr): return False @@ -141,7 +123,7 @@ async def list_profiles(request: Request) -> ProfileListResponse: settings = settings_store.load() or PersistedSettings() store = get_llm_profile_store() - with _store_errors(): + with store_errors(): summaries = store.list_summaries() return ProfileListResponse( @@ -164,7 +146,7 @@ async def get_profile(request: Request, name: ProfileName) -> ProfileDetailRespo store = get_llm_profile_store() try: - with _store_errors(): + with store_errors(): llm = store.load(name, cipher=cipher) except FileNotFoundError: raise HTTPException( @@ -208,7 +190,7 @@ async def save_profile( llm = decrypt_incoming_llm_secrets(body.llm, cipher) if cipher else body.llm store = get_llm_profile_store() try: - with _store_errors(): + with store_errors(): store.save( name, llm, @@ -241,7 +223,7 @@ async def delete_profile( store = get_llm_profile_store() agent_store = get_agent_profile_store() try: - with _store_errors(): + with store_errors(): delete_llm_profile(agent_store, store, name) except ProfileReferenced as e: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) @@ -269,7 +251,7 @@ async def rename_profile( store = get_llm_profile_store() agent_store = get_agent_profile_store() try: - with _store_errors(): + with store_errors(): rename_llm_profile(agent_store, store, name, body.new_name) except FileNotFoundError: raise HTTPException( @@ -325,7 +307,7 @@ async def activate_profile( # Load the profile profile_store = get_llm_profile_store() try: - with _store_errors(): + with store_errors(): llm = profile_store.load(name, cipher=cipher) except FileNotFoundError: raise HTTPException( diff --git a/openhands-agent-server/openhands/agent_server/settings_router.py b/openhands-agent-server/openhands/agent_server/settings_router.py index 75408ff7d4d..6024b1b254b 100644 --- a/openhands-agent-server/openhands/agent_server/settings_router.py +++ b/openhands-agent-server/openhands/agent_server/settings_router.py @@ -10,6 +10,7 @@ get_cipher, get_config, parse_expose_secrets_header, + store_errors, translate_missing_cipher, ) from openhands.agent_server.persistence import ( @@ -20,7 +21,6 @@ get_settings_store, ) from openhands.agent_server.persistence.models import SettingsUpdatePayload -from openhands.agent_server.profiles_router import _store_errors from openhands.agent_server.telemetry import notify_misc_settings_changed from openhands.sdk.logger import get_logger from openhands.sdk.mcp.config import MCPServer @@ -237,7 +237,7 @@ def _resolve_active_profile_llm( request: Request, update_data: SettingsUpdatePayload ) -> SettingsUpdatePayload: """Fold the named profile's LLM into ``agent_settings_diff`` unless the - caller already gave one explicitly. Mirrors ``/activate``. See #4314.""" + caller already gave one explicitly. Mirrors ``/activate``.""" profile_name = update_data.get("active_profile") agent_diff = update_data.get("agent_settings_diff") explicit_llm_diff = isinstance(agent_diff, dict) and "llm" in agent_diff @@ -247,7 +247,7 @@ def _resolve_active_profile_llm( cipher = get_cipher(request) profile_store = get_llm_profile_store() try: - with _store_errors(): + with store_errors(): llm = profile_store.load(profile_name, cipher=cipher) except FileNotFoundError: raise HTTPException( diff --git a/tests/agent_server/test_settings_router.py b/tests/agent_server/test_settings_router.py index 7df81ad624a..bb4cea92a17 100644 --- a/tests/agent_server/test_settings_router.py +++ b/tests/agent_server/test_settings_router.py @@ -711,6 +711,32 @@ def test_patch_settings_active_profile_applies_llm(client_with_settings): assert refetch["agent_settings"]["llm"]["model"] == "claude-haiku" +def test_patch_settings_active_profile_applies_encrypted_api_key( + client_with_settings, secret_key +): + """Applying a profile carries its at-rest-encrypted api_key through PATCH.""" + cipher = Cipher(secret_key) + get_llm_profile_store().save( + "secure-profile", + LLM(model="claude-haiku", api_key=SecretStr("sk-secret")), + include_secrets=True, + cipher=cipher, + ) + + response = client_with_settings.patch( + "/api/settings", + json={"active_profile": "secure-profile"}, + ) + assert response.status_code == 200 + + exposed = client_with_settings.get( + "/api/settings", headers={"X-Expose-Secrets": "plaintext"} + ).json() + assert exposed["agent_settings"]["llm"]["model"] == "claude-haiku" + assert exposed["agent_settings"]["llm"]["api_key"] == "sk-secret" + assert exposed["llm_api_key_is_set"] is True + + def test_patch_settings_switching_active_profile_updates_llm(client_with_settings): """Switching active_profile re-applies the new profile's LLM.""" get_llm_profile_store().save("profile-a", LLM(model="model-a")) From deeb8462918a93947afbb721ab81467f79988ab0 Mon Sep 17 00:00:00 2001 From: emmanuel-adu Date: Sat, 1 Aug 2026 08:54:14 -0700 Subject: [PATCH 4/4] Fix CI: test_seed_references_active_llm_profile expected a nonexistent profile PATCH /api/settings now validates active_profile against the profile store (this PR's own fix), so setting it to a never-saved "my-llm" 404s instead of silently taking effect. Save the profile first so the test exercises the seed picking up a real active LLM profile, as intended. --- tests/agent_server/test_agent_profiles_router.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/agent_server/test_agent_profiles_router.py b/tests/agent_server/test_agent_profiles_router.py index d999f261b7b..735be213769 100644 --- a/tests/agent_server/test_agent_profiles_router.py +++ b/tests/agent_server/test_agent_profiles_router.py @@ -105,8 +105,9 @@ def test_seed_is_idempotent(client): assert second["active_agent_profile_id"] == first["active_agent_profile_id"] -def test_seed_references_active_llm_profile(client): +def test_seed_references_active_llm_profile(client, default_llm_profile_store): """The seed references the active LLM profile when one is set.""" + default_llm_profile_store.save("my-llm", LLM(model="gpt-4o-mini")) client.patch("/api/settings", json={"active_profile": "my-llm"}) body = client.get("/api/agent-profiles").json()