Repository navigation
fix(agent-server): resolve provider connection in /switch_llm - #5417
Conversation
Switching a conversation to an LLM profile linked to a provider connection (e.g. an OpenRouter profile in agent-canvas) lost the API key: the frontend fetches the profile without resolving secrets and forwards a keyless config carrying only `provider_connection_id`, and the `/switch_llm` endpoint decrypted inline secrets but never resolved the referenced connection — so the installed LLM ran with `api_key=None` and OpenRouter rejected calls with 401 Invalid API key. Resolve the provider connection before installing the LLM, mirroring `LLMProfileStore.load(resolve_provider=True)`. A dangling reference or missing credential surfaces as 422 before the working LLM is replaced; an inline-key config without `provider_connection_id` is byte-identical to the old path. Fixes OpenHands/OpenHands#17206.
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
|
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Summary
The fix targets a real bug and is well-scoped: /switch_llm now resolves a caller-supplied provider_connection_id before installing the LLM, mirroring LLMProfileStore.load(resolve_provider=True). The LLMProfileStore.resolve_provider_connection(...) entry point and the router's store_errors() wrapping are sound, and the four new regression tests pass locally (8/8 switch_llm tests). However the current head is not mergeable as-is: the newly declared 422 response removes the application/json media type from the public OpenAPI contract, which fails the required REST API (OpenAPI) check and violates the repo's 5-minor-release REST compatibility policy; the same head also fails pre-commit (pyright) on the new test.
Findings
1. New explicit 422 drops application/json from the public REST contract (blocking)
conversation_router.py lines 554-557 declare 422: {"description": "Referenced provider connection is missing"}. In FastAPI, a responses entry for a status code that is otherwise auto-generated for the operation replaces the generated entry rather than merging with it. Because switch_conversation_llm has a body parameter, FastAPI auto-adds a 422 carrying content: {"application/json": {schema: HTTPValidationError}}. The explicit entry has no content, so that media type disappears.
Verified on this head: exporting the public OpenAPI via .github/scripts/export_agent_server_openapi.py yields paths./api/conversations/{conversation_id}/switch_llm.post.responses.422 == {"description": "Referenced provider connection is missing"} with no content key, and a minimal FastAPI repro reproduces the same drop. This is exactly the CI failure reported by the REST API (OpenAPI) job (run 36798335415): removed the media type application/json for the response with the status 422. Repo policy (openhands-agent-server/AGENTS.md) requires breaking REST contract changes to keep the old contract for 5 minor releases, and the breakage script has no allowlist bucket for a removed response media type, so this is a genuine public-contract regression, not a lint nit.
Note that the existing 422 declarations in plugins_router, canvas_extensions_router, and skills_router use handlers without a body parameter, so FastAPI does not auto-generate a 422 for them and their explicit declaration is purely additive — that is why they do not break. Here it is a replacement.
Suggested direction: keep the generated content in the declared 422 (for example declare it with the HTTPValidationError content schema alongside the description), or drop the explicit 422 declaration and document the new failure mode in the endpoint docstring instead.
2. pre-commit (pyright) is red on the new test
tests/agent_server/test_conversation_router.py line 2581 (assert forwarded.api_key.get_secret_value() == "or-secret") fails pyright with Cannot access attribute "get_secret_value" for class "str" and "get_secret_value" is not a known attribute of "None" (reportOptionalMemberAccess). The pre-commit job (run 36798335523) is failing on the current head. Narrow the type first, e.g. assert isinstance(forwarded.api_key, SecretStr) before dereferencing.
Assessment
The bug fix itself is correct, minimal, and covered by good regression tests. But the current head fails two required checks, and finding 1 is a real backward-compatibility regression on the public REST API rather than a stylistic concern. Both should be addressed before merge. The linked issue OpenHands/OpenHands#17206 (labels: bug, llm, agent-canvas, priority:medium, security; no readiness label) is filed against the agent-canvas repo while the handler lives here, which the PR description already calls out.
🔄 CHANGES REQUESTED
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Summary
The fix is correct, minimal, and appropriately scoped. /switch_llm now resolves a caller-supplied provider_connection_id into the connection's api_key / base_url before installing the LLM, mirroring LLMProfileStore.load(resolve_provider=True) / switch_profile. LLMProfileStore.resolve_provider_connection(llm, *, cipher=None) reuses the existing _resolve_provider_connection logic with an optional profile name, and the router resolves inside store_errors() so a dangling reference surfaces as 422 before the working LLM is replaced. An inline-key config without provider_connection_id is unchanged.
Both findings from the prior review are addressed on this head:
- The explicit
422entry was removed from the route'sresponses, so FastAPI's default validation422(application/json+HTTPValidationError) is restored. I re-exported the public OpenAPI on this head and confirmedpaths./api/conversations/{conversation_id}/switch_llm.post.responses.422is again the generatedapplication/json/HTTPValidationErrorshape. The REST API (OpenAPI) check now passes. - The pyright failure was fixed by narrowing
forwarded.api_keywithisinstance(..., SecretStr)beforeget_secret_value().uv run pyright tests/agent_server/test_conversation_router.pyreports 0 errors and the pre-commit check passes.
Verification performed on this head
uv run pytest tests/agent_server/test_conversation_router.py -k switch_conversation_llm -q→ 8 passed.uv run pytest tests/agent_server/test_conversation_router.py tests/sdk/llm/test_llm_profile_store.py tests/agent_server/test_profiles_router.py -q→ 268 passed.uv run pyright tests/agent_server/test_conversation_router.py→ 0 errors.- Public OpenAPI export confirms the
422contract is unchanged from the base.
Non-blocking note
agent-server-stress-tests is red on this head, but it is a pre-existing flake unrelated to this change. I reproduced the same failure on a clean origin/main worktree: tests/agent_server/stress/test_concurrent_conversations.py::test_concurrent_conversations_isolated_and_fast fails intermittently on the wall-clock budget assertion (concurrent wall (0.6-0.7s) > budget (~0.6s = ref × 4.0)), and occasionally on ConversationRunLimitExceeded when a semaphore permit is still held by an in-flight predecessor. The PR diff does not touch the stress fixtures, max_concurrent_runs, or the run-slot logic, so this is not a regression from this change. Worth a separate flake-fix PR, but it does not block this one.
Assessment
No material correctness, security, or compatibility defect remains on this head. The linked issue #5439 is ready-for-dev (labels: bug, llm, priority:medium, ready-for-dev, duplicate-candidate) and its acceptance criteria — resolve the linked connection's credentials on /switch_llm — are met by the implementation and covered by regression tests. The duplicate-candidate label on #5439 is worth a maintainer's eye, but it is orthogonal to the code correctness here.
✅ APPROVED
HUMAN:
Fixing a real 401 bug users hit in agent-canvas when switching to a linked OpenRouter profile — the keyless forwarded config needs server-side resolution.
Screenshots.
Before
After
AGENT:
Why
Switching a conversation to an LLM profile linked to a provider connection (e.g. an OpenRouter profile in agent-canvas) silently lost the API key. The frontend fetches the profile config without resolving secrets (they aren't exposed to the client), so it forwards a keyless config carrying only
provider_connection_id. The/switch_llmhandler decrypted inline secrets but never resolved the referenced connection — unlikeswitch_profile/LLMProfileStore.load(resolve_provider=True)— so the installed LLM ran withapi_key=Noneand OpenRouter rejected every call with401 Invalid API key.Fixes OpenHands/OpenHands#17206. Tracked in this repo at #5439.
Summary
LLMProfileStore.resolve_provider_connection(llm, *, cipher=None)that reuses the existing_resolve_provider_connectionlogic with an optional profile name, so a caller-suppliedLLM(no profile name) can resolve itsprovider_connection_idinto a realapi_key+base_url.switch_conversation_llmnow resolves the provider connection (insidestore_errors()) before callingconversation.switch_llm, mirroringswitch_profile. A dangling reference / missing credential surfaces as 422 before the working LLM is replaced; an inline-key config withoutprovider_connection_idis byte-identical to the old path./switch_llmand/switch_profileresolve provider connections identically.Issue Number
Fixes #5439
Ref OpenHands/OpenHands#17206
How to Test
New regression tests in
tests/agent_server/test_conversation_router.py:test_switch_conversation_llm_resolves_provider_connection— aprovider_connection_idis resolved into the connection'sapi_keybefore the LLM is installed (the #17206 regression).test_switch_conversation_llm_resolves_encrypted_provider_connection— encrypted-at-rest credentials are decrypted with the server's cipher and the connection'sbase_urlis applied.test_switch_conversation_llm_inline_key_without_provider_connection— an inlineapi_keywith noprovider_connection_idis applied unchanged (old path preserved).test_switch_conversation_llm_missing_provider_connection_rejects_before_switch— a danglingprovider_connection_id(no inline key) returns 422 and does not callconversation.switch_llm, so the working LLM is not replaced.Result: 8 switch_llm tests pass; combined run of
test_conversation_router.py + test_llm_profile_store.py + test_profiles_router.py→ 266 passed. Ruff + pyright clean. OpenAPI422media type for/switch_llmunchanged (application/jsondefault validation response).End-to-end reproduction (agent-canvas, manual): link an OpenRouter profile to a provider connection, switch a running conversation to it, and send a message — calls now authenticate instead of 401.
This pull request was created by an AI agent (OpenHands) on behalf of @juanmichelini.
🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdkpython-node-runtimepython-node-runtimepython-node-runtimegolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:53af5e9-pythonRun
All tags pushed for this build
About Multi-Architecture Support
53af5e9-python) is a multi-arch manifest supporting both amd64 and arm6453af5e9-python-amd64) are also available if needed