Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from openhands.agent_server._secrets_exposure import (
decrypt_incoming_llm_secrets,
get_cipher,
store_errors,
)
from openhands.agent_server.conversation_registry import ConversationRegistry
from openhands.agent_server.conversation_service import (
Expand Down Expand Up @@ -47,6 +48,7 @@
UpdateSecretsRequest,
trim_conversation_response_skills,
)
from openhands.agent_server.persistence import get_llm_profile_store
from openhands.sdk import LLM, Agent, TextContent
from openhands.sdk.conversation.state import ConversationExecutionStatus
from openhands.sdk.marketplace.registry import (
Expand Down Expand Up @@ -560,7 +562,10 @@ async def switch_conversation_llm(
"""Swap the conversation's LLM to a caller-supplied object.

Used by app-servers that own the LLM directly and don't push profiles
to the agent-server's filesystem (see #3017).
to the agent-server's filesystem (see #3017), and by the frontend's
per-conversation model switch, which forwards a profile config that may
reference a saved provider connection by id instead of carrying an inline
API key.
"""
event_service = await conversation_service.get_event_service(conversation_id)
if event_service is None:
Expand All @@ -569,6 +574,14 @@ async def switch_conversation_llm(
cipher = get_cipher(request)
if cipher is not None:
llm = decrypt_incoming_llm_secrets(llm, cipher)
# Resolve a referenced provider connection before installing the LLM, so a
# profile linked to a shared connection runs with its api_key / base_url
# instead of a keyless config (mirrors LLMProfileStore.load). A dangling
# reference or missing credential surfaces as 422 before the working LLM
# is replaced. Inline-key configs without a provider_connection_id are
# byte-identical to the old path.
with store_errors():
llm = get_llm_profile_store().resolve_provider_connection(llm, cipher=cipher)
conversation.switch_llm(llm)
return Success()

Expand Down
26 changes: 24 additions & 2 deletions openhands-sdk/openhands/sdk/llm/llm_profile_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,25 @@ def load(
)
return llm_instance

def resolve_provider_connection(
self, llm: LLM, *, cipher: Cipher | None = None
) -> LLM:
"""Apply a referenced provider connection's credentials to ``llm``.

Shared entry point for the read-at-use resolution that :meth:`load`
applies at profile-load time. Callers that install a caller-supplied
LLM (e.g. the ``/switch_llm`` endpoint, which receives a profile config
forwarded by the frontend) use this so a profile linked to a provider
connection runs with the connection's ``api_key`` / ``base_url`` instead
of a keyless config. ``profile_name`` is unknown here, so error messages
reference the connection id directly.

See :meth:`_resolve_provider_connection` for the resolution rules.
"""
return self._resolve_provider_connection(None, llm, cipher=cipher)

def _resolve_provider_connection(
self, profile_name: str, llm: LLM, *, cipher: Cipher | None
self, profile_name: str | None, llm: LLM, *, cipher: Cipher | None
) -> LLM:
"""Apply a referenced provider connection's credentials to ``llm``.

Expand Down Expand Up @@ -345,8 +362,13 @@ def _resolve_provider_connection(
connection_id,
)
return llm
owner = (
f"Profile {profile_name!r}"
if profile_name is not None
else "LLM config"
)
raise ProviderConnectionNotFound(
f"Profile {profile_name!r} references provider connection "
f"{owner} references provider connection "
f"{connection_id!r}, which does not exist. Update the profile or "
"recreate the connection."
)
Expand Down
218 changes: 218 additions & 0 deletions tests/agent_server/test_conversation_router.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tests for conversation_router.py endpoints."""

import time
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID, uuid4

Expand Down Expand Up @@ -2528,6 +2529,223 @@ def test_switch_conversation_llm_not_found(
client.app.dependency_overrides.clear()


def test_switch_conversation_llm_resolves_provider_connection(
client, mock_conversation_service, mock_event_service, sample_conversation_id
):
"""A provider_connection_id is resolved into the connection's api_key /
base_url before the LLM is installed — regression for OpenHands/OpenHands#17206
(switching to a linked OpenRouter profile lost credentials)."""
import tempfile
from pathlib import Path

from openhands.agent_server.persistence import store as store_module
from openhands.sdk.llm.provider_connection_store import ProviderConnectionStore

with tempfile.TemporaryDirectory() as tmpdir:
base = Path(tmpdir)
provider_store = ProviderConnectionStore(base_dir=base / "connections")
provider_store.create(
_provider_connection("or-conn", api_key="or-secret", base_url=None),
cipher=None,
)
profile_store = LLMProfileStore(
base_dir=base / "profiles", provider_store=provider_store
)

mock_conversation = MagicMock()
mock_conversation_service.get_event_service.return_value = mock_event_service
mock_event_service.get_conversation.return_value = mock_conversation
client.app.dependency_overrides[get_conversation_service] = lambda: (
mock_conversation_service
)

old_store = store_module._llm_profile_store
store_module._llm_profile_store = profile_store
try:
response = client.post(
f"/api/conversations/{sample_conversation_id}/switch_llm",
json={
"llm": {
"model": "openrouter/z-ai/glm-5.3-flash",
"provider_connection_id": "or-conn",
"usage_id": "caller-supplied-id",
}
},
)

assert response.status_code == 200
mock_conversation.switch_llm.assert_called_once()
forwarded = mock_conversation.switch_llm.call_args.args[0]
assert isinstance(forwarded, LLM)
assert forwarded.provider_connection_id == "or-conn"
assert isinstance(forwarded.api_key, SecretStr)
assert forwarded.api_key.get_secret_value() == "or-secret"
Comment thread
juanmichelini marked this conversation as resolved.
Resolved
finally:
store_module._llm_profile_store = old_store
client.app.dependency_overrides.clear()


def test_switch_conversation_llm_resolves_encrypted_provider_connection(
client, mock_conversation_service, mock_event_service, sample_conversation_id
):
"""Encrypted-at-rest provider credentials are decrypted with the server's
cipher before the LLM is installed."""
import tempfile
from base64 import urlsafe_b64encode
from pathlib import Path

from openhands.agent_server.persistence import store as store_module
from openhands.sdk.llm.provider_connection_store import ProviderConnectionStore
from openhands.sdk.utils.cipher import Cipher

secret_key = urlsafe_b64encode(b"a" * 32).decode("ascii")
cipher = Cipher(secret_key)
client.app.state.config = Config(
static_files_path=None,
session_api_keys=[],
secret_key=SecretStr(secret_key),
)

with tempfile.TemporaryDirectory() as tmpdir:
base = Path(tmpdir)
provider_store = ProviderConnectionStore(base_dir=base / "connections")
provider_store.create(
_provider_connection(
"or-conn",
api_key="plaintext-or-secret",
base_url="https://openrouter.ai/api/v1",
),
cipher=cipher,
)
profile_store = LLMProfileStore(
base_dir=base / "profiles", provider_store=provider_store
)

mock_conversation = MagicMock()
mock_conversation_service.get_event_service.return_value = mock_event_service
mock_event_service.get_conversation.return_value = mock_conversation
client.app.dependency_overrides[get_conversation_service] = lambda: (
mock_conversation_service
)

old_store = store_module._llm_profile_store
store_module._llm_profile_store = profile_store
try:
response = client.post(
f"/api/conversations/{sample_conversation_id}/switch_llm",
json={
"llm": {
"model": "openrouter/z-ai/glm-5.3-flash",
"provider_connection_id": "or-conn",
"usage_id": "caller-supplied-id",
}
},
)

assert response.status_code == 200
forwarded = mock_conversation.switch_llm.call_args.args[0]
assert isinstance(forwarded.api_key, SecretStr)
assert forwarded.api_key.get_secret_value() == "plaintext-or-secret"
assert forwarded.base_url == "https://openrouter.ai/api/v1"
finally:
store_module._llm_profile_store = old_store
client.app.dependency_overrides.clear()


def test_switch_conversation_llm_inline_key_without_provider_connection(
client, mock_conversation_service, mock_event_service, sample_conversation_id
):
"""An inline api_key with no provider_connection_id is applied unchanged
(byte-identical old path)."""
mock_conversation = MagicMock()
mock_conversation_service.get_event_service.return_value = mock_event_service
mock_event_service.get_conversation.return_value = mock_conversation
client.app.dependency_overrides[get_conversation_service] = lambda: (
mock_conversation_service
)

try:
response = client.post(
f"/api/conversations/{sample_conversation_id}/switch_llm",
json={
"llm": {
"model": "openai/gpt-4o",
"api_key": "sk-test",
"usage_id": "caller-supplied-id",
}
},
)

assert response.status_code == 200
forwarded = mock_conversation.switch_llm.call_args.args[0]
assert forwarded.api_key.get_secret_value() == "sk-test"
assert forwarded.provider_connection_id is None
finally:
client.app.dependency_overrides.clear()


def test_switch_conversation_llm_missing_provider_connection_rejects_before_switch(
client, mock_conversation_service, mock_event_service, sample_conversation_id
):
"""A dangling provider_connection_id (and no inline key) surfaces 422 before
the working LLM is replaced."""
import tempfile
from pathlib import Path

from openhands.agent_server.persistence import store as store_module
from openhands.sdk.llm.provider_connection_store import ProviderConnectionStore

with tempfile.TemporaryDirectory() as tmpdir:
base = Path(tmpdir)
provider_store = ProviderConnectionStore(base_dir=base / "connections")
profile_store = LLMProfileStore(
base_dir=base / "profiles", provider_store=provider_store
)

mock_conversation = MagicMock()
mock_conversation_service.get_event_service.return_value = mock_event_service
mock_event_service.get_conversation.return_value = mock_conversation
client.app.dependency_overrides[get_conversation_service] = lambda: (
mock_conversation_service
)

old_store = store_module._llm_profile_store
store_module._llm_profile_store = profile_store
try:
response = client.post(
f"/api/conversations/{sample_conversation_id}/switch_llm",
json={
"llm": {
"model": "openrouter/z-ai/glm-5.3-flash",
"provider_connection_id": "ghost-conn",
"usage_id": "caller-supplied-id",
}
},
)

assert response.status_code == 422
assert "ghost-conn" in response.json()["detail"]
mock_conversation.switch_llm.assert_not_called()
finally:
store_module._llm_profile_store = old_store
client.app.dependency_overrides.clear()


def _provider_connection(connection_id: str, *, api_key: str, base_url: str | None):
from openhands.sdk.llm.provider_connection_store import ProviderConnection

now = int(time.time())
return ProviderConnection(
id=connection_id,
display_name=connection_id,
provider="custom",
api_key=SecretStr(api_key),
base_url=base_url,
created_at=now,
updated_at=now,
)


def test_fork_conversation_success(
client, mock_conversation_service, sample_conversation_info, sample_conversation_id
):
Expand Down
Loading