Skip to content

🙌 OpenHands: AI-Driven Development

feat: add LLM provider-connections UI (local agent-server) (#16616)

Juan Pedro Michelini Jorgef2dd33090592
diff --git a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
index 588854ad03..c8c8dc5e67 100644
--- a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
+++ b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
@@ -16,6 +16,7 @@ import ProfilesService from "#/api/profiles-service/profiles-service.api";
vi.mock("#/routes/llm-settings", async () => {
const React = await vi.importActual<typeof import("react")>("react");
return {
+ LLM_PROVIDER_CONNECTION_KEY: "llm.provider_connection_id",
LlmSettingsScreen: ({
initialValueOverrides,
onSaveControlChange,
@@ -654,6 +655,30 @@ describe("LlmSettingsLocalView", () => {
await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());
},
);
+
+ it("skips pre-flight validation for a connection-linked profile", async () => {
+ // A linked profile carries no inline key — its credential lives on the
+ // provider connection — so there is nothing on this profile to pre-flight.
+ const user = userEvent.setup();
+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({
+ name: "gpt-4-profile",
+ api_key_set: true,
+ config: {
+ model: "anthropic/claude-sonnet-4",
+ provider_connection_id: "conn1",
+ },
+ });
+ mockSaveMutateAsync.mockResolvedValue({ success: true });
+ renderWithProviders(<LlmSettingsLocalView />);
+ await openEditView(user);
+ await waitFor(() => {
+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();
+ });
+ await user.click(screen.getByTestId("save-profile-btn"));
+
+ await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());
+ expect(ProfilesService.validateProfile).not.toHaveBeenCalled();
+ });
});
describe("Basic tab save", () => {
diff --git a/__tests__/routes/llm-settings.test.tsx b/__tests__/routes/llm-settings.test.tsx
index f8cfded4f0..7ed33abb30 100644
--- a/__tests__/routes/llm-settings.test.tsx
+++ b/__tests__/routes/llm-settings.test.tsx
@@ -12,6 +12,9 @@ import * as activeBackendContext from "#/contexts/active-backend-context";
import type { Backend } from "#/api/backend-registry/types";
import * as useLlmProfilesHook from "#/hooks/query/use-llm-profiles";
import LLMSubscriptionService from "#/api/llm-subscription-service";
+import ProviderConnectionsService, {
+ type ProviderConnection,
+} from "#/api/provider-connections-service/provider-connections-service.api";
vi.mock("#/hooks/query/use-llm-profiles");
// The profile manager gates mutate controls on this hook; default to a user
@@ -338,6 +341,99 @@ describe("LlmSettingsScreen", () => {
});
});
+describe("LlmSettingsScreen - provider connection selector", () => {
+ const connection: ProviderConnection = {
+ id: "conn-1",
+ display_name: "My OpenAI",
+ provider: "openai",
+ base_url: null,
+ created_at: 1,
+ updated_at: 2,
+ api_key_set: true,
+ };
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({ llm_model: "openai/gpt-4o", llm_api_key_set: true }),
+ );
+ });
+
+ it("hides the selector on cloud even when a connection is linked", async () => {
+ vi.spyOn(activeBackendContext, "useActiveBackend").mockReturnValue({
+ backend: mockCloudBackend,
+ } as ReturnType<typeof activeBackendContext.useActiveBackend>);
+ const listSpy = vi
+ .spyOn(ProviderConnectionsService, "list")
+ .mockResolvedValue([connection]);
+
+ renderLlmSettingsScreen({
+ embedded: true,
+ hideSaveButton: true,
+ // showProviderConnection omitted → cloud path
+ initialValueOverrides: {
+ "llm.model": "openai/gpt-4o",
+ "llm.provider_connection_id": "conn-1",
+ },
+ });
+
+ await screen.findByTestId("llm-settings-screen");
+ expect(
+ screen.queryByTestId("llm-provider-connection-input"),
+ ).not.toBeInTheDocument();
+ expect(listSpy).not.toHaveBeenCalled();
+ });
+
+ it("hides the API key / base URL inputs when linked to a connection", async () => {
+ vi.spyOn(activeBackendContext, "useActiveBackend").mockReturnValue({
+ backend: mockLocalBackend,
+ } as ReturnType<typeof activeBackendContext.useActiveBackend>);
+ vi.spyOn(ProviderConnectionsService, "list").mockResolvedValue([
+ connection,
+ ]);
+
+ renderLlmSettingsScreen({
+ embedded: true,
+ hideSaveButton: true,
+ showProviderConnection: true,
+ initialValueOverrides: {
+ "llm.model": "openai/gpt-4o",
+ "llm.provider_connection_id": "conn-1",
+ },
+ });
+
+ await screen.findByTestId("llm-settings-screen");
+ await screen.findByTestId("llm-provider-connection-input");
+ expect(screen.queryByTestId("llm-api-key-input")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("base-url-input")).not.toBeInTheDocument();
+ });
+
+ it("still renders the selector for an orphaned link when no connections load", async () => {
+ // Regression: a profile linked to a since-deleted connection would hide the
+ // API key / base URL inputs while also hiding the selector, leaving no way
+ // to recover the credential or unlink.
+ vi.spyOn(activeBackendContext, "useActiveBackend").mockReturnValue({
+ backend: mockLocalBackend,
+ } as ReturnType<typeof activeBackendContext.useActiveBackend>);
+ vi.spyOn(ProviderConnectionsService, "list").mockResolvedValue([]);
+
+ renderLlmSettingsScreen({
+ embedded: true,
+ hideSaveButton: true,
+ showProviderConnection: true,
+ initialValueOverrides: {
+ "llm.model": "openai/gpt-4o",
+ "llm.provider_connection_id": "conn-gone",
+ },
+ });
+
+ await screen.findByTestId("llm-settings-screen");
+ expect(
+ await screen.findByTestId("llm-provider-connection-input"),
+ ).toBeInTheDocument();
+ });
+});
+
describe("LlmSettingsRoute - backend mode rendering", () => {
beforeEach(() => {
vi.restoreAllMocks();
diff --git a/src/api/profiles-service/profiles-service.api.ts b/src/api/profiles-service/profiles-service.api.ts
index 7d08ceeb6c..c2a511e21b 100644
--- a/src/api/profiles-service/profiles-service.api.ts
+++ b/src/api/profiles-service/profiles-service.api.ts
@@ -20,15 +20,15 @@ import {
ProfilesClient,
type GetProfileOptions,
} from "@openhands/typescript-client/clients";
-import {
- type ProfileInfo,
- type ProfileListResponse,
- type ProfileDetailResponse,
- type ProfileMutationResponse,
- type ActivateProfileResponse,
- type SaveProfileRequest,
- type ExposeSecretsMode,
- type ValidateProfileResponse,
+import type {
+ ProfileInfo as ClientProfileInfo,
+ ProfileListResponse as ClientProfileListResponse,
+ ProfileDetailResponse,
+ ProfileMutationResponse,
+ ActivateProfileResponse,
+ SaveProfileRequest,
+ ExposeSecretsMode,
+ ValidateProfileResponse,
} from "@openhands/typescript-client";
import { getAgentServerClientOptions } from "../agent-server-client-options";
import { getActiveBackend } from "../backend-registry/active-store";
@@ -41,10 +41,27 @@ import {
saveCloudProfile,
} from "../cloud/profiles-service.api";
+/**
+ * Profile summaries carry an optional `provider_connection_id` (the shared
+ * provider connection a profile links to), but `@openhands/typescript-client`
+ * predates that field. Widen the client types here so consumers can read it; it
+ * stays optional, so a client response without the field is still assignable.
+ */
+export interface ProfileInfo extends ClientProfileInfo {
+ provider_connection_id?: string | null;
+ /** True when provider_connection_id is set but the referenced connection no longer exists. */
+ provider_connection_broken?: boolean;
+}
+
+export interface ProfileListResponse extends Omit<
+ ClientProfileListResponse,
+ "profiles"
+> {
+ profiles: ProfileInfo[];
+}
+
// Re-export SDK types for consumers
export type {
- ProfileInfo,
- ProfileListResponse,
ProfileDetailResponse,
ProfileMutationResponse,
ActivateProfileResponse,
diff --git a/src/api/provider-connections-service/provider-connections-service.api.test.ts b/src/api/provider-connections-service/provider-connections-service.api.test.ts
new file mode 100644
index 0000000000..14817d1542
--- /dev/null
+++ b/src/api/provider-connections-service/provider-connections-service.api.test.ts
@@ -0,0 +1,130 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import { AgentServerClient } from "@openhands/typescript-client/clients";
+import ProviderConnectionsService from "./provider-connections-service.api";
+
+const getMock = vi.hoisted(() => vi.fn());
+const postMock = vi.hoisted(() => vi.fn());
+const patchMock = vi.hoisted(() => vi.fn());
+const deleteMock = vi.hoisted(() => vi.fn());
+const closeMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ AgentServerClient: vi.fn(function AgentServerClientMock() {
+ return {
+ get: getMock,
+ post: postMock,
+ patch: patchMock,
+ delete: deleteMock,
+ close: closeMock,
+ };
+ }),
+}));
+
+const localBackend: Backend = {
+ id: "local-test",
+ name: "Local test backend",
+ host: "http://localhost:3000",
+ apiKey: "test-session-key",
+ kind: "local",
+};
+
+const connection = {
+ id: "conn-1",
+ display_name: "My OpenAI",
+ provider: "openai",
+ base_url: null,
+ created_at: 1,
+ updated_at: 2,
+ api_key_set: true,
+};
+
+const PATH = "/api/llm/provider-connections";
+
+describe("ProviderConnectionsService", () => {
+ beforeEach(() => {
+ getMock.mockReset();
+ postMock.mockReset();
+ patchMock.mockReset();
+ deleteMock.mockReset();
+ closeMock.mockReset();
+ vi.mocked(AgentServerClient).mockClear();
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ });
+
+ afterEach(() => {
+ setActiveSelection(null);
+ setRegisteredBackends([]);
+ });
+
+ it("lists connections via the typed client and closes it", async () => {
+ getMock.mockResolvedValue([connection]);
+
+ const result = await ProviderConnectionsService.list();
+
+ expect(result).toEqual([connection]);
+ expect(vi.mocked(AgentServerClient)).toHaveBeenCalledWith({
+ host: "http://localhost:3000",
+ apiKey: "test-session-key",
+ });
+ expect(getMock).toHaveBeenCalledWith(PATH, { responseType: "json" });
+ expect(closeMock).toHaveBeenCalled();
+ });
+
+ it("creates a connection with the request body", async () => {
+ postMock.mockResolvedValue(connection);
+
+ const request = {
+ display_name: "My OpenAI",
+ provider: "openai",
+ api_key: "sk-123",
+ base_url: null,
+ };
+ const result = await ProviderConnectionsService.create(request);
+
+ expect(result).toEqual(connection);
+ expect(postMock).toHaveBeenCalledWith(PATH, request, {
+ responseType: "json",
+ });
+ expect(closeMock).toHaveBeenCalled();
+ });
+
+ it("updates a connection at the id-scoped path", async () => {
+ patchMock.mockResolvedValue(connection);
+
+ const result = await ProviderConnectionsService.update("conn-1", {
+ display_name: "Renamed",
+ });
+
+ expect(result).toEqual(connection);
+ expect(patchMock).toHaveBeenCalledWith(
+ `${PATH}/conn-1`,
+ { display_name: "Renamed" },
+ { responseType: "json" },
+ );
+ expect(closeMock).toHaveBeenCalled();
+ });
+
+ it("url-encodes the id when deleting", async () => {
+ deleteMock.mockResolvedValue(connection);
+
+ await ProviderConnectionsService.delete("a b/c");
+
+ expect(deleteMock).toHaveBeenCalledWith(`${PATH}/a%20b%2Fc`, {
+ responseType: "json",
+ });
+ expect(closeMock).toHaveBeenCalled();
+ });
+
+ it("closes the client even when the request throws", async () => {
+ getMock.mockRejectedValue(new Error("boom"));
+
+ await expect(ProviderConnectionsService.list()).rejects.toThrow("boom");
+ expect(closeMock).toHaveBeenCalled();
+ });
+});
diff --git a/src/api/provider-connections-service/provider-connections-service.api.ts b/src/api/provider-connections-service/provider-connections-service.api.ts
new file mode 100644
index 0000000000..6126ff3695
--- /dev/null
+++ b/src/api/provider-connections-service/provider-connections-service.api.ts
@@ -0,0 +1,111 @@
+/**
+ * ProviderConnectionsService is a thin wrapper over the local agent-server's
+ * `/api/llm/provider-connections` CRUD endpoints. A provider connection is a
+ * shared `api_key` + optional `base_url` that one or more LLM profiles
+ * reference by id; the agent-server resolves the credential into a runnable LLM
+ * at profile-load time, so this service only manages the stored connections.
+ *
+ * These endpoints exist only on the agent-server (local backend). Cloud has no
+ * equivalent yet, so callers must gate usage on `backend.kind === "local"`.
+ *
+ * There is no generated client for these routes in `@openhands/typescript-client`
+ * yet, so requests go through the generic `AgentServerClient` verb helpers —
+ * the same approach `LLMBalanceService` uses.
+ */
+import { AgentServerClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
+
+const PROVIDER_CONNECTIONS_PATH = "/api/llm/provider-connections";
+
+export interface ProviderConnection {
+ id: string;
+ display_name: string;
+ provider: string;
+ base_url: string | null;
+ created_at: number;
+ updated_at: number;
+ /** Whether the stored connection currently holds a usable key. */
+ api_key_set: boolean;
+}
+
+export interface CreateProviderConnectionRequest {
+ display_name: string;
+ provider: string;
+ api_key: string;
+ base_url?: string | null;
+}
+
+/**
+ * Partial update. Only the provided fields change. `api_key` may be sent to
+ * rotate the key; the agent-server rejects `api_key: null` (a connection must
+ * always keep a key), so callers omit it to leave the key unchanged.
+ */
+export interface UpdateProviderConnectionRequest {
+ display_name?: string;
+ provider?: string;
+ api_key?: string;
+ base_url?: string | null;
+}
+
+function createClient(): AgentServerClient {
+ const { host, apiKey } = getAgentServerClientOptions();
+ return new AgentServerClient({ host, ...(apiKey ? { apiKey } : {}) });
+}
+
+class ProviderConnectionsService {
+ static async list(): Promise<ProviderConnection[]> {
+ const client = createClient();
+ try {
+ return await client.get<ProviderConnection[]>(PROVIDER_CONNECTIONS_PATH, {
+ responseType: "json",
+ });
+ } finally {
+ client.close();
+ }
+ }
+
+ static async create(
+ request: CreateProviderConnectionRequest,
+ ): Promise<ProviderConnection> {
+ const client = createClient();
+ try {
+ return await client.post<ProviderConnection>(
+ PROVIDER_CONNECTIONS_PATH,
+ request,
+ { responseType: "json" },
+ );
+ } finally {
+ client.close();
+ }
+ }
+
+ static async update(
+ id: string,
+ request: UpdateProviderConnectionRequest,
+ ): Promise<ProviderConnection> {
+ const client = createClient();
+ try {
+ return await client.patch<ProviderConnection>(
+ `${PROVIDER_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,
+ request,
+ { responseType: "json" },
+ );
+ } finally {
+ client.close();
+ }
+ }
+
+ static async delete(id: string): Promise<ProviderConnection> {
+ const client = createClient();
+ try {
+ return await client.delete<ProviderConnection>(
+ `${PROVIDER_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,
+ { responseType: "json" },
+ );
+ } finally {
+ client.close();
+ }
+ }
+}
+
+export default ProviderConnectionsService;
diff --git a/src/components/features/settings/llm-profiles/delete-provider-connection-modal.tsx b/src/components/features/settings/llm-profiles/delete-provider-connection-modal.tsx
new file mode 100644
index 0000000000..d557cfdbae
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/delete-provider-connection-modal.tsx
@@ -0,0 +1,96 @@
+import { useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinner } from "#/components/shared/loading-spinner";
+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import { useDeleteProviderConnection } from "#/hooks/mutation/use-delete-provider-connection";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
+import { I18nKey } from "#/i18n/declaration";
+
+interface DeleteProviderConnectionModalProps {
+ connection: ProviderConnection | null;
+ onClose: () => void;
+}
+
+export function DeleteProviderConnectionModal({
+ connection,
+ onClose,
+}: DeleteProviderConnectionModalProps) {
+ const { t } = useTranslation("openhands");
+ const deleteConnection = useDeleteProviderConnection();
+ const cancelButtonRef = useRef<HTMLButtonElement>(null);
+
+ if (!connection) return null;
+
+ const handleDelete = async () => {
+ try {
+ await deleteConnection.mutateAsync(connection.id);
+ displaySuccessToast(
+ t(I18nKey.SETTINGS$PROVIDER_CONNECTION_DELETED, {
+ name: connection.display_name,
+ }),
+ );
+ onClose();
+ } catch (error) {
+ // The agent-server returns 409 with a message naming the profiles that
+ // still reference this connection; surface it verbatim.
+ displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
+ }
+ };
+
+ const handleClose = () => {
+ if (!deleteConnection.isPending) onClose();
+ };
+
+ const footer = (
+ <>
+ <BrandButton
+ ref={cancelButtonRef}
+ type="button"
+ variant="tertiary"
+ onClick={handleClose}
+ isDisabled={deleteConnection.isPending}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ testId="delete-provider-connection-confirm"
+ type="button"
+ variant="danger"
+ onClick={handleDelete}
+ isDisabled={deleteConnection.isPending}
+ aria-busy={deleteConnection.isPending}
+ >
+ {deleteConnection.isPending ? (
+ <>
+ <LoadingSpinner size="small" />
+ <span className="sr-only">{t(I18nKey.BUTTON$DELETE)}</span>
+ </>
+ ) : (
+ t(I18nKey.BUTTON$DELETE)
+ )}
+ </BrandButton>
+ </>
+ );
+
+ return (
+ <ApiKeyModalBase
+ isOpen
+ title={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_DELETE_TITLE)}
+ footer={footer}
+ onClose={handleClose}
+ initialFocusRef={cancelButtonRef}
+ >
+ <p className="text-sm break-all">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTION_DELETE_CONFIRMATION, {
+ name: connection.display_name,
+ })}
+ </p>
+ </ApiKeyModalBase>
+ );
+}
diff --git a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx
index c354147a40..28f617190f 100644
--- a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx
+++ b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx
@@ -1,17 +1,20 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { BrandButton } from "#/components/features/settings/brand-button";
import { RenameProfileModal } from "./rename-profile-modal";
import { DeleteProfileModal } from "./delete-profile-modal";
import { ProfilesBody } from "./profiles-body";
+import { ProviderConnectionsManager } from "./provider-connections-manager";
import ProfilesService, {
ProfileInfo,
type SaveProfileRequest,
} from "#/api/profiles-service/profiles-service.api";
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
+import { useProviderConnections } from "#/hooks/query/use-provider-connections";
import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";
import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import {
displayErrorToast,
displaySuccessToast,
@@ -34,6 +37,14 @@ export function LlmProfilesManager({
// Cloud members are view-only; only owners/admins (and all local users) may
// add, edit, rename, duplicate, delete, or activate profiles.
const canManage = useCanManageOrgProfiles();
+ // Provider connections exist only on the local agent-server.
+ const { backend } = useActiveBackend();
+ const isLocal = backend.kind === "local";
+ const {
+ data: connections,
+ isLoading: isLoadingConnections,
+ error: connectionsError,
+ } = useProviderConnections();
const [profileToRename, setProfileToRename] = useState<ProfileInfo | null>(
null,
);
@@ -43,6 +54,20 @@ export function LlmProfilesManager({
const profiles = data?.profiles ?? [];
const active = data?.active_profile ?? null;
+ const connectionList = useMemo(() => connections ?? [], [connections]);
+
+ const connectionNamesById = useMemo(
+ () => Object.fromEntries(connectionList.map((c) => [c.id, c.display_name])),
+ [connectionList],
+ );
+ const linkedCountById = useMemo(() => {
+ const counts: Record<string, number> = {};
+ for (const profile of profiles) {
+ const id = profile.provider_connection_id;
+ if (id) counts[id] = (counts[id] ?? 0) + 1;
+ }
+ return counts;
+ }, [profiles]);
const handleActivate = async (name: string) => {
try {
@@ -95,37 +120,49 @@ export function LlmProfilesManager({
return (
<>
- <div className="flex flex-col gap-4">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <h2 className="text-base font-medium text-white">
- {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}
- </h2>
- {onAddProfile && canManage ? (
- <BrandButton
- testId="add-llm-profile"
- type="button"
- variant="secondary"
- className="ml-auto"
- onClick={onAddProfile}
- >
- {t(I18nKey.SETTINGS$ADD_LLM_PROFILE)}
- </BrandButton>
- ) : null}
+ <div className="flex flex-col gap-8">
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h2 className="text-base font-medium text-white">
+ {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}
+ </h2>
+ {onAddProfile && canManage ? (
+ <BrandButton
+ testId="add-llm-profile"
+ type="button"
+ variant="secondary"
+ className="ml-auto"
+ onClick={onAddProfile}
+ >
+ {t(I18nKey.SETTINGS$ADD_LLM_PROFILE)}
+ </BrandButton>
+ ) : null}
+ </div>
+
+ <ProfilesBody
+ isLoading={isLoading}
+ loadError={error ?? null}
+ profiles={profiles}
+ active={active}
+ canManage={canManage}
+ connectionNamesById={connectionNamesById}
+ onActivate={handleActivate}
+ onEdit={handleEdit}
+ onRename={setProfileToRename}
+ onDuplicate={handleDuplicate}
+ onDelete={setProfileToDelete}
+ isActivating={activateProfile.isPending}
+ />
</div>
- <ProfilesBody
- isLoading={isLoading}
- loadError={error ?? null}
- profiles={profiles}
- active={active}
- canManage={canManage}
- onActivate={handleActivate}
- onEdit={handleEdit}
- onRename={setProfileToRename}
- onDuplicate={handleDuplicate}
- onDelete={setProfileToDelete}
- isActivating={activateProfile.isPending}
- />
+ {isLocal && canManage ? (
+ <ProviderConnectionsManager
+ connections={connectionList}
+ linkedCountById={linkedCountById}
+ isLoading={isLoadingConnections}
+ loadError={connectionsError ?? null}
+ />
+ ) : null}
</div>
<RenameProfileModal
diff --git a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
index 5ceb8ecd5c..3bb49e0066 100644
--- a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
+++ b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
@@ -9,7 +9,11 @@ import { useTranslation } from "react-i18next";
import { LlmProfilesManager } from "./llm-profiles-manager";
import { ProfileNameInput } from "./profile-name-input";
import { BrandButton } from "#/components/features/settings/brand-button";
-import { LlmSettingsScreen } from "#/routes/llm-settings";
+import {
+ LlmSettingsScreen,
+ LLM_PROVIDER_CONNECTION_KEY,
+} from "#/routes/llm-settings";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
@@ -104,6 +108,10 @@ export function LlmSettingsLocalView() {
const agentSchemaRef = useRef(agentSchema);
agentSchemaRef.current = agentSchema;
+ // Provider connections are a local agent-server feature.
+ const { backend } = useActiveBackend();
+ const isLocal = backend.kind === "local";
+
const [viewMode, setViewMode] = useState<ViewMode>("list");
const [profileName, setProfileName] = useState("");
const [editingProfile, setEditingProfile] = useState<EditingProfile | null>(
@@ -197,6 +205,13 @@ export function LlmSettingsLocalView() {
OPENAI_SUBSCRIPTION_VENDOR;
}
+ // Seed the provider-connection link explicitly (it is excluded from the
+ // schema-driven inputs), so an unchanged profile keeps its connection.
+ initialValues[LLM_PROVIDER_CONNECTION_KEY] =
+ typeof config.provider_connection_id === "string"
+ ? config.provider_connection_id
+ : "";
+
setEditingProfile({ profile, initialValues, baseConfig: config });
setProfileName(profile.name);
setViewMode("edit");
@@ -271,14 +286,31 @@ export function LlmSettingsLocalView() {
const llmConfig: Record<string, unknown> = { ...baseConfig, ...dirtyLlm };
const authType = resolveLlmAuthType(llmConfig.auth_type);
+ // A profile linked to a provider connection sources its credential from the
+ // connection, so it never carries an inline api_key / base_url. The form
+ // value is the source of truth: empty (or absent) means "not linked".
+ const connectionId = isLocal
+ ? String(saveControl.values[LLM_PROVIDER_CONNECTION_KEY] ?? "").trim()
+ : "";
+
if (authType === LLM_AUTH_TYPE_SUBSCRIPTION) {
llmConfig.auth_type = LLM_AUTH_TYPE_SUBSCRIPTION;
llmConfig.subscription_vendor = OPENAI_SUBSCRIPTION_VENDOR;
+ llmConfig.provider_connection_id = null;
+ delete llmConfig.api_key;
+ delete llmConfig.base_url;
+ } else if (connectionId) {
+ llmConfig.auth_type = LLM_AUTH_TYPE_API_KEY;
+ llmConfig.subscription_vendor = null;
+ llmConfig.provider_connection_id = connectionId;
delete llmConfig.api_key;
delete llmConfig.base_url;
} else {
llmConfig.auth_type = LLM_AUTH_TYPE_API_KEY;
llmConfig.subscription_vendor = null;
+ // Clear any prior link so unlinking sticks (only relevant on local; on
+ // cloud the field stays untouched below).
+ if (isLocal) llmConfig.provider_connection_id = null;
// The Basic tab has no base_url field. Preserve an existing hidden value
// when the model did not actually change; if the user chooses a new model,
@@ -324,14 +356,20 @@ export function LlmSettingsLocalView() {
setIsSaving(true);
setIsValidating(true);
try {
- const preflight = await ProfilesService.validateProfile(trimmedName, {
- llm: llmConfig as SaveProfileRequest["llm"],
- include_secrets: true,
- });
- if (preflight && !preflight.valid) {
- const errorMsg = preflight.error?.message ?? t(I18nKey.ERROR$GENERIC);
- displayErrorToast(errorMsg);
- return;
+ // Pre-flight validation fires a minimal completion to catch a
+ // misconfigured profile before saving it. Skip it for connection-linked
+ // profiles: their credential lives on the provider connection, not
+ // inline, so there is nothing on this profile to pre-flight here.
+ if (!connectionId) {
+ const preflight = await ProfilesService.validateProfile(trimmedName, {
+ llm: llmConfig as SaveProfileRequest["llm"],
+ include_secrets: true,
+ });
+ if (preflight && !preflight.valid) {
+ const errorMsg = preflight.error?.message ?? t(I18nKey.ERROR$GENERIC);
+ displayErrorToast(errorMsg);
+ return;
+ }
}
setIsValidating(false);
@@ -372,6 +410,7 @@ export function LlmSettingsLocalView() {
}, [
saveControl,
isNameValid,
+ isLocal,
profileName,
viewMode,
editingProfile,
@@ -449,10 +488,12 @@ export function LlmSettingsLocalView() {
"llm.model": DEFAULT_SETTINGS.llm_model,
"llm.api_key": "",
"llm.base_url": "",
+ [LLM_PROVIDER_CONNECTION_KEY]: "",
[LLM_AUTH_TYPE_KEY]: LLM_AUTH_TYPE_API_KEY,
[LLM_SUBSCRIPTION_VENDOR_KEY]: OPENAI_SUBSCRIPTION_VENDOR,
}
}
+ showProviderConnection={isLocal}
onSaveControlChange={handleSaveControlChange}
/>
diff --git a/src/components/features/settings/llm-profiles/profile-row.tsx b/src/components/features/settings/llm-profiles/profile-row.tsx
index 67cd79a350..cf1415355b 100644
--- a/src/components/features/settings/llm-profiles/profile-row.tsx
+++ b/src/components/features/settings/llm-profiles/profile-row.tsx
@@ -1,4 +1,5 @@
import { useRef, useState } from "react";
+import { AlertTriangle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ProfileActionsMenu } from "./profile-actions-menu";
import { ProfileInfo } from "#/api/profiles-service/profiles-service.api";
@@ -72,6 +73,16 @@ export function ProfileRow({
{t(I18nKey.SETTINGS$PROFILE_DEFAULT)}
</BrandBadge>
)}
+ {profile.provider_connection_broken && (
+ <span
+ className="flex shrink-0 items-center gap-1 whitespace-nowrap rounded-full bg-[var(--oh-warning,#f59e0b)] px-2 py-0.5 text-xs font-medium text-black"
+ title={t(I18nKey.SETTINGS$PROFILE_BROKEN_CONNECTION_TOOLTIP)}
+ data-testid="profile-broken-connection-badge"
+ >
+ <AlertTriangle className="h-3 w-3" aria-hidden />
+ {t(I18nKey.SETTINGS$PROFILE_BROKEN_CONNECTION)}
+ </span>
+ )}
</div>
{canManage && (
<div className="relative shrink-0">
diff --git a/src/components/features/settings/llm-profiles/profiles-body.test.ts b/src/components/features/settings/llm-profiles/profiles-body.test.ts
new file mode 100644
index 0000000000..173bef0282
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/profiles-body.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import type { ProfileInfo } from "#/api/profiles-service/profiles-service.api";
+import { groupProfilesByConnection } from "./profiles-body";
+
+function profile(name: string, connectionId?: string | null): ProfileInfo {
+ return {
+ name,
+ model: "openai/gpt-4o",
+ base_url: null,
+ api_key_set: true,
+ provider_connection_id: connectionId ?? null,
+ };
+}
+
+describe("groupProfilesByConnection", () => {
+ it("groups linked profiles by connection, preserving order", () => {
+ const groups = groupProfilesByConnection(
+ [profile("a", "conn-1"), profile("b", "conn-2"), profile("c", "conn-1")],
+ { "conn-1": "OpenAI", "conn-2": "Anthropic" },
+ );
+
+ expect(groups).toEqual([
+ {
+ connectionId: "conn-1",
+ label: "OpenAI",
+ profiles: [profile("a", "conn-1"), profile("c", "conn-1")],
+ },
+ {
+ connectionId: "conn-2",
+ label: "Anthropic",
+ profiles: [profile("b", "conn-2")],
+ },
+ ]);
+ });
+
+ it("collects unlinked profiles into a trailing null group", () => {
+ const groups = groupProfilesByConnection(
+ [profile("a", "conn-1"), profile("b"), profile("c", null)],
+ { "conn-1": "OpenAI" },
+ );
+
+ expect(groups.map((g) => g.connectionId)).toEqual(["conn-1", null]);
+ expect(groups[1].label).toBeNull();
+ expect(groups[1].profiles.map((p) => p.name)).toEqual(["b", "c"]);
+ });
+
+ it("falls back to the connection id when no display name is known", () => {
+ const groups = groupProfilesByConnection([profile("a", "conn-x")], {});
+
+ expect(groups[0].label).toBe("conn-x");
+ });
+
+ it("omits the unlinked group when every profile is linked", () => {
+ const groups = groupProfilesByConnection([profile("a", "conn-1")], {
+ "conn-1": "OpenAI",
+ });
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0].connectionId).toBe("conn-1");
+ });
+});
diff --git a/src/components/features/settings/llm-profiles/profiles-body.tsx b/src/components/features/settings/llm-profiles/profiles-body.tsx
index 46c78d769a..2fdfd94fa0 100644
--- a/src/components/features/settings/llm-profiles/profiles-body.tsx
+++ b/src/components/features/settings/llm-profiles/profiles-body.tsx
@@ -17,6 +17,13 @@ interface ProfilesBodyProps {
active: string | null;
/** When false, rows render read-only (no actions menu) — cloud members. */
canManage: boolean;
+ /**
+ * Display name per provider-connection id. When non-empty, profiles are
+ * grouped under their connection's name so models sharing a provider are
+ * visually clustered. Empty (the default, and always on cloud) renders a flat
+ * list identical to before.
+ */
+ connectionNamesById?: Record<string, string>;
onActivate: (name: string) => void;
onEdit: (profile: ProfileInfo) => void;
onRename: (profile: ProfileInfo) => void;
@@ -25,12 +32,60 @@ interface ProfilesBodyProps {
isActivating: boolean;
}
+interface ProfileGroup {
+ /** Connection id, or null for profiles with no provider connection. */
+ connectionId: string | null;
+ label: string | null;
+ profiles: ProfileInfo[];
+}
+
+/**
+ * Bucket profiles by their `provider_connection_id`, preserving input order
+ * within each group and ordering groups by first appearance. Unlinked profiles
+ * collect under a trailing `null` group.
+ */
+export function groupProfilesByConnection(
+ profiles: ProfileInfo[],
+ connectionNamesById: Record<string, string>,
+): ProfileGroup[] {
+ const groups = new Map<string, ProfileGroup>();
+ const unlinked: ProfileGroup = {
+ connectionId: null,
+ label: null,
+ profiles: [],
+ };
+
+ for (const profile of profiles) {
+ const connectionId = profile.provider_connection_id ?? null;
+ if (!connectionId) {
+ unlinked.profiles.push(profile);
+ continue;
+ }
+ let group = groups.get(connectionId);
+ if (!group) {
+ group = {
+ connectionId,
+ label: connectionNamesById[connectionId] ?? connectionId,
+ profiles: [],
+ };
+ groups.set(connectionId, group);
+ }
+ group.profiles.push(profile);
+ }
+
+ const linkedGroups = [...groups.values()];
+ return unlinked.profiles.length > 0
+ ? [...linkedGroups, unlinked]
+ : linkedGroups;
+}
+
export function ProfilesBody({
isLoading,
loadError,
profiles,
active,
canManage,
+ connectionNamesById = {},
onActivate,
onEdit,
onRename,
@@ -40,6 +95,26 @@ export function ProfilesBody({
}: ProfilesBodyProps) {
const { t } = useTranslation("openhands");
+ const renderRow = (profile: ProfileInfo) => (
+ <ProfileRow
+ key={profile.name}
+ profile={profile}
+ isActive={profile.name === active}
+ canManage={canManage}
+ onActivate={onActivate}
+ onEdit={onEdit}
+ onRename={onRename}
+ onDuplicate={onDuplicate}
+ onDelete={onDelete}
+ isActivating={isActivating}
+ />
+ );
+
+ const listClassName = cn(
+ settingsListContainerClassName,
+ settingsListDividerClassName,
+ );
+
if (isLoading) {
return (
<div className="flex justify-center p-4">
@@ -74,26 +149,29 @@ export function ProfilesBody({
);
}
+ // Group only when there is at least one linked connection to show; otherwise
+ // (every profile today, and always on cloud) render the flat list unchanged.
+ const hasLinkedProfiles = profiles.some((p) => p.provider_connection_id);
+ if (!hasLinkedProfiles) {
+ return <div className={listClassName}>{profiles.map(renderRow)}</div>;
+ }
+
+ const groups = groupProfilesByConnection(profiles, connectionNamesById);
return (
- <div
- className={cn(
- settingsListContainerClassName,
- settingsListDividerClassName,
- )}
- >
- {profiles.map((profile) => (
- <ProfileRow
- key={profile.name}
- profile={profile}
- isActive={profile.name === active}
- canManage={canManage}
- onActivate={onActivate}
- onEdit={onEdit}
- onRename={onRename}
- onDuplicate={onDuplicate}
- onDelete={onDelete}
- isActivating={isActivating}
- />
+ <div className="flex flex-col gap-4">
+ {groups.map((group) => (
+ <div
+ key={group.connectionId ?? "__unlinked__"}
+ className="flex flex-col gap-2"
+ >
+ <h3
+ data-testid="profile-group-header"
+ className="text-xs font-medium uppercase tracking-wide text-[var(--oh-muted)]"
+ >
+ {group.label ?? t(I18nKey.SETTINGS$PROFILES_UNGROUPED)}
+ </h3>
+ <div className={listClassName}>{group.profiles.map(renderRow)}</div>
+ </div>
))}
</div>
);
diff --git a/src/components/features/settings/llm-profiles/provider-connection-modal.tsx b/src/components/features/settings/llm-profiles/provider-connection-modal.tsx
new file mode 100644
index 0000000000..606697e23a
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/provider-connection-modal.tsx
@@ -0,0 +1,206 @@
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { KeyStatusIcon } from "#/components/features/settings/key-status-icon";
+import { LoadingSpinner } from "#/components/shared/loading-spinner";
+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import { useCreateProviderConnection } from "#/hooks/mutation/use-create-provider-connection";
+import { useUpdateProviderConnection } from "#/hooks/mutation/use-update-provider-connection";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
+import { I18nKey } from "#/i18n/declaration";
+
+const DEFAULT_PROVIDER = "custom";
+
+interface ProviderConnectionModalProps {
+ /** When `null` the modal is closed; otherwise it edits that connection. */
+ connection?: ProviderConnection | null;
+ /** When true the modal creates a new connection. */
+ isCreate: boolean;
+ onClose: () => void;
+ /** Called with the saved connection so a caller can select it (create flow). */
+ onSaved?: (connection: ProviderConnection) => void;
+}
+
+/**
+ * Single modal for creating, editing, and rotating a provider connection. Create
+ * is a POST; every edit (rename, base_url, key rotation) is a single PATCH. The
+ * key field follows the same "empty means unchanged" convention as the profile
+ * form, so a blank key on edit is simply omitted from the request — the
+ * agent-server rejects `api_key: null`, so we never send it.
+ */
+export function ProviderConnectionModal({
+ connection,
+ isCreate,
+ onClose,
+ onSaved,
+}: ProviderConnectionModalProps) {
+ const { t } = useTranslation("openhands");
+ const createConnection = useCreateProviderConnection();
+ const updateConnection = useUpdateProviderConnection();
+ const firstFieldRef = useRef<HTMLInputElement>(null);
+
+ const [displayName, setDisplayName] = useState("");
+ const [provider, setProvider] = useState(DEFAULT_PROVIDER);
+ const [apiKey, setApiKey] = useState("");
+ const [baseUrl, setBaseUrl] = useState("");
+
+ const isOpen = isCreate || Boolean(connection);
+ const keyAlreadySet = Boolean(connection?.api_key_set);
+
+ useEffect(() => {
+ setDisplayName(connection?.display_name ?? "");
+ setProvider(connection?.provider ?? DEFAULT_PROVIDER);
+ setBaseUrl(connection?.base_url ?? "");
+ setApiKey("");
+ }, [connection, isCreate]);
+
+ const isPending = createConnection.isPending || updateConnection.isPending;
+ const trimmedName = displayName.trim();
+ const trimmedKey = apiKey.trim();
+ // On create the key is required; on edit an empty key means "leave unchanged".
+ const isValid = Boolean(trimmedName) && (!isCreate || Boolean(trimmedKey));
+
+ if (!isOpen) return null;
+
+ const handleClose = () => {
+ if (!isPending) onClose();
+ };
+
+ const handleSubmit = async () => {
+ if (!isValid || isPending) return;
+ const trimmedBaseUrl = baseUrl.trim();
+
+ try {
+ if (isCreate) {
+ const created = await createConnection.mutateAsync({
+ display_name: trimmedName,
+ provider: provider.trim() || DEFAULT_PROVIDER,
+ api_key: trimmedKey,
+ base_url: trimmedBaseUrl || null,
+ });
+ displaySuccessToast(
+ t(I18nKey.SETTINGS$PROVIDER_CONNECTION_CREATED, {
+ name: created.display_name,
+ }),
+ );
+ onSaved?.(created);
+ } else if (connection) {
+ const updated = await updateConnection.mutateAsync({
+ id: connection.id,
+ request: {
+ display_name: trimmedName,
+ provider: provider.trim() || DEFAULT_PROVIDER,
+ base_url: trimmedBaseUrl || null,
+ // Omit the key entirely when left blank so the stored key is kept.
+ ...(trimmedKey ? { api_key: trimmedKey } : {}),
+ },
+ });
+ displaySuccessToast(
+ t(I18nKey.SETTINGS$PROVIDER_CONNECTION_UPDATED, {
+ name: updated.display_name,
+ }),
+ );
+ onSaved?.(updated);
+ }
+ onClose();
+ } catch (error) {
+ displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
+ }
+ };
+
+ const footer = (
+ <>
+ <BrandButton
+ type="button"
+ variant="tertiary"
+ onClick={handleClose}
+ isDisabled={isPending}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ testId="provider-connection-submit"
+ type="button"
+ variant="primary"
+ onClick={handleSubmit}
+ isDisabled={isPending || !isValid}
+ aria-busy={isPending}
+ >
+ {isPending ? <LoadingSpinner size="small" /> : t(I18nKey.BUTTON$SAVE)}
+ </BrandButton>
+ </>
+ );
+
+ return (
+ <ApiKeyModalBase
+ isOpen
+ title={
+ isCreate
+ ? t(I18nKey.SETTINGS$PROVIDER_CONNECTION_ADD_TITLE)
+ : t(I18nKey.SETTINGS$PROVIDER_CONNECTION_EDIT_TITLE)
+ }
+ footer={footer}
+ onClose={handleClose}
+ initialFocusRef={firstFieldRef}
+ >
+ <div
+ data-testid="provider-connection-modal"
+ className="flex flex-col gap-4"
+ >
+ <SettingsInput
+ ref={firstFieldRef}
+ testId="provider-connection-name-input"
+ label={t(I18nKey.SETTINGS$NAME)}
+ type="text"
+ className="w-full"
+ value={displayName}
+ onChange={setDisplayName}
+ required
+ />
+ <SettingsInput
+ testId="provider-connection-provider-input"
+ label={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_PROVIDER)}
+ type="text"
+ className="w-full"
+ value={provider}
+ onChange={setProvider}
+ />
+ <SettingsInput
+ testId="provider-connection-api-key-input"
+ label={t(I18nKey.SETTINGS_FORM$API_KEY)}
+ type="password"
+ className="w-full"
+ value={apiKey}
+ // eslint-disable-next-line i18next/no-literal-string -- masked-key sentinel, not translatable
+ placeholder={keyAlreadySet ? "<hidden>" : ""}
+ onChange={setApiKey}
+ startContent={
+ keyAlreadySet ? <KeyStatusIcon isSet={keyAlreadySet} /> : undefined
+ }
+ hint={
+ keyAlreadySet
+ ? t(I18nKey.SETTINGS$PROVIDER_CONNECTION_ROTATE_HINT)
+ : undefined
+ }
+ />
+ <SettingsInput
+ testId="provider-connection-base-url-input"
+ label={t(I18nKey.SETTINGS$BASE_URL)}
+ type="text"
+ className="w-full"
+ value={baseUrl}
+ // eslint-disable-next-line i18next/no-literal-string -- example value, not translatable
+ placeholder="https://api.openai.com"
+ onChange={setBaseUrl}
+ showOptionalTag
+ />
+ </div>
+ </ApiKeyModalBase>
+ );
+}
diff --git a/src/components/features/settings/llm-profiles/provider-connection-row.tsx b/src/components/features/settings/llm-profiles/provider-connection-row.tsx
new file mode 100644
index 0000000000..befcb462ec
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/provider-connection-row.tsx
@@ -0,0 +1,73 @@
+import { useTranslation } from "react-i18next";
+import EditIcon from "#/icons/u-edit.svg?react";
+import DeleteIcon from "#/icons/u-delete.svg?react";
+import { KeyStatusIcon } from "#/components/features/settings/key-status-icon";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import { cn } from "#/utils/utils";
+import {
+ settingsListIconActionButtonClassName,
+ settingsListRowClassName,
+} from "#/utils/settings-list-classes";
+import { I18nKey } from "#/i18n/declaration";
+
+interface ProviderConnectionRowProps {
+ connection: ProviderConnection;
+ /** Number of LLM profiles linked to this connection. */
+ linkedProfileCount: number;
+ onEdit: (connection: ProviderConnection) => void;
+ onDelete: (connection: ProviderConnection) => void;
+}
+
+export function ProviderConnectionRow({
+ connection,
+ linkedProfileCount,
+ onEdit,
+ onDelete,
+}: ProviderConnectionRowProps) {
+ const { t } = useTranslation("openhands");
+
+ return (
+ <div
+ data-testid="provider-connection-row"
+ className={cn(settingsListRowClassName, "justify-between gap-3")}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <span
+ className="min-w-0 max-w-full truncate text-sm font-medium text-white"
+ title={connection.display_name}
+ >
+ {connection.display_name}
+ </span>
+ <span className="min-w-0 max-w-full truncate text-sm text-[var(--oh-muted)]">
+ {connection.provider}
+ </span>
+ <span className="shrink-0 text-sm text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTION_MODEL_COUNT, {
+ count: linkedProfileCount,
+ })}
+ </span>
+ <KeyStatusIcon isSet={connection.api_key_set} />
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ type="button"
+ data-testid="provider-connection-edit"
+ aria-label={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_EDIT_TITLE)}
+ className={settingsListIconActionButtonClassName}
+ onClick={() => onEdit(connection)}
+ >
+ <EditIcon width={16} height={16} />
+ </button>
+ <button
+ type="button"
+ data-testid="provider-connection-delete"
+ aria-label={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_DELETE_TITLE)}
+ className={settingsListIconActionButtonClassName}
+ onClick={() => onDelete(connection)}
+ >
+ <DeleteIcon width={16} height={16} />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/settings/llm-profiles/provider-connections-manager.test.tsx b/src/components/features/settings/llm-profiles/provider-connections-manager.test.tsx
new file mode 100644
index 0000000000..9761382ec5
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/provider-connections-manager.test.tsx
@@ -0,0 +1,98 @@
+import { screen, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+import ProviderConnectionsService, {
+ type ProviderConnection,
+} from "#/api/provider-connections-service/provider-connections-service.api";
+import { ProviderConnectionsManager } from "./provider-connections-manager";
+
+const displayErrorToast = vi.hoisted(() => vi.fn());
+const displaySuccessToast = vi.hoisted(() => vi.fn());
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast,
+ displaySuccessToast,
+}));
+
+const renderWith = (ui: React.ReactElement) => renderWithProviders(ui);
+
+const connection: ProviderConnection = {
+ id: "conn-1",
+ display_name: "My OpenAI",
+ provider: "openai",
+ base_url: null,
+ created_at: 1,
+ updated_at: 2,
+ api_key_set: true,
+};
+
+describe("ProviderConnectionsManager", () => {
+ beforeEach(() => {
+ displayErrorToast.mockReset();
+ displaySuccessToast.mockReset();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("shows an empty state when there are no connections", () => {
+ renderWith(
+ <ProviderConnectionsManager
+ connections={[]}
+ linkedCountById={{}}
+ isLoading={false}
+ loadError={null}
+ />,
+ );
+
+ expect(
+ screen.getByTestId("provider-connections-empty"),
+ ).toBeInTheDocument();
+ });
+
+ it("lists a row per connection with its display name and provider", () => {
+ renderWith(
+ <ProviderConnectionsManager
+ connections={[connection]}
+ linkedCountById={{ "conn-1": 3 }}
+ isLoading={false}
+ loadError={null}
+ />,
+ );
+
+ expect(screen.getByTestId("provider-connection-row")).toBeInTheDocument();
+ expect(screen.getByText("My OpenAI")).toBeInTheDocument();
+ expect(screen.getByText("openai")).toBeInTheDocument();
+ });
+
+ it("surfaces the server message when deleting a referenced connection fails", async () => {
+ const conflict = Object.assign(new Error("HTTP 409"), {
+ response: {
+ detail: "Connection is used by profile 'gpt-4o'.",
+ },
+ });
+ const deleteSpy = vi
+ .spyOn(ProviderConnectionsService, "delete")
+ .mockRejectedValue(conflict);
+
+ renderWith(
+ <ProviderConnectionsManager
+ connections={[connection]}
+ linkedCountById={{ "conn-1": 1 }}
+ isLoading={false}
+ loadError={null}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("provider-connection-delete"));
+ fireEvent.click(screen.getByTestId("delete-provider-connection-confirm"));
+
+ await waitFor(() => {
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ "Connection is used by profile 'gpt-4o'.",
+ );
+ });
+ expect(deleteSpy).toHaveBeenCalledWith("conn-1");
+ });
+});
diff --git a/src/components/features/settings/llm-profiles/provider-connections-manager.tsx b/src/components/features/settings/llm-profiles/provider-connections-manager.tsx
new file mode 100644
index 0000000000..bae33195ca
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/provider-connections-manager.tsx
@@ -0,0 +1,134 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { ProviderConnectionRow } from "./provider-connection-row";
+import { ProviderConnectionModal } from "./provider-connection-modal";
+import { DeleteProviderConnectionModal } from "./delete-provider-connection-modal";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import { cn } from "#/utils/utils";
+import {
+ settingsListContainerClassName,
+ settingsListDividerClassName,
+} from "#/utils/settings-list-classes";
+import { extensionModuleEmptyStateClassName } from "#/utils/extension-module-card-classes";
+import { I18nKey } from "#/i18n/declaration";
+
+interface ProviderConnectionsManagerProps {
+ connections: ProviderConnection[];
+ /** Number of LLM profiles linked to each connection id. */
+ linkedCountById: Record<string, number>;
+ isLoading: boolean;
+ loadError: Error | null;
+}
+
+/**
+ * Manages shared provider connections: a shared API key + optional base URL
+ * that LLM profiles reference by id. Rendered only for the local agent-server,
+ * which is the only backend exposing the endpoints.
+ */
+export function ProviderConnectionsManager({
+ connections,
+ linkedCountById,
+ isLoading,
+ loadError,
+}: ProviderConnectionsManagerProps) {
+ const { t } = useTranslation("openhands");
+ const [isCreating, setIsCreating] = useState(false);
+ const [connectionToEdit, setConnectionToEdit] =
+ useState<ProviderConnection | null>(null);
+ const [connectionToDelete, setConnectionToDelete] =
+ useState<ProviderConnection | null>(null);
+
+ const renderBody = () => {
+ if (isLoading) return null;
+
+ if (loadError) {
+ return (
+ <div
+ data-testid="provider-connections-load-error"
+ className={extensionModuleEmptyStateClassName}
+ >
+ <p className="text-sm text-red-400">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTIONS_LOAD_ERROR)}
+ </p>
+ </div>
+ );
+ }
+
+ if (connections.length === 0) {
+ return (
+ <div
+ data-testid="provider-connections-empty"
+ className={extensionModuleEmptyStateClassName}
+ >
+ <p className="text-sm text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTIONS_EMPTY)}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={cn(
+ settingsListContainerClassName,
+ settingsListDividerClassName,
+ )}
+ >
+ {connections.map((connection) => (
+ <ProviderConnectionRow
+ key={connection.id}
+ connection={connection}
+ linkedProfileCount={linkedCountById[connection.id] ?? 0}
+ onEdit={setConnectionToEdit}
+ onDelete={setConnectionToDelete}
+ />
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <>
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-base font-medium text-white">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTIONS_TITLE)}
+ </h2>
+ <p className="text-sm text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTIONS_SUBLINE)}
+ </p>
+ </div>
+ <BrandButton
+ testId="add-provider-connection"
+ type="button"
+ variant="secondary"
+ className="ml-auto"
+ onClick={() => setIsCreating(true)}
+ >
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTION_ADD)}
+ </BrandButton>
+ </div>
+
+ {renderBody()}
+ </div>
+
+ {isCreating && (
+ <ProviderConnectionModal
+ isCreate
+ onClose={() => setIsCreating(false)}
+ />
+ )}
+ <ProviderConnectionModal
+ isCreate={false}
+ connection={connectionToEdit}
+ onClose={() => setConnectionToEdit(null)}
+ />
+ <DeleteProviderConnectionModal
+ connection={connectionToDelete}
+ onClose={() => setConnectionToDelete(null)}
+ />
+ </>
+ );
+}
diff --git a/src/hooks/mutation/use-create-provider-connection.ts b/src/hooks/mutation/use-create-provider-connection.ts
new file mode 100644
index 0000000000..96fc4a1c49
--- /dev/null
+++ b/src/hooks/mutation/use-create-provider-connection.ts
@@ -0,0 +1,21 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import ProviderConnectionsService, {
+ type CreateProviderConnectionRequest,
+} from "#/api/provider-connections-service/provider-connections-service.api";
+import { PROVIDER_CONNECTIONS_QUERY_KEYS } from "#/hooks/query/query-keys";
+
+export function useCreateProviderConnection() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (request: CreateProviderConnectionRequest) =>
+ ProviderConnectionsService.create(request),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: PROVIDER_CONNECTIONS_QUERY_KEYS.all,
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts.
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/mutation/use-delete-provider-connection.ts b/src/hooks/mutation/use-delete-provider-connection.ts
new file mode 100644
index 0000000000..b265df43a6
--- /dev/null
+++ b/src/hooks/mutation/use-delete-provider-connection.ts
@@ -0,0 +1,25 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import ProviderConnectionsService from "#/api/provider-connections-service/provider-connections-service.api";
+import {
+ LLM_PROFILES_QUERY_KEYS,
+ PROVIDER_CONNECTIONS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+
+export function useDeleteProviderConnection() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (id: string) => ProviderConnectionsService.delete(id),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: PROVIDER_CONNECTIONS_QUERY_KEYS.all,
+ });
+ await queryClient.invalidateQueries({
+ queryKey: LLM_PROFILES_QUERY_KEYS.all,
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts (e.g. the 409
+ // returned when a profile still references the connection).
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/mutation/use-update-provider-connection.ts b/src/hooks/mutation/use-update-provider-connection.ts
new file mode 100644
index 0000000000..5b50842c59
--- /dev/null
+++ b/src/hooks/mutation/use-update-provider-connection.ts
@@ -0,0 +1,34 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import ProviderConnectionsService, {
+ type UpdateProviderConnectionRequest,
+} from "#/api/provider-connections-service/provider-connections-service.api";
+import {
+ LLM_PROFILES_QUERY_KEYS,
+ PROVIDER_CONNECTIONS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+
+interface UpdateProviderConnectionVariables {
+ id: string;
+ request: UpdateProviderConnectionRequest;
+}
+
+export function useUpdateProviderConnection() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ id, request }: UpdateProviderConnectionVariables) =>
+ ProviderConnectionsService.update(id, request),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: PROVIDER_CONNECTIONS_QUERY_KEYS.all,
+ });
+ // Linked profiles report the connection's key presence via `api_key_set`,
+ // so refresh the profile list too after a rotation or rename.
+ await queryClient.invalidateQueries({
+ queryKey: LLM_PROFILES_QUERY_KEYS.all,
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts.
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index 69e8bdb175..533eeed5a8 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -26,6 +26,10 @@ export const AGENT_PROFILES_QUERY_KEYS = {
all: ["agent-profiles"] as const,
} as const;
+export const PROVIDER_CONNECTIONS_QUERY_KEYS = {
+ all: ["provider-connections"] as const,
+} as const;
+
/** Fail fast when older backends lack the profile endpoint. */
export const AGENT_PROFILES_RETRY_OPTIONS = {
retry: false,
diff --git a/src/hooks/query/use-provider-connections.ts b/src/hooks/query/use-provider-connections.ts
new file mode 100644
index 0000000000..9fa3bad165
--- /dev/null
+++ b/src/hooks/query/use-provider-connections.ts
@@ -0,0 +1,27 @@
+import { useQuery } from "@tanstack/react-query";
+import ProviderConnectionsService from "#/api/provider-connections-service/provider-connections-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ CONFIG_CACHE_OPTIONS,
+ PROVIDER_CONNECTIONS_QUERY_KEYS,
+} from "./query-keys";
+
+export { PROVIDER_CONNECTIONS_QUERY_KEYS };
+
+/**
+ * Provider connections live only on the local agent-server. On cloud backends
+ * the query stays disabled and returns no data, so the connections UI hides
+ * itself rather than firing a request that would 404.
+ */
+export function useProviderConnections() {
+ const { backend } = useActiveBackend();
+ const isLocal = backend.kind === "local";
+
+ return useQuery({
+ queryKey: [...PROVIDER_CONNECTIONS_QUERY_KEYS.all, backend.id],
+ queryFn: ProviderConnectionsService.list,
+ ...CONFIG_CACHE_OPTIONS,
+ enabled: isLocal,
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index a698002aea..e6e6d77eb0 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -38928,5 +38928,328 @@
"ca": "Cada {{count}}s",
"tr": "Her {{count}}sn",
"uk": "Кожні {{count}} с"
+ },
+ "SETTINGS$PROFILES_UNGROUPED": {
+ "ar": "غير مرتبط",
+ "ca": "No enllaçat",
+ "de": "Nicht verknüpft",
+ "en": "Not linked",
+ "es": "Sin vincular",
+ "fr": "Non lié",
+ "it": "Non collegato",
+ "ja": "未リンク",
+ "ko-KR": "연결 안 됨",
+ "no": "Ikke koblet",
+ "pt": "Não vinculado",
+ "tr": "Bağlı değil",
+ "uk": "Не пов'язано",
+ "zh-CN": "未关联",
+ "zh-TW": "未關聯"
+ },
+ "SETTINGS$PROFILE_BROKEN_CONNECTION": {
+ "en": "Broken link",
+ "ja": "リンク切れ",
+ "zh-CN": "链接失效",
+ "zh-TW": "連結失效",
+ "ko-KR": "연결 끊김",
+ "no": "Brutt lenke",
+ "it": "Collegamento interrotto",
+ "pt": "Link quebrado",
+ "es": "Enlace roto",
+ "ar": "رابط معطل",
+ "fr": "Lien rompu",
+ "tr": "Bozuk bağlantı",
+ "de": "Defekter Link",
+ "uk": "Зламане посилання",
+ "ca": "Enllaç trencat"
+ },
+ "SETTINGS$PROFILE_BROKEN_CONNECTION_TOOLTIP": {
+ "en": "The linked provider connection was deleted. Edit this profile to re-link it.",
+ "ja": "リンクされたプロバイダ接続が削除されました。このプロファイルを編集して再リンクしてください。",
+ "zh-CN": "关联的提供商连接已被删除。请编辑此配置文件以重新链接。",
+ "zh-TW": "關聯的提供商連接已被刪除。請編輯此設定檔以重新連結。",
+ "ko-KR": "연결된 제공자 연결이 삭제되었습니다. 이 프로필을 편집하여 다시 연결하세요.",
+ "no": "Den tilknyttede leverandørforbindelsen ble slettet. Rediger denne profilen for å koble den til igjen.",
+ "it": "Il collegamento al provider è stato eliminato. Modifica questo profilo per ricollegerlo.",
+ "pt": "A conexão do provedor vinculada foi excluída. Edite este perfil para reconectá-lo.",
+ "es": "La conexión del proveedor vinculada fue eliminada. Edita este perfil para volver a vincularlo.",
+ "ar": "تم حذف اتصال المزود المرتبط. قم بتحرير هذا الملف الشخصي لإعادة ربطه.",
+ "fr": "La connexion fournisseur liée a été supprimée. Modifiez ce profil pour le lier à nouveau.",
+ "tr": "Bağlı sağlayıcı bağlantısı silindi. Yeniden bağlamak için bu profili düzenleyin.",
+ "de": "Die verknüpfte Anbieterverbindung wurde gelöscht. Bearbeite dieses Profil, um es erneut zu verknüpfen.",
+ "uk": "Пов'язане підключення до постачальника було видалено. Відредагуйте цей профіль, щоб знову зв'язати його.",
+ "ca": "La connexió del proveïdor vinculada va ser eliminada. Edita aquest perfil per tornar-lo a vincular."
+ },
+ "SETTINGS$PROVIDER_CONNECTIONS_EMPTY": {
+ "ar": "لا توجد اتصالات مزود بعد. أضف واحدًا لمشاركة مفتاح API عبر النماذج.",
+ "ca": "Encara no hi ha connexions de proveïdor. Afegeix-ne una per compartir una clau API entre models.",
+ "de": "Noch keine Anbieterverbindungen. Fügen Sie eine hinzu, um einen API-Schlüssel für mehrere Modelle zu nutzen.",
+ "en": "No provider connections yet. Add one to share an API key across models.",
+ "es": "Aún no hay conexiones de proveedor. Añade una para compartir una clave de API entre modelos.",
+ "fr": "Aucune connexion de fournisseur pour l'instant. Ajoutez-en une pour partager une clé API entre les modèles.",
+ "it": "Nessuna connessione provider. Aggiungine una per condividere una chiave API tra i modelli.",
+ "ja": "プロバイダー接続はまだありません。モデル間でAPIキーを共有するには追加してください。",
+ "ko-KR": "아직 공급자 연결이 없습니다. 모델 간에 API 키를 공유하려면 추가하세요.",
+ "no": "Ingen leverandørtilkoblinger ennå. Legg til én for å dele en API-nøkkel mellom modeller.",
+ "pt": "Nenhuma conexão de provedor ainda. Adicione uma para compartilhar uma chave de API entre modelos.",
+ "tr": "Henüz sağlayıcı bağlantısı yok. Modeller arasında bir API anahtarı paylaşmak için ekleyin.",
+ "uk": "Ще немає підключень постачальників. Додайте одне, щоб спільно використовувати ключ API для моделей.",
+ "zh-CN": "尚无提供商连接。添加一个以在模型之间共享 API 密钥。",
+ "zh-TW": "尚無提供者連線。新增一個以在模型之間共用 API 金鑰。"
+ },
+ "SETTINGS$PROVIDER_CONNECTIONS_LOAD_ERROR": {
+ "ar": "فشل تحميل اتصالات المزود.",
+ "ca": "No s'han pogut carregar les connexions de proveïdor.",
+ "de": "Anbieterverbindungen konnten nicht geladen werden.",
+ "en": "Failed to load provider connections.",
+ "es": "No se pudieron cargar las conexiones de proveedor.",
+ "fr": "Échec du chargement des connexions de fournisseur.",
+ "it": "Impossibile caricare le connessioni provider.",
+ "ja": "プロバイダー接続の読み込みに失敗しました。",
+ "ko-KR": "공급자 연결을 불러오지 못했습니다.",
+ "no": "Kunne ikke laste leverandørtilkoblinger.",
+ "pt": "Falha ao carregar as conexões de provedor.",
+ "tr": "Sağlayıcı bağlantıları yüklenemedi.",
+ "uk": "Не вдалося завантажити підключення постачальників.",
+ "zh-CN": "加载提供商连接失败。",
+ "zh-TW": "載入提供者連線失敗。"
+ },
+ "SETTINGS$PROVIDER_CONNECTIONS_SUBLINE": {
+ "ar": "شارك مفتاح API واحدًا عبر نماذج متعددة.",
+ "ca": "Comparteix una clau API entre diversos models.",
+ "de": "Teilen Sie einen API-Schlüssel für mehrere Modelle.",
+ "en": "Share one API key across multiple models.",
+ "es": "Comparte una clave de API entre varios modelos.",
+ "fr": "Partagez une clé API entre plusieurs modèles.",
+ "it": "Condividi una chiave API tra più modelli.",
+ "ja": "1つのAPIキーを複数のモデルで共有します。",
+ "ko-KR": "하나의 API 키를 여러 모델에서 공유합니다.",
+ "no": "Del én API-nøkkel på tvers av flere modeller.",
+ "pt": "Compartilhe uma chave de API entre vários modelos.",
+ "tr": "Bir API anahtarını birden fazla modelde paylaşın.",
+ "uk": "Спільно використовуйте один ключ API для кількох моделей.",
+ "zh-CN": "在多个模型之间共享一个 API 密钥。",
+ "zh-TW": "在多個模型之間共用一個 API 金鑰。"
+ },
+ "SETTINGS$PROVIDER_CONNECTIONS_TITLE": {
+ "ar": "اتصالات المزود",
+ "ca": "Connexions de proveïdor",
+ "de": "Anbieterverbindungen",
+ "en": "Provider connections",
+ "es": "Conexiones de proveedor",
+ "fr": "Connexions de fournisseur",
+ "it": "Connessioni provider",
+ "ja": "プロバイダー接続",
+ "ko-KR": "공급자 연결",
+ "no": "Leverandørtilkoblinger",
+ "pt": "Conexões de provedor",
+ "tr": "Sağlayıcı bağlantıları",
+ "uk": "Підключення постачальників",
+ "zh-CN": "提供商连接",
+ "zh-TW": "提供者連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_ADD": {
+ "ar": "إضافة اتصال",
+ "ca": "Afegeix una connexió",
+ "de": "Verbindung hinzufügen",
+ "en": "Add connection",
+ "es": "Añadir conexión",
+ "fr": "Ajouter une connexion",
+ "it": "Aggiungi connessione",
+ "ja": "接続を追加",
+ "ko-KR": "연결 추가",
+ "no": "Legg til tilkobling",
+ "pt": "Adicionar conexão",
+ "tr": "Bağlantı ekle",
+ "uk": "Додати підключення",
+ "zh-CN": "添加连接",
+ "zh-TW": "新增連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_ADD_TITLE": {
+ "ar": "إضافة اتصال المزود",
+ "ca": "Afegeix una connexió de proveïdor",
+ "de": "Anbieterverbindung hinzufügen",
+ "en": "Add provider connection",
+ "es": "Añadir conexión de proveedor",
+ "fr": "Ajouter une connexion de fournisseur",
+ "it": "Aggiungi connessione provider",
+ "ja": "プロバイダー接続を追加",
+ "ko-KR": "공급자 연결 추가",
+ "no": "Legg til leverandørtilkobling",
+ "pt": "Adicionar conexão de provedor",
+ "tr": "Sağlayıcı bağlantısı ekle",
+ "uk": "Додати підключення постачальника",
+ "zh-CN": "添加提供商连接",
+ "zh-TW": "新增提供者連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_CREATED": {
+ "ar": "تم إنشاء الاتصال \"{{name}}\"",
+ "ca": "S'ha creat la connexió \"{{name}}\"",
+ "de": "Verbindung \"{{name}}\" erstellt",
+ "en": "Connection \"{{name}}\" created",
+ "es": "Conexión \"{{name}}\" creada",
+ "fr": "Connexion « {{name}} » créée",
+ "it": "Connessione \"{{name}}\" creata",
+ "ja": "接続「{{name}}」を作成しました",
+ "ko-KR": "\"{{name}}\" 연결이 생성되었습니다",
+ "no": "Tilkoblingen «{{name}}» ble opprettet",
+ "pt": "Conexão \"{{name}}\" criada",
+ "tr": "\"{{name}}\" bağlantısı oluşturuldu",
+ "uk": "Підключення \"{{name}}\" створено",
+ "zh-CN": "已创建连接“{{name}}”",
+ "zh-TW": "已建立連線「{{name}}」"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_DELETED": {
+ "ar": "تم حذف الاتصال \"{{name}}\"",
+ "ca": "S'ha eliminat la connexió \"{{name}}\"",
+ "de": "Verbindung \"{{name}}\" gelöscht",
+ "en": "Connection \"{{name}}\" deleted",
+ "es": "Conexión \"{{name}}\" eliminada",
+ "fr": "Connexion « {{name}} » supprimée",
+ "it": "Connessione \"{{name}}\" eliminata",
+ "ja": "接続「{{name}}」を削除しました",
+ "ko-KR": "\"{{name}}\" 연결이 삭제되었습니다",
+ "no": "Tilkoblingen «{{name}}» ble slettet",
+ "pt": "Conexão \"{{name}}\" excluída",
+ "tr": "\"{{name}}\" bağlantısı silindi",
+ "uk": "Підключення \"{{name}}\" видалено",
+ "zh-CN": "已删除连接“{{name}}”",
+ "zh-TW": "已刪除連線「{{name}}」"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_DELETE_CONFIRMATION": {
+ "ar": "هل أنت متأكد أنك تريد حذف الاتصال \"{{name}}\"؟",
+ "ca": "Segur que voleu eliminar la connexió \"{{name}}\"?",
+ "de": "Möchten Sie die Verbindung \"{{name}}\" wirklich löschen?",
+ "en": "Are you sure you want to delete the connection \"{{name}}\"?",
+ "es": "¿Seguro que quieres eliminar la conexión \"{{name}}\"?",
+ "fr": "Voulez-vous vraiment supprimer la connexion « {{name}} » ?",
+ "it": "Sei sicuro di voler eliminare la connessione \"{{name}}\"?",
+ "ja": "接続「{{name}}」を削除してもよろしいですか?",
+ "ko-KR": "\"{{name}}\" 연결을 삭제하시겠습니까?",
+ "no": "Er du sikker på at du vil slette tilkoblingen «{{name}}»?",
+ "pt": "Tem certeza de que deseja excluir a conexão \"{{name}}\"?",
+ "tr": "\"{{name}}\" bağlantısını silmek istediğinizden emin misiniz?",
+ "uk": "Ви впевнені, що хочете видалити підключення \"{{name}}\"?",
+ "zh-CN": "确定要删除连接“{{name}}”吗?",
+ "zh-TW": "確定要刪除連線「{{name}}」嗎?"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_DELETE_TITLE": {
+ "ar": "حذف اتصال المزود",
+ "ca": "Elimina la connexió de proveïdor",
+ "de": "Anbieterverbindung löschen",
+ "en": "Delete provider connection",
+ "es": "Eliminar conexión de proveedor",
+ "fr": "Supprimer la connexion de fournisseur",
+ "it": "Elimina connessione provider",
+ "ja": "プロバイダー接続を削除",
+ "ko-KR": "공급자 연결 삭제",
+ "no": "Slett leverandørtilkobling",
+ "pt": "Excluir conexão de provedor",
+ "tr": "Sağlayıcı bağlantısını sil",
+ "uk": "Видалити підключення постачальника",
+ "zh-CN": "删除提供商连接",
+ "zh-TW": "刪除提供者連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_EDIT_TITLE": {
+ "ar": "تعديل اتصال المزود",
+ "ca": "Edita la connexió de proveïdor",
+ "de": "Anbieterverbindung bearbeiten",
+ "en": "Edit provider connection",
+ "es": "Editar conexión de proveedor",
+ "fr": "Modifier la connexion de fournisseur",
+ "it": "Modifica connessione provider",
+ "ja": "プロバイダー接続を編集",
+ "ko-KR": "공급자 연결 편집",
+ "no": "Rediger leverandørtilkobling",
+ "pt": "Editar conexão de provedor",
+ "tr": "Sağlayıcı bağlantısını düzenle",
+ "uk": "Редагувати підключення постачальника",
+ "zh-CN": "编辑提供商连接",
+ "zh-TW": "編輯提供者連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_MODEL_COUNT": {
+ "ar": "{{count}} نموذج",
+ "ca": "{{count}} model(s)",
+ "de": "{{count}} Modell(e)",
+ "en": "{{count}} model(s)",
+ "es": "{{count}} modelo(s)",
+ "fr": "{{count}} modèle(s)",
+ "it": "{{count}} modello/i",
+ "ja": "{{count}} モデル",
+ "ko-KR": "모델 {{count}}개",
+ "no": "{{count}} modell(er)",
+ "pt": "{{count}} modelo(s)",
+ "tr": "{{count}} model",
+ "uk": "{{count}} модель(ей)",
+ "zh-CN": "{{count}} 个模型",
+ "zh-TW": "{{count}} 個模型"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_PROVIDER": {
+ "ar": "المزود",
+ "ca": "Proveïdor",
+ "de": "Anbieter",
+ "en": "Provider",
+ "es": "Proveedor",
+ "fr": "Fournisseur",
+ "it": "Provider",
+ "ja": "プロバイダー",
+ "ko-KR": "공급자",
+ "no": "Leverandør",
+ "pt": "Provedor",
+ "tr": "Sağlayıcı",
+ "uk": "Постачальник",
+ "zh-CN": "提供商",
+ "zh-TW": "提供者"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_ROTATE_HINT": {
+ "ar": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي.",
+ "ca": "Deixeu-ho en blanc per conservar la clau actual.",
+ "de": "Leer lassen, um den aktuellen Schlüssel beizubehalten.",
+ "en": "Leave blank to keep the current key.",
+ "es": "Déjalo en blanco para mantener la clave actual.",
+ "fr": "Laissez vide pour conserver la clé actuelle.",
+ "it": "Lascia vuoto per mantenere la chiave attuale.",
+ "ja": "現在のキーを保持するには空白のままにします。",
+ "ko-KR": "현재 키를 유지하려면 비워 두세요.",
+ "no": "La stå tom for å beholde gjeldende nøkkel.",
+ "pt": "Deixe em branco para manter a chave atual.",
+ "tr": "Mevcut anahtarı korumak için boş bırakın.",
+ "uk": "Залиште порожнім, щоб зберегти поточний ключ.",
+ "zh-CN": "留空以保留当前密钥。",
+ "zh-TW": "留空以保留目前的金鑰。"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_SELECT_LABEL": {
+ "ar": "اتصال المزود",
+ "ca": "Connexió de proveïdor",
+ "de": "Anbieterverbindung",
+ "en": "Provider connection",
+ "es": "Conexión de proveedor",
+ "fr": "Connexion de fournisseur",
+ "it": "Connessione provider",
+ "ja": "プロバイダー接続",
+ "ko-KR": "공급자 연결",
+ "no": "Leverandørtilkobling",
+ "pt": "Conexão de provedor",
+ "tr": "Sağlayıcı bağlantısı",
+ "uk": "Підключення постачальника",
+ "zh-CN": "提供商连接",
+ "zh-TW": "提供者連線"
+ },
+ "SETTINGS$PROVIDER_CONNECTION_UPDATED": {
+ "ar": "تم تحديث الاتصال \"{{name}}\"",
+ "ca": "S'ha actualitzat la connexió \"{{name}}\"",
+ "de": "Verbindung \"{{name}}\" aktualisiert",
+ "en": "Connection \"{{name}}\" updated",
+ "es": "Conexión \"{{name}}\" actualizada",
+ "fr": "Connexion « {{name}} » mise à jour",
+ "it": "Connessione \"{{name}}\" aggiornata",
+ "ja": "接続「{{name}}」を更新しました",
+ "ko-KR": "\"{{name}}\" 연결이 업데이트되었습니다",
+ "no": "Tilkoblingen «{{name}}» ble oppdatert",
+ "pt": "Conexão \"{{name}}\" atualizada",
+ "tr": "\"{{name}}\" bağlantısı güncellendi",
+ "uk": "Підключення \"{{name}}\" оновлено",
+ "zh-CN": "已更新连接“{{name}}”",
+ "zh-TW": "已更新連線「{{name}}」"
}
}
diff --git a/src/routes/llm-settings.tsx b/src/routes/llm-settings.tsx
index c8216ee594..182400dfae 100644
--- a/src/routes/llm-settings.tsx
+++ b/src/routes/llm-settings.tsx
@@ -33,15 +33,23 @@ import {
resolveLlmAuthType,
} from "#/constants/llm-subscription";
import { useOpenAISubscriptionModels } from "#/hooks/query/use-llm-subscription-models";
+import { useProviderConnections } from "#/hooks/query/use-provider-connections";
import {
FREE_OPENHANDS_MODEL_NOTE,
isFreeOpenHandsModel,
} from "#/utils/format-model-name";
+/** Form-values key for the shared provider connection a profile links to. */
+export const LLM_PROVIDER_CONNECTION_KEY = "llm.provider_connection_id";
+
+/** Dropdown sentinel for "no provider connection" (an inline key is used). */
+const NO_PROVIDER_CONNECTION = "__none__";
+
const LLM_EXCLUDED_KEYS = new Set([
"llm.model",
"llm.api_key",
"llm.base_url",
+ LLM_PROVIDER_CONNECTION_KEY,
LLM_AUTH_TYPE_KEY,
LLM_SUBSCRIPTION_VENDOR_KEY,
]);
@@ -128,6 +136,7 @@ export function LlmSettingsScreen({
hideSaveButton,
suppressSuccessToast,
onSaveControlChange,
+ showProviderConnection,
}: {
scope?: SettingsScope;
/** Optional hook fired after a successful save (e.g. advance an onboarding step). */
@@ -142,9 +151,21 @@ export function LlmSettingsScreen({
suppressSuccessToast?: boolean;
/** Forwarded to {@link SdkSectionPage}. */
onSaveControlChange?: (control: SdkSectionSaveControl) => void;
+ /**
+ * When true (the local profile editor), show a "Provider connection" selector
+ * that links this profile to a shared connection. Only rendered when at least
+ * one connection exists, so the form is unchanged until the user creates one.
+ */
+ showProviderConnection?: boolean;
}) {
const { t } = useTranslation("openhands");
+ const { data: providerConnections } = useProviderConnections();
+ const connectionOptions = React.useMemo(
+ () => (showProviderConnection ? (providerConnections ?? []) : []),
+ [showProviderConnection, providerConnections],
+ );
+
const { data: settings } = useSettings(scope);
const { data: schema } = useAgentSettingsSchema(
settings?.agent_settings_schema,
@@ -229,6 +250,60 @@ export function LlmSettingsScreen({
? apiKeyValue.length > 0
: Boolean(settings?.llm_api_key_set);
+ // A profile linked to a provider connection reads its api_key / base_url
+ // from that connection, so the inline key + base URL inputs are hidden.
+ const connectionValue =
+ typeof values[LLM_PROVIDER_CONNECTION_KEY] === "string"
+ ? values[LLM_PROVIDER_CONNECTION_KEY]
+ : "";
+ const isLinkedToConnection = Boolean(connectionValue);
+ // Show the selector whenever connections can be linked here. Include the
+ // linked case so a profile pointing at an orphaned connection (its only
+ // connection deleted, or the list still loading) still exposes a control
+ // to unlink — otherwise the API key / base URL inputs stay hidden with no
+ // way to recover.
+ const showConnectionSelector =
+ showProviderConnection &&
+ !isSubscriptionAuth &&
+ (isLinkedToConnection || connectionOptions.length > 0);
+ // Surface an orphaned link (a selected id absent from the fetched list)
+ // as its own option so the dropdown reflects it and can be cleared.
+ const isOrphanedLink =
+ isLinkedToConnection &&
+ !connectionOptions.some((c) => c.id === connectionValue);
+
+ const renderConnectionSelector = () => (
+ <SettingsDropdownInput
+ testId="llm-provider-connection-input"
+ name={LLM_PROVIDER_CONNECTION_KEY}
+ label={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_SELECT_LABEL)}
+ items={[
+ {
+ key: NO_PROVIDER_CONNECTION,
+ label: t(I18nKey.SETTINGS$MCP_AUTH_MODE_NONE),
+ },
+ ...connectionOptions.map((connection) => ({
+ key: connection.id,
+ label: connection.display_name,
+ })),
+ ...(isOrphanedLink
+ ? [{ key: connectionValue, label: connectionValue }]
+ : []),
+ ]}
+ selectedKey={connectionValue || NO_PROVIDER_CONNECTION}
+ isClearable={false}
+ isDisabled={isDisabled}
+ onSelectionChange={(selectedKey) => {
+ const next =
+ typeof selectedKey === "string" &&
+ selectedKey !== NO_PROVIDER_CONNECTION
+ ? selectedKey
+ : "";
+ onChange(LLM_PROVIDER_CONNECTION_KEY, next);
+ }}
+ />
+ );
+
const renderApiKeyInput = (testId: string, helpTestId: string) => (
<>
<SettingsInput
@@ -369,16 +444,20 @@ export function LlmSettingsScreen({
isDisabled={isDisabled}
/>
- {showOpenHandsApiKeyHelp ? (
+ {showConnectionSelector ? renderConnectionSelector() : null}
+
+ {showOpenHandsApiKeyHelp && !isLinkedToConnection ? (
<OpenHandsApiKeyHelp testId="openhands-api-key-help" />
) : null}
- {renderApiKeyInput(
- // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
- "llm-api-key-input",
- // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
- "llm-api-key-help-anchor",
- )}
+ {isLinkedToConnection
+ ? null
+ : renderApiKeyInput(
+ // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
+ "llm-api-key-input",
+ // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
+ "llm-api-key-help-anchor",
+ )}
</>
)}
</div>
@@ -404,7 +483,7 @@ export function LlmSettingsScreen({
isDisabled={isDisabled}
/>
- {showOpenHandsApiKeyHelp ? (
+ {showOpenHandsApiKeyHelp && !isLinkedToConnection ? (
<>
{isFreeOpenHandsModel(modelValue) ? (
<OpenHandsFreeModelsNote />
@@ -413,24 +492,30 @@ export function LlmSettingsScreen({
</>
) : null}
- <SettingsInput
- testId="base-url-input"
- label={t(I18nKey.SETTINGS$BASE_URL)}
- type="text"
- className="w-full"
- value={baseUrlValue}
- // eslint-disable-next-line i18next/no-literal-string -- example value, not translatable
- placeholder="https://api.openai.com"
- onChange={(value) => onChange("llm.base_url", value)}
- isDisabled={isDisabled}
- />
-
- {renderApiKeyInput(
- // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
- "llm-api-key-input",
- // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
- "llm-api-key-help-anchor-advanced",
+ {showConnectionSelector ? renderConnectionSelector() : null}
+
+ {isLinkedToConnection ? null : (
+ <SettingsInput
+ testId="base-url-input"
+ label={t(I18nKey.SETTINGS$BASE_URL)}
+ type="text"
+ className="w-full"
+ value={baseUrlValue}
+ // eslint-disable-next-line i18next/no-literal-string -- example value, not translatable
+ placeholder="https://api.openai.com"
+ onChange={(value) => onChange("llm.base_url", value)}
+ isDisabled={isDisabled}
+ />
)}
+
+ {isLinkedToConnection
+ ? null
+ : renderApiKeyInput(
+ // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
+ "llm-api-key-input",
+ // eslint-disable-next-line i18next/no-literal-string -- DOM id, not user-facing
+ "llm-api-key-help-anchor-advanced",
+ )}
</>
)}
</div>
@@ -439,6 +524,8 @@ export function LlmSettingsScreen({
);
},
[
+ connectionOptions,
+ showProviderConnection,
defaultModel,
embedded,
isWaitingForSubscriptionModels,