Skip to content

🙌 OpenHands: AI-Driven Development

feat(settings): per-connection bulk-add LLM profiles (#17723)

Juan Pedro Michelini Jorge3cc1dac2cbe6
diff --git a/AGENTS.md b/AGENTS.md
index 96babeb611..65fb4d44c7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -3,6 +3,20 @@
## General
- This repository is the OpenHands Agent Canvas React/TypeScript frontend.
+
+## i18n workflow
+- After editing `src/i18n/translation.json`, run `npm run make-i18n` to
+ regenerate `src/i18n/declaration.ts` (gitignored, auto-generated) and
+ `scripts/check-translation-completeness.cjs` to confirm full locale coverage.
+- Removing an i18n key: delete the whole locale block from translation.json,
+ then `make-i18n`, then remove any test-mock entries (tests inline a
+ `translations` map in the `useTranslation` vi.mock).
+
+## Commit messages
+- The persistent shell can garble long multi-line `commit -m` bodies (echo
+ loop corrupts the stored message). Use `git commit -F <file>` with a
+ written temp file instead of `-m` for any non-trivial message.
+
- Primary verification commands are `npm run lint`, `npm test`, `npm run build`, and `npm run build:lib`.
- Direct dependencies and dev dependencies are exact-pinned. Use the committed `package-lock.json` with `npm ci`, and update `package.json` and `package-lock.json` together through npm.
- Public skills come from `@openhands/extensions`; project-specific contributor guidance lives under `.agents/skills/`.
diff --git a/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx b/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx
index 984d64a446..49dbe9b101 100644
--- a/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx
+++ b/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx
@@ -5,7 +5,14 @@ import React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AddModelsModal } from "#/components/features/settings/llm-profiles/add-models-modal";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
import ConfigService from "#/api/config-service/config-service.api";
+import type {
+ LLMModel,
+ LLMModelPage,
+ LLMProvider,
+ ProviderPage,
+} from "#/api/config-service/config-service.types";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
vi.mock("react-i18next", () => ({
@@ -15,11 +22,13 @@ vi.mock("react-i18next", () => ({
SETTINGS$ADD_MODELS_TITLE: "Add models as profiles",
SETTINGS$ADD_MODELS_PROVIDER_LABEL: "Provider",
SETTINGS$ADD_MODELS_PROVIDER_PLACEHOLDER: "Select a provider",
- SETTINGS$ADD_MODELS_VERIFIED_ONLY: "Verified models only",
+ SETTINGS$ADD_MODELS_CONNECTION_LABEL: "Provider connection",
+ SETTINGS$ADD_MODELS_NO_CONNECTION: "No connection (keyless)",
+ SETTINGS$ADD_MODELS_CONNECTION_BOUND: `Linked to ${params?.provider ?? "?"}`,
+ SETTINGS$ADD_MODELS_KEYLESS_NOTE:
+ "No connection — profiles will need a key added later",
SETTINGS$ADD_MODELS_SELECT_ALL: "Select all",
SETTINGS$ADD_MODELS_EMPTY: "No models found for this provider.",
- COMMON$NO_RESULTS: "No results found",
- SETTINGS$ADD_MODELS_NAME_TAKEN: "Name already exists",
SETTINGS$ADD_N_PROFILES: `Add ${params?.count ?? "?"} profiles`,
SETTINGS$MODELS_ADDED: `Added ${params?.count ?? "?"} profiles`,
SETTINGS$MODELS_ADDED_PARTIAL: `Added ${params?.added ?? "?"} profiles; ${params?.failed ?? "?"} failed`,
@@ -53,17 +62,6 @@ vi.mock("#/utils/custom-toast-handlers", () => ({
displayErrorToast: vi.fn(),
}));
-const PROVIDERS = {
- items: [
- { name: "openhands", verified: true },
- { name: "openai", verified: true },
- // The provider feed carries entries that are not providers at all; they
- // arrive unverified and belong under the "Others" divider.
- { name: "1024-x-1024", verified: false },
- ],
- next_page_id: null,
-};
-
/**
* An error shaped like the SDK's HttpError, which the modal narrows on.
* `HttpError.response` carries the parsed error body, so a server that answers
@@ -78,41 +76,67 @@ const httpError = (status: number, detail?: string) => {
});
};
-const MODELS = {
+// The local reconstruction path sets `free`/`default` to false for every item;
+// the fixtures mirror that so they satisfy LLMModel without drift.
+const model = (
+ provider: string,
+ name: string,
+ verified: boolean,
+): LLMModel => ({ provider, name, verified, free: false, default: false });
+
+const OPENAI_MODELS: LLMModelPage = {
items: [
- {
- provider: "openhands",
- name: "trinity-large-thinking",
- verified: true,
- free: false,
- default: false,
- },
- {
- provider: "openhands",
- name: "deepseek-v4-flash",
- verified: true,
- free: false,
- default: false,
- },
- {
- provider: "openhands",
- name: "unverified-model",
- verified: false,
- free: false,
- default: false,
- },
+ model("openai", "gpt-4o", true),
+ model("openai", "gpt-4o-mini", true),
+ model("openai", "unverified-model", false),
],
next_page_id: null,
};
+// The provider combobox is driven by `searchProviders`. The modal only needs
+// the openai provider to appear so it can be picked / preselected.
+const PROVIDERS: ProviderPage = {
+ items: [{ name: "openai", verified: true } satisfies LLMProvider],
+ next_page_id: null,
+};
+
+function makeConnection(
+ overrides: Partial<ProviderConnection> = {},
+): ProviderConnection {
+ return {
+ id: "conn-openai",
+ display_name: "Shared OpenAI",
+ provider: "openai",
+ base_url: null,
+ created_at: 1,
+ updated_at: 2,
+ api_key_set: true,
+ ...overrides,
+ };
+}
+
+const OPENAI_CONNECTION = makeConnection();
+
describe("AddModelsModal", () => {
let queryClient: QueryClient;
- const renderModal = (existingNames: string[] = [], onClose = vi.fn()) => {
+ const renderModal = (
+ connection: ProviderConnection | null = OPENAI_CONNECTION,
+ existingNames: string[] = [],
+ onClose = vi.fn(),
+ ) => {
+ // When a connection is given, preselect it (the "..." entry point). When
+ // null, render chooser mode with no preselect (the top-button entry
+ // point) and an empty connection pool — the modal then just shows the
+ // combobox prompt.
+ const connections = connection ? [connection] : [];
+ const initialConnectionId = connection?.id ?? null;
const view = render(
<QueryClientProvider client={queryClient}>
<AddModelsModal
isOpen
+ connections={connections}
+ initialConnectionId={initialConnectionId}
existingNames={existingNames}
onClose={onClose}
/>
@@ -125,6 +149,8 @@ describe("AddModelsModal", () => {
<QueryClientProvider client={queryClient}>
<AddModelsModal
isOpen={isOpen}
+ connections={connections}
+ initialConnectionId={initialConnectionId}
existingNames={existingNames}
onClose={onClose}
/>
@@ -134,15 +160,20 @@ describe("AddModelsModal", () => {
};
const showUnverified = async () => {
- await userEvent.click(screen.getByTestId("add-models-verified-only"));
- await screen.findByTestId("add-models-row-openhands/unverified-model");
+ // No verified filter anymore — unverified models are always visible, so
+ // this just waits for the unverified row to render. Kept as a helper so
+ // call sites read clearly.
+ await screen.findByTestId("add-models-row-openai/unverified-model");
};
- const pickProvider = async () => {
- const select = await screen.findByTestId("add-models-provider");
- // Options populate async via the providers query; wait before selecting.
- await screen.findByRole("option", { name: "openhands" });
- await userEvent.selectOptions(select, "openhands");
+ // The provider combobox options arrive asynchronously (searchProviders is a
+ // query), so wait for the openai option before interacting with it.
+ const chooseOpenAI = async () => {
+ await screen.findByText("OpenAI");
+ await userEvent.selectOptions(
+ screen.getByTestId("add-models-provider"),
+ "openai",
+ );
};
beforeEach(() => {
@@ -150,71 +181,63 @@ describe("AddModelsModal", () => {
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
+ // `searchModels` is provider-scoped; the default fixture covers openai.
+ vi.mocked(ConfigService.searchModels).mockResolvedValue(OPENAI_MODELS);
+ // `searchProviders` feeds the provider combobox.
vi.mocked(ConfigService.searchProviders).mockResolvedValue(PROVIDERS);
- vi.mocked(ConfigService.searchModels).mockResolvedValue(MODELS);
vi.mocked(ProfilesService.saveProfile).mockResolvedValue({
name: "x",
message: "ok",
});
});
- it("lists verified models with derived names after picking a provider", async () => {
- renderModal();
- await pickProvider();
-
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
+ it("renders only the provider combobox in chooser mode (no provider picked)", () => {
+ renderModal(null);
+ expect(screen.getByTestId("add-models-modal")).toBeInTheDocument();
+ // The provider box is the prompt — no model list, no empty-state, no
+ // spinner, and no connection box (there is no provider to match yet).
+ expect(screen.getByTestId("add-models-provider")).toBeInTheDocument();
+ expect(screen.queryByTestId("add-models-loading")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("add-models-empty")).not.toBeInTheDocument();
expect(
- screen.getByTestId("add-models-row-openhands/deepseek-v4-flash"),
- ).toBeInTheDocument();
- // unverified filtered out by default
- expect(
- screen.queryByTestId("add-models-row-openhands/unverified-model"),
+ screen.queryByTestId("add-models-connection-field"),
).not.toBeInTheDocument();
- // derived name pre-fills the input
- expect(
- screen.getByTestId("add-models-name-openhands/deepseek-v4-flash"),
- ).toHaveValue("deepseek-v4-flash");
});
- it("shows unverified models when the filter is toggled off", async () => {
+ it("shows the provider preselected to the launched connection's provider", async () => {
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
-
- await userEvent.click(screen.getByTestId("add-models-verified-only"));
-
- await screen.findByTestId("add-models-row-openhands/unverified-model");
+ // Preselect mode: the provider box opens on the connection's provider,
+ // the connection is bound, and the models load without the user choosing.
+ await screen.findByText("OpenAI");
+ const providerBox = screen.getByTestId(
+ "add-models-provider",
+ ) as HTMLSelectElement;
+ expect(providerBox.value).toBe("openai");
+ const connectionBox = (await screen.findByTestId(
+ "add-models-connection",
+ )) as HTMLSelectElement;
+ expect(connectionBox.value).toBe("conn-openai");
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
});
- it("distinguishes a provider with no models from a filter hiding them all", async () => {
- // Saying "no models found for this provider" when the provider has models
- // and the filter is hiding them sends the user looking for the wrong thing.
- vi.mocked(ConfigService.searchModels).mockResolvedValue({
- items: [
- {
- provider: "openhands",
- name: "unverified-only",
- verified: false,
- free: false,
- default: false,
- },
- ],
- next_page_id: null,
- });
+ it("lists all models for the connection's provider with short (unprefixed) names", async () => {
renderModal();
- await pickProvider();
-
- await screen.findByTestId("add-models-empty");
- expect(screen.getByTestId("add-models-empty")).toHaveTextContent(
- "No results found",
- );
-
- await userEvent.click(screen.getByTestId("add-models-verified-only"));
- await screen.findByTestId("add-models-row-openhands/unverified-only");
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ expect(
+ screen.getByTestId("add-models-row-openai/gpt-4o-mini"),
+ ).toBeInTheDocument();
+ // No verified filter: unverified models are shown too.
+ expect(
+ screen.getByTestId("add-models-row-openai/unverified-model"),
+ ).toBeInTheDocument();
+ // The provider prefix is stripped from the displayed label — it's implied
+ // by the selected connection.
+ expect(screen.getByText("gpt-4o-mini")).toBeInTheDocument();
+ expect(screen.queryByText("openai/gpt-4o-mini")).not.toBeInTheDocument();
+ // No per-row name editor.
+ expect(
+ screen.queryByTestId("add-models-name-openai/gpt-4o-mini"),
+ ).not.toBeInTheDocument();
});
it("says the provider is empty when it really has no models", async () => {
@@ -223,41 +246,59 @@ describe("AddModelsModal", () => {
next_page_id: null,
});
renderModal();
- await pickProvider();
-
await screen.findByTestId("add-models-empty");
expect(screen.getByTestId("add-models-empty")).toHaveTextContent(
"No models found for this provider.",
);
});
- it("flags names that collide with existing profiles and excludes them", async () => {
- renderModal(["deepseek-v4-flash"]);
- await pickProvider();
- await screen.findByTestId("add-models-row-openhands/deepseek-v4-flash");
-
+ it("hides models whose name matches an existing profile", async () => {
+ renderModal(OPENAI_CONNECTION, ["gpt-4o-mini"]);
+ // The non-hidden model renders first; await it so the query has settled.
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // The already-added model is not rendered at all — no row, no checkbox,
+ // no conflict badge. Showing it disabled just clutters the list.
expect(
- screen.getByTestId("add-models-conflict-openhands/deepseek-v4-flash"),
- ).toBeInTheDocument();
- expect(
- screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),
- ).toBeDisabled();
- // select-all reaches only the non-colliding row
- await userEvent.click(screen.getByTestId("add-models-select-all"));
+ screen.queryByTestId("add-models-row-openai/gpt-4o-mini"),
+ ).not.toBeInTheDocument();
+ // Preselect mode auto-selects the visible rows (gpt-4o + unverified-model);
+ // the hidden gpt-4o-mini is not counted.
expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
- "Add 1 profiles",
+ "Add 2 profiles",
);
});
- it("selects nothing until the user chooses", async () => {
+ it("dedupes a model the catalog lists twice (verified + raw)", async () => {
+ // A provider's catalog can surface the same model twice — once in the
+ // verified set and once in the raw list — when the two disagree on
+ // prefixing. Both must collapse to a single row instead of flagging each
+ // other as a name conflict on a fresh account with no profiles.
+ vi.mocked(ConfigService.searchModels).mockResolvedValue({
+ items: [
+ model("openai", "gpt-4o", true),
+ model("openai", "gpt-4o", false),
+ model("openai", "gpt-4o-mini", true),
+ ],
+ next_page_id: null,
+ });
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ expect(screen.getAllByTestId("add-models-row-openai/gpt-4o")).toHaveLength(
+ 1,
);
+ expect(
+ screen.queryByTestId("add-models-conflict-openai/gpt-4o"),
+ ).not.toBeInTheDocument();
+ });
+ it("selects nothing until the user chooses (chooser mode)", async () => {
+ // Chooser entry point: no preselect, so the user picks a provider. Rows
+ // are not auto-selected — choosing is the point of the modal.
+ renderModal(null);
+ await chooseOpenAI();
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
expect(
- screen.getByTestId("add-models-check-openhands/trinity-large-thinking"),
+ screen.getByTestId("add-models-check-openai/gpt-4o"),
).not.toBeChecked();
expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
"Add 0 profiles",
@@ -265,67 +306,159 @@ describe("AddModelsModal", () => {
expect(screen.getByTestId("add-models-submit")).toBeDisabled();
});
- it("groups unverified providers under a separate divider", async () => {
+ it("auto-selects the loaded rows in preselect mode (connection row entry point)", async () => {
+ // The "..." entry point is an explicit intent to bulk-add from that
+ // connection, so its models load already selected.
renderModal();
- const select = await screen.findByTestId("add-models-provider");
- // options arrive with the providers query, not on first paint
- await screen.findByRole("option", { name: "1024-x-1024" });
-
- const groups = Array.from(select.querySelectorAll("optgroup"));
- expect(groups).toHaveLength(2);
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ expect(screen.getByTestId("add-models-check-openai/gpt-4o")).toBeChecked();
expect(
- Array.from(groups[0].querySelectorAll("option")).map((o) => o.value),
- ).toEqual(["openhands", "openai"]);
- expect(
- Array.from(groups[1].querySelectorAll("option")).map((o) => o.value),
- ).toEqual(["1024-x-1024"]);
+ screen.getByTestId("add-models-check-openai/gpt-4o-mini"),
+ ).toBeChecked();
+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
+ "Add 3 profiles",
+ );
});
- it("creates one profile per selected model, keyless", async () => {
+ it("creates profiles linked to the connection", async () => {
const onClose = vi.fn();
- renderModal([], onClose);
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
+ renderModal(OPENAI_CONNECTION, [], onClose);
+ // Preselect mode auto-selects the rows; submit creates one profile per
+ // selected row, each linked to the bound connection.
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ await userEvent.click(screen.getByTestId("add-models-submit"));
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(3);
+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("gpt-4o", {
+ llm: {
+ model: "openai/gpt-4o",
+ provider_connection_id: "conn-openai",
+ },
+ include_secrets: false,
+ });
+ });
- // pick one; only that one is created
- await userEvent.click(
- screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),
+ it("creates keyless profiles when the provider has no matching connection", async () => {
+ // Chooser entry point with no connections at all: the user picks a
+ // provider from the catalog and bulk-adds. With no connection to bind,
+ // profiles are created keyless (provider_connection_id: null) — the
+ // pre-connection bulk-add behavior the linked issue requires.
+ const onClose = vi.fn();
+ renderModal(null, [], onClose);
+ await chooseOpenAI();
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // No connection box: nothing matches the chosen provider.
+ expect(
+ screen.queryByTestId("add-models-connection-field"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTestId("add-models-keyless-note")).toHaveTextContent(
+ "No connection — profiles will need a key added later",
);
+ await userEvent.click(screen.getByTestId("add-models-select-all"));
await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() => expect(onClose).toHaveBeenCalled());
- expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(1);
- expect(ProfilesService.saveProfile).toHaveBeenCalledWith(
- "deepseek-v4-flash",
- {
- llm: { model: "openhands/deepseek-v4-flash" },
- include_secrets: false,
+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("gpt-4o", {
+ llm: {
+ model: "openai/gpt-4o",
+ provider_connection_id: null,
},
+ include_secrets: false,
+ });
+ });
+
+ it("binds a matching connection by default when the user picks a provider in chooser mode", async () => {
+ // Picking a provider that has a connection binds it automatically, so
+ // created profiles are usable out of the box. The user can opt out via
+ // the connection box's "No connection" option.
+ const onClose = vi.fn();
+ // Chooser entry point (no preselect) but a connection exists in the pool.
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AddModelsModal
+ isOpen
+ connections={[OPENAI_CONNECTION]}
+ initialConnectionId={null}
+ existingNames={[]}
+ onClose={onClose}
+ />
+ </QueryClientProvider>,
);
+ await chooseOpenAI();
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // The connection box appears and defaults to the matching connection.
+ const connectionBox = screen.getByTestId(
+ "add-models-connection",
+ ) as HTMLSelectElement;
+ expect(connectionBox.value).toBe("conn-openai");
+ expect(
+ screen.queryByTestId("add-models-keyless-note"),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("add-models-select-all"));
+ await userEvent.click(screen.getByTestId("add-models-submit"));
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("gpt-4o", {
+ llm: {
+ model: "openai/gpt-4o",
+ provider_connection_id: "conn-openai",
+ },
+ include_secrets: false,
+ });
});
- it("keeps the modal open and marks the row on per-model failure", async () => {
+ it("lets the user opt out of a matching connection to create keyless profiles", async () => {
const onClose = vi.fn();
- vi.mocked(ProfilesService.saveProfile)
- .mockResolvedValueOnce({ name: "a", message: "ok" })
- .mockRejectedValueOnce(new Error("boom"));
- renderModal([], onClose);
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AddModelsModal
+ isOpen
+ connections={[OPENAI_CONNECTION]}
+ initialConnectionId={null}
+ existingNames={[]}
+ onClose={onClose}
+ />
+ </QueryClientProvider>,
+ );
+ await chooseOpenAI();
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // Explicitly choose "No connection (keyless)".
+ await userEvent.selectOptions(
+ screen.getByTestId("add-models-connection"),
+ "",
);
+ expect(screen.getByTestId("add-models-keyless-note")).toBeInTheDocument();
await userEvent.click(screen.getByTestId("add-models-select-all"));
await userEvent.click(screen.getByTestId("add-models-submit"));
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("gpt-4o", {
+ llm: {
+ model: "openai/gpt-4o",
+ provider_connection_id: null,
+ },
+ include_secrets: false,
+ });
+ });
+
+ it("keeps the modal open and marks the row on per-model failure", async () => {
+ const onClose = vi.fn();
+ vi.mocked(ProfilesService.saveProfile)
+ .mockResolvedValueOnce({ name: "a", message: "ok" })
+ .mockRejectedValueOnce(new Error("boom"))
+ .mockResolvedValue({ name: "c", message: "ok" });
+ renderModal(OPENAI_CONNECTION, [], onClose);
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // Preselect mode auto-selects the rows; submit drives all three.
+ await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() =>
expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),
);
expect(onClose).not.toHaveBeenCalled();
const rows = screen.getAllByText(/^(Saved|Failed)$/);
- expect(rows).toHaveLength(2);
+ expect(rows).toHaveLength(3);
});
it("stops the run and reports the server's reason when it refuses with 409", async () => {
@@ -333,14 +466,10 @@ describe("AddModelsModal", () => {
vi.mocked(ProfilesService.saveProfile).mockRejectedValue(
httpError(409, "Profile limit reached (10). Delete a profile first."),
);
- renderModal([], onClose);
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
+ renderModal(OPENAI_CONNECTION, [], onClose);
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await showUnverified();
- await userEvent.click(screen.getByTestId("add-models-select-all"));
await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() =>
@@ -352,52 +481,36 @@ describe("AddModelsModal", () => {
"Profile limit reached (10). Delete a profile first.",
);
expect(onClose).not.toHaveBeenCalled();
- // only the attempted rows report a status; the unattempted row is not
- // left spinning on a "saving" it never got
expect(screen.getAllByText(/^(Saved|Failed)$/)).toHaveLength(2);
expect(screen.queryByTestId("loading-spinner")).not.toBeInTheDocument();
});
it("carries on past a single 409 so one raced name collision cannot halt the run", async () => {
- // A name free at load can be taken by another session before submit. That
- // 409 is about one row, not the account's profile ceiling.
vi.mocked(ProfilesService.saveProfile)
.mockRejectedValueOnce(httpError(409, "Profile 'x' already exists."))
- .mockResolvedValueOnce({ name: "b", message: "ok" });
+ .mockResolvedValue({ name: "b", message: "ok" });
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
-
- await userEvent.click(screen.getByTestId("add-models-select-all"));
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() =>
expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),
);
- expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(2);
- expect(screen.getByText("Saved")).toBeInTheDocument();
+ expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(3);
+ expect(screen.getAllByText("Saved")).toHaveLength(2);
expect(displayErrorToast).toHaveBeenCalledWith(
- "Added 1 profiles; 1 failed",
+ "Added 2 profiles; 1 failed",
);
});
it("reports the blocking 409's own reason, not the earlier one's", async () => {
- // A raced duplicate stops nothing on its own. When the next 409 is the one
- // that halts the run and explains nothing, quoting the duplicate's sentence
- // blames the wrong thing entirely.
vi.mocked(ProfilesService.saveProfile)
.mockRejectedValueOnce(httpError(409, "Profile 'x' already exists."))
.mockRejectedValueOnce(httpError(409));
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await showUnverified();
- await userEvent.click(screen.getByTestId("add-models-select-all"));
await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() =>
@@ -412,17 +525,11 @@ describe("AddModelsModal", () => {
});
it("names the refusal generically when the 409 carries no detail", async () => {
- // A body the client cannot quote must not fall through to a count that
- // omits the rows the server never let it attempt.
vi.mocked(ProfilesService.saveProfile).mockRejectedValue(httpError(409));
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await showUnverified();
- await userEvent.click(screen.getByTestId("add-models-select-all"));
await userEvent.click(screen.getByTestId("add-models-submit"));
await waitFor(() =>
@@ -433,95 +540,40 @@ describe("AddModelsModal", () => {
);
});
- it("keeps selections and edited names across a filter toggle", async () => {
+ it("keeps selections once the list has settled", async () => {
+ // Preselect mode auto-selects the rows; a selection must survive the
+ // list settling (the unverified row arriving after the verified ones).
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
-
- const name = screen.getByTestId(
- "add-models-name-openhands/deepseek-v4-flash",
- );
- await userEvent.clear(name);
- await userEvent.type(name, "my-flash");
- await userEvent.click(
- screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),
- );
-
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await showUnverified();
expect(
- screen.getByTestId("add-models-name-openhands/deepseek-v4-flash"),
- ).toHaveValue("my-flash");
- expect(
- screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),
+ screen.getByTestId("add-models-check-openai/gpt-4o-mini"),
).toBeChecked();
-
- // and back again
- await userEvent.click(screen.getByTestId("add-models-verified-only"));
- await waitFor(() =>
- expect(
- screen.queryByTestId("add-models-row-openhands/unverified-model"),
- ).not.toBeInTheDocument(),
- );
- expect(
- screen.getByTestId("add-models-name-openhands/deepseek-v4-flash"),
- ).toHaveValue("my-flash");
- });
-
- it("does not repopulate rows when the old provider's query refreshes after close", async () => {
- // The reset clears provider, so the hook subscribes to a null-keyed query.
- // A late refresh of the previous provider's key must not reach it.
- const { setOpen } = renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
-
- setOpen(false);
- await waitFor(() =>
- expect(screen.queryByTestId("add-models-modal")).not.toBeInTheDocument(),
- );
- await queryClient.refetchQueries({
- queryKey: ["config", "models", "openhands"],
- });
-
- setOpen(true);
- await screen.findByTestId("add-models-modal");
- expect(screen.getByTestId("add-models-provider")).toHaveValue("");
- expect(screen.queryAllByTestId(/^add-models-row-/)).toHaveLength(0);
});
it("starts a fresh session when the modal is reopened", async () => {
vi.mocked(ProfilesService.saveProfile).mockRejectedValue(new Error("boom"));
const { setOpen } = renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
- );
- await userEvent.click(screen.getByTestId("add-models-select-all"));
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
await userEvent.click(screen.getByTestId("add-models-submit"));
- await waitFor(() => expect(screen.getAllByText("Failed")).toHaveLength(2));
+ await waitFor(() => expect(screen.getAllByText("Failed")).toHaveLength(3));
setOpen(false);
setOpen(true);
- const select = await screen.findByTestId("add-models-provider");
- expect(select).toHaveValue("");
expect(screen.queryByText("Failed")).not.toBeInTheDocument();
- expect(
- screen.queryByTestId("add-models-row-openhands/deepseek-v4-flash"),
- ).not.toBeInTheDocument();
});
it("select-all toggles every selectable row", async () => {
renderModal();
- await pickProvider();
- await screen.findByTestId(
- "add-models-row-openhands/trinity-large-thinking",
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ // Preselect mode auto-selects every row.
+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
+ "Add 3 profiles",
);
+ await userEvent.click(screen.getByTestId("add-models-select-all"));
expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
"Add 0 profiles",
);
@@ -529,12 +581,64 @@ describe("AddModelsModal", () => {
await userEvent.click(screen.getByTestId("add-models-select-all"));
expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
- "Add 2 profiles",
+ "Add 3 profiles",
);
+ });
- await userEvent.click(screen.getByTestId("add-models-select-all"));
+ it("does not re-submit saved rows on retry (no false failure)", async () => {
+ // Two models: the first saves, the second fails. The saved row must drop
+ // out of the selection so a retry only re-attempts the failed one —
+ // otherwise the saved row is re-created, 409s on its now-existing name,
+ // and surfaces as a failure for work that already succeeded.
+ vi.mocked(ConfigService.searchModels).mockResolvedValue({
+ items: [
+ model("openai", "gpt-4o", true),
+ model("openai", "gpt-4o-mini", true),
+ ],
+ next_page_id: null,
+ });
+ vi.mocked(ProfilesService.saveProfile)
+ .mockResolvedValueOnce({ name: "gpt-4o", message: "ok" })
+ .mockRejectedValue(new Error("boom"));
+ renderModal(OPENAI_CONNECTION, []);
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+
+ await userEvent.click(screen.getByTestId("add-models-submit"));
+ await waitFor(() =>
+ expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),
+ );
+
+ // The saved row is no longer selectable; only the failed row remains.
expect(screen.getByTestId("add-models-submit")).toHaveTextContent(
- "Add 0 profiles",
+ "Add 1 profiles",
);
+
+ // Retry: exactly one more create (the failed row), not two.
+ await userEvent.click(screen.getByTestId("add-models-submit"));
+ await waitFor(() =>
+ expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(3),
+ );
+ // The third create targets the failed row, never the saved one.
+ expect(
+ vi.mocked(ProfilesService.saveProfile).mock.calls[2][1].llm.model,
+ ).toBe("openai/gpt-4o-mini");
+ });
+
+ it("reloads the model list when reopened in preselect mode", async () => {
+ // Close leaves the provider set in state, and useProviderModels serves a
+ // cached list for the same provider — so reopening used to render the
+ // empty state with Submit disabled. Resetting provider/connection on close
+ // makes the list reload.
+ const { setOpen } = renderModal(OPENAI_CONNECTION, []);
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+
+ setOpen(false);
+ setOpen(true);
+
+ // The model list reloads instead of showing the empty state.
+ await screen.findByTestId("add-models-row-openai/gpt-4o");
+ expect(screen.queryByTestId("add-models-empty")).not.toBeInTheDocument();
+ // And the rows are re-selected (preselect intent carries across the reopen).
+ expect(screen.getByTestId("add-models-submit")).not.toBeDisabled();
});
});
diff --git a/__tests__/components/settings/llm-profiles/llm-profiles-manager.test.tsx b/__tests__/components/settings/llm-profiles/llm-profiles-manager.test.tsx
index ea5aa7ec30..d4b8a331f8 100644
--- a/__tests__/components/settings/llm-profiles/llm-profiles-manager.test.tsx
+++ b/__tests__/components/settings/llm-profiles/llm-profiles-manager.test.tsx
@@ -281,8 +281,55 @@ describe("LlmProfilesManager", () => {
expect(await screen.findByText("Provider connections")).toBeInTheDocument();
expect(screen.getByTestId("add-provider-connection")).toBeInTheDocument();
const row = await screen.findByTestId("provider-connection-row");
- expect(within(row).getByTestId("provider-connection-edit")).toBeVisible();
- expect(within(row).getByTestId("provider-connection-delete")).toBeVisible();
+ // Edit/delete/bulk-add live behind the three-dots menu, so a manager sees
+ // the trigger; the actions themselves appear once it is opened.
+ expect(
+ within(row).getByTestId("provider-connection-menu-trigger"),
+ ).toBeVisible();
+ });
+
+ it("shows the top Add-from-provider-connections button and opens the chooser modal", async () => {
+ const user = userEvent.setup();
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: mockProfiles,
+ active_profile: "gpt-4-profile",
+ });
+
+ renderManager(
+ { onAddProfile: vi.fn() },
+ { connections: [makeConnection()] },
+ );
+
+ const topButton = await screen.findByTestId("add-models-from-provider");
+ expect(topButton).toBeInTheDocument();
+ // The regular single-profile button remains alongside it.
+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();
+
+ // Chooser entry point: the modal opens with the combobox unset (no
+ // preselected connection), so the model list has not loaded yet.
+ await user.click(topButton);
+ expect(await screen.findByTestId("add-models-modal")).toBeInTheDocument();
+ const combobox = screen.getByTestId(
+ "add-models-provider",
+ ) as HTMLSelectElement;
+ expect(combobox.value).toBe("");
+ });
+
+ it("still shows the top Add-from-provider-connections button when there are no connections", async () => {
+ // The entry point stays reachable with zero connections: the user can
+ // pick a provider from the catalog and bulk-add keyless profiles, the
+ // pre-connection behavior the linked issue requires.
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: mockProfiles,
+ active_profile: "gpt-4-profile",
+ });
+
+ renderManager({ onAddProfile: vi.fn() }, { connections: [] });
+
+ expect(
+ await screen.findByTestId("add-models-from-provider"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();
});
it("hides provider connections on a cloud backend without an org", async () => {
diff --git a/src/components/features/settings/llm-profiles/add-models-modal.tsx b/src/components/features/settings/llm-profiles/add-models-modal.tsx
index 32d6eb5f19..57d78f4633 100644
--- a/src/components/features/settings/llm-profiles/add-models-modal.tsx
+++ b/src/components/features/settings/llm-profiles/add-models-modal.tsx
@@ -1,25 +1,21 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } 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 { SettingsInput } from "#/components/features/settings/settings-input";
-import { useSearchProviders } from "#/hooks/query/use-search-providers";
import { useProviderModels } from "#/hooks/query/use-provider-models";
+import { useSearchProviders } from "#/hooks/query/use-search-providers";
import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
import type { SaveProfileRequest } from "#/api/profiles-service/profiles-service.api";
-import {
- deriveProfileNameFromModel,
- isProfileNameValid,
-} from "#/utils/derive-profile-name";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import { mapProvider } from "#/utils/map-provider";
+import { deriveProfileNameFromModel } from "#/utils/derive-profile-name";
import {
displayErrorToast,
displaySuccessToast,
} from "#/utils/custom-toast-handlers";
import { I18nKey } from "#/i18n/declaration";
import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";
-import { cn } from "#/utils/utils";
-
/** Pull the server's own explanation out of an error, when it sent one. */
function getServerDetail(error: unknown): string | null {
const detail = (error as { response?: { detail?: unknown } })?.response
@@ -30,6 +26,23 @@ function getServerDetail(error: unknown): string | null {
interface AddModelsModalProps {
isOpen: boolean;
existingNames: string[];
+ /**
+ * Provider connections the user can bulk-add from. When the selected
+ * provider has a matching connection, the modal binds it (created profiles
+ * inherit the connection's credential). When it does not — or the user
+ * chooses "No connection" — profiles are created keyless, preserving the
+ * pre-connection bulk-add behavior.
+ */
+ connections: ProviderConnection[];
+ /**
+ * A connection id to preselect when the modal opens (launched from a
+ * connection row's "…"). Omit/leave null for the chooser entry point
+ * (the top "Add from provider connections" button), where the user picks a
+ * provider. In preselect mode the provider combobox opens on that
+ * connection's provider, the connection is bound, and its models load
+ * already selected.
+ */
+ initialConnectionId?: string | null;
onClose: () => void;
}
@@ -38,95 +51,171 @@ type RowStatus = "idle" | "saving" | "saved" | "failed";
interface ModelRow {
/** Full model id, e.g. "openhands/deepseek-v4-flash". */
model: string;
- /** Editable profile name. */
+ /** Derived profile name (not user-editable). */
name: string;
- verified: boolean;
selected: boolean;
status: RowStatus;
}
+/** Sentinel for the "no connection" (keyless) option in the connection box. */
+const KEYLESS_CONNECTION_VALUE = "";
+
/**
- * Bulk-add a provider's models as LLM profiles: pick a provider, select
- * models, edit the proposed names, add them all at once. Profiles are created
- * keyless (`include_secrets: false`) — a key, when a model needs one, is added
- * by editing the profile afterward, same as any keyless profile.
+ * Bulk-add models as LLM profiles. One modal serves two entry points: the top
+ * "Add from provider connections" button (chooser mode — pick a provider) and
+ * a connection row's "…" (preselect mode — opens on that connection's
+ * provider with the connection bound and models already selected).
+ *
+ * The selected provider drives the model list. When a matching provider
+ * connection exists it is bound by default, so created profiles inherit the
+ * connection's shared credential via `provider_connection_id` (mirroring the
+ * link flow in `llm-settings-local-view.tsx`) and no key needs to be added
+ * afterward. When no connection matches — or the user chooses "No connection"
+ * — `provider_connection_id` is null and profiles are created keyless, the
+ * same behavior bulk-add had before provider connections existed.
*/
export function AddModelsModal({
isOpen,
existingNames,
+ connections,
+ initialConnectionId = null,
onClose,
}: AddModelsModalProps) {
const { t } = useTranslation("openhands");
- const [provider, setProvider] = useState<string | null>(null);
- const [verifiedOnly, setVerifiedOnly] = useState(true);
+ const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
+ const [selectedConnectionId, setSelectedConnectionId] = useState<
+ string | null
+ >(null);
const [rows, setRows] = useState<ModelRow[]>([]);
const [submitting, setSubmitting] = useState(false);
- const providers = useSearchProviders();
- const models = useProviderModels(provider);
+ const { data: providers } = useSearchProviders();
+ const models = useProviderModels(selectedProvider);
const saveProfile = useSaveLlmProfile();
- // Rows follow the model list, and only the model list: the verified filter
- // hides rows at render rather than rebuilding them, because a rebuild
- // discards the edited names, selections and per-row statuses the user has
- // accumulated. A row already on screen keeps its state when the list
- // refreshes; only its verified flag tracks the server.
+ // Connections whose provider matches the selected provider. These are the
+ // only ones the connection box offers: a connection is only usable as a
+ // credential source for its own provider's models.
+ const matchingConnections = useMemo(
+ () =>
+ selectedProvider
+ ? connections.filter((c) => c.provider === selectedProvider)
+ : [],
+ [connections, selectedProvider],
+ );
+
+ // The bound connection id drives the submit payload. Null means keyless.
+ const connectionId = useMemo(() => {
+ if (!selectedConnectionId) return null;
+ return matchingConnections.some((c) => c.id === selectedConnectionId)
+ ? selectedConnectionId
+ : null;
+ }, [matchingConnections, selectedConnectionId]);
+
+ // Rows follow the model list, and only the model list. Already-added models
+ // are hidden at render rather than rebuilding the rows, because a rebuild
+ // discards the selections and per-row statuses the user has accumulated. A
+ // row already on screen keeps its state when the list refreshes.
+ // `autoSelectRef` is set when the modal opens from a connection row ("…"):
+ // that entry point is an explicit intent to bulk-add from that connection,
+ // so the loaded rows are selected for the user instead of forcing per-row
+ // clicking. It fires once per open (on the first model list that arrives)
+ // and is cleared, so a later connection change in the combobox does not
+ // re-select rows the user has already curated.
+ const autoSelectRef = useRef(false);
useEffect(() => {
const items = models.data ?? [];
+ const selectNew = autoSelectRef.current;
setRows((prev) => {
const prior = new Map(prev.map((row) => [row.model, row]));
- return items.map((m) => {
+ // Dedupe by canonical model id: a provider's catalog can list the same
+ // model twice (e.g. once in the verified set and once in the raw list
+ // when the two disagree on prefixing). Without dedup each copy becomes
+ // its own row with the same derived name, and the two flag each other as
+ // conflicts — surfacing bogus "Name already exists" on a fresh account.
+ const seen = new Set<string>();
+ const built: ModelRow[] = [];
+ for (const m of items) {
const full =
m.provider && !m.name.startsWith(`${m.provider}/`)
? `${m.provider}/${m.name}`
: m.name;
- const verified = !!m.verified;
+ if (seen.has(full)) continue;
+ seen.add(full);
const carried = prior.get(full);
- if (carried) return { ...carried, verified };
- return {
- model: full,
- name: deriveProfileNameFromModel(full),
- verified,
- // Nothing is pre-selected: the server caps how many profiles an
- // account may hold, so defaulting to "all" invites a submission
- // that is mostly refusals. Choosing is the point of the modal.
- selected: false,
- status: "idle" as RowStatus,
- };
- });
+ built.push(
+ carried
+ ? carried
+ : {
+ model: full,
+ name: deriveProfileNameFromModel(full),
+ // Chooser mode leaves rows unselected: the server caps how
+ // many profiles an account may hold, so defaulting to "all"
+ // invites a submission that is mostly refusals. Preselect mode
+ // (autoSelectRef) selects them — see the comment above.
+ selected: selectNew,
+ status: "idle" as RowStatus,
+ },
+ );
+ }
+ return built;
});
+ if (items.length > 0) autoSelectRef.current = false;
}, [models.data]);
// The manager keeps this component mounted and drives it with `isOpen`, so
// without an explicit reset a reopened modal still shows the last session's
- // provider, selections and Saved/Failed marks.
+ // provider, connection, selections, and Saved/Failed marks. On open, seed
+ // the provider/connection from `initialConnectionId` (preselect mode) or
+ // leave both unset (chooser mode). On close, clear everything.
useEffect(() => {
- if (!isOpen) {
- setProvider(null);
- setVerifiedOnly(true);
+ if (isOpen) {
+ const initial =
+ initialConnectionId &&
+ connections.find((c) => c.id === initialConnectionId);
+ if (initial) {
+ setSelectedProvider(initial.provider);
+ setSelectedConnectionId(initial.id);
+ autoSelectRef.current = true;
+ } else {
+ setSelectedProvider(null);
+ setSelectedConnectionId(null);
+ }
+ } else {
+ // Clear the provider/connection too, not just the rows. The modal stays
+ // mounted between openings, and `useProviderModels` serves a cached
+ // `models.data` for the same provider — so if `selectedProvider` is left
+ // set, reopening in preselect mode reseeds the same provider string, the
+ // cached list reference is unchanged, and the `[models.data]` effect
+ // never re-runs to rebuild `rows`. Resetting to null makes that effect
+ // see undefined -> cached-list on reopen, so the model list reloads.
+ setSelectedProvider(null);
+ setSelectedConnectionId(null);
setRows([]);
setSubmitting(false);
+ autoSelectRef.current = false;
}
- }, [isOpen]);
+ }, [isOpen, initialConnectionId, connections]);
const existing = useMemo(() => new Set(existingNames), [existingNames]);
if (!isOpen) return null;
- // Everything below reasons about what the user can see: a row hidden by the
- // filter is neither counted, nor conflict-checked, nor submitted.
- const visibleRows = rows.filter((row) => !verifiedOnly || row.verified);
-
- const nameCounts = new Map<string, number>();
- for (const row of visibleRows) {
- nameCounts.set(row.name, (nameCounts.get(row.name) ?? 0) + 1);
- }
- const hasConflict = (row: ModelRow) =>
- existing.has(row.name) || (nameCounts.get(row.name) ?? 0) > 1;
+ // Already-added models are hidden, not disabled: a row whose name matches an
+ // existing profile can't be re-created, so showing it (flagged or greyed)
+ // just clutters the list. A saved row is exempt — it was added from this
+ // very session, so it stays visible with its "Saved" mark.
+ const visibleRows = rows.filter(
+ (row) => row.status === "saved" || !existing.has(row.name),
+ );
- const isSelectable = (row: ModelRow) =>
- !hasConflict(row) && isProfileNameValid(row.name, { isRequired: true });
- const selectable = visibleRows.filter(isSelectable);
+ // Saved rows stay visible (so the user sees the "Saved" mark) but are not
+ // selectable: a saved row is finished work, so it must not count toward the
+ // footer's "Add N", drive select-all, or be re-POSTed on a retry. Without
+ // this exclusion a partial submit leaves the saved rows selected, and a
+ // second Submit re-creates them — the create now 409s (the name exists) and
+ // is reported as a fresh failure for work that already succeeded.
+ const selectable = visibleRows.filter((row) => row.status !== "saved");
const selectedRows = selectable.filter((row) => row.selected);
const setRow = (model: string, patch: Partial<ModelRow>) =>
@@ -147,6 +236,16 @@ export function AddModelsModal({
);
};
+ // When the user picks a provider, bind a matching connection by default so
+ // created profiles are usable out of the box (this modal's reason for
+ // existing). If there is no matching connection, leave it keyless. The user
+ // can still switch the connection box to "No connection" to opt out.
+ const handleProviderChange = (value: string) => {
+ setSelectedProvider(value || null);
+ const first = connections.find((c) => c.provider === value);
+ setSelectedConnectionId(first?.id ?? null);
+ };
+
const handleSubmit = async () => {
setSubmitting(true);
const targets = selectedRows;
@@ -173,7 +272,16 @@ export function AddModelsModal({
await saveProfile.mutateAsync({
name: row.name,
request: {
- llm: { model: row.model } as SaveProfileRequest["llm"],
+ // A bound connection sources the credential, so it replaces any
+ // inline api_key/base_url — mirrored on the normal save flow in
+ // `llm-settings-local-view.tsx`. `include_secrets: false` because
+ // no secret is being sent; the link is by id. When no connection
+ // is bound (`connectionId` is null) the profile is keyless, the
+ // same as bulk-add before provider connections existed.
+ llm: {
+ model: row.model,
+ provider_connection_id: connectionId,
+ } as SaveProfileRequest["llm"],
include_secrets: false,
},
});
@@ -231,23 +339,13 @@ export function AddModelsModal({
if (!submitting) onClose();
};
- // Split verified from the rest, matching how the model selector presents the
- // same list: the provider feed carries entries that are not really providers
- // (image dimensions, quality tiers), and they belong below a divider rather
- // than inline with Anthropic and OpenAI.
- const providerOptions = providers.data ?? [];
- const verifiedProviders = providerOptions.filter((p) => p.verified);
- const otherProviders = providerOptions.filter((p) => !p.verified);
- const isLoadingModels = provider !== null && models.isLoading;
+ const isLoadingModels = selectedProvider !== null && models.isLoading;
+ // Only flag "empty" once a provider is chosen and its (non-loading) model
+ // list came back bare. In chooser mode with nothing picked yet, the
+ // provider box is the prompt — there's no list to call empty.
const showEmpty =
- provider !== null && !isLoadingModels && visibleRows.length === 0;
- // Empty because the provider has nothing, or empty because the filter hid
- // everything it has. Telling the user the provider is bare when the fix is
- // one checkbox away sends them looking in the wrong place.
- const emptyMessage =
- showEmpty && rows.length > 0
- ? I18nKey.COMMON$NO_RESULTS
- : I18nKey.SETTINGS$ADD_MODELS_EMPTY;
+ selectedProvider !== null && !isLoadingModels && visibleRows.length === 0;
+ const emptyMessage = I18nKey.SETTINGS$ADD_MODELS_EMPTY;
const footer = (
<>
@@ -285,52 +383,74 @@ export function AddModelsModal({
onClose={handleClose}
>
<div data-testid="add-models-modal" className="flex flex-col gap-3">
- <label className="flex flex-col gap-2 text-sm text-white">
+ <label
+ className="flex flex-col gap-2 text-sm text-white"
+ data-testid="add-models-provider-field"
+ >
{t(I18nKey.SETTINGS$ADD_MODELS_PROVIDER_LABEL)}
<select
data-testid="add-models-provider"
className="rounded-md border border-[var(--oh-border)] bg-[var(--oh-background)] px-3 py-2 text-sm text-white"
- value={provider ?? ""}
- onChange={(e) => setProvider(e.target.value || null)}
+ value={selectedProvider ?? ""}
+ onChange={(e) => handleProviderChange(e.target.value)}
disabled={submitting}
>
<option value="" disabled>
{t(I18nKey.SETTINGS$ADD_MODELS_PROVIDER_PLACEHOLDER)}
</option>
- {verifiedProviders.length > 0 && (
- <optgroup label={t(I18nKey.MODEL_SELECTOR$VERIFIED)}>
- {verifiedProviders.map((p) => (
- <option key={p.name} value={p.name}>
- {p.name}
- </option>
- ))}
- </optgroup>
- )}
- {otherProviders.length > 0 && (
- <optgroup label={t(I18nKey.MODEL_SELECTOR$OTHERS)}>
- {otherProviders.map((p) => (
- <option key={p.name} value={p.name}>
- {p.name}
- </option>
- ))}
- </optgroup>
- )}
+ {providers?.map((p) => (
+ <option key={p.name} value={p.name}>
+ {mapProvider(p.name)}
+ </option>
+ ))}
</select>
</label>
- {provider !== null && (
- <label className="flex items-center gap-2 text-sm text-white">
- <input
- data-testid="add-models-verified-only"
- type="checkbox"
- checked={verifiedOnly}
- onChange={(e) => setVerifiedOnly(e.target.checked)}
+ {/* Only offer a connection binding when the selected provider has a
+ matching connection. With none, the run is keyless and there is
+ nothing to choose, so the box is omitted rather than showing a
+ lone "No connection" option. */}
+ {matchingConnections.length > 0 && (
+ <label
+ className="flex flex-col gap-2 text-sm text-white"
+ data-testid="add-models-connection-field"
+ >
+ {t(I18nKey.SETTINGS$ADD_MODELS_CONNECTION_LABEL)}
+ <select
+ data-testid="add-models-connection"
+ className="rounded-md border border-[var(--oh-border)] bg-[var(--oh-background)] px-3 py-2 text-sm text-white"
+ value={selectedConnectionId ?? KEYLESS_CONNECTION_VALUE}
+ onChange={(e) => setSelectedConnectionId(e.target.value || null)}
disabled={submitting}
- />
- {t(I18nKey.SETTINGS$ADD_MODELS_VERIFIED_ONLY)}
+ >
+ <option value={KEYLESS_CONNECTION_VALUE}>
+ {t(I18nKey.SETTINGS$ADD_MODELS_NO_CONNECTION)}
+ </option>
+ {matchingConnections.map((c) => (
+ <option key={c.id} value={c.id}>
+ {c.display_name}
+ </option>
+ ))}
+ </select>
</label>
)}
+ {selectedProvider && connectionId && (
+ <span className="min-w-0 max-w-full truncate text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$ADD_MODELS_CONNECTION_BOUND, {
+ provider: selectedProvider,
+ })}
+ </span>
+ )}
+ {selectedProvider && !connectionId && (
+ <span
+ data-testid="add-models-keyless-note"
+ className="min-w-0 max-w-full truncate text-xs text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.SETTINGS$ADD_MODELS_KEYLESS_NOTE)}
+ </span>
+ )}
+
{isLoadingModels && (
<div data-testid="add-models-loading" className="py-4 text-center">
<LoadingSpinner size="small" />
@@ -360,15 +480,11 @@ export function AddModelsModal({
</label>
<ul className="flex max-h-64 flex-col gap-2 overflow-y-auto">
{visibleRows.map((row) => {
- // A successfully saved row re-appears in existingNames after
- // the profiles query refreshes — don't flag it as conflicting
- // with itself.
- const conflict = row.status !== "saved" && hasConflict(row);
- const valid = isProfileNameValid(row.name, {
- isRequired: true,
- });
- const disabled =
- submitting || conflict || row.status === "saved";
+ const disabled = submitting || row.status === "saved";
+ // Show the model name without the provider prefix — the
+ // prefix is implied by the selected connection and just adds
+ // visual noise to every row.
+ const shortName = row.model.split("/").pop() ?? row.model;
return (
<li
key={row.model}
@@ -378,17 +494,17 @@ export function AddModelsModal({
<input
data-testid={`add-models-check-${row.model}`}
type="checkbox"
- checked={row.selected && !conflict}
+ checked={row.selected}
onChange={(e) =>
setRow(row.model, { selected: e.target.checked })
}
- disabled={disabled || !valid}
+ disabled={disabled}
/>
<span
className="min-w-0 flex-1 truncate text-sm text-white"
title={row.model}
>
- {row.model}
+ {shortName}
</span>
{row.status === "saving" && <LoadingSpinner size="small" />}
{row.status === "saved" && (
@@ -401,25 +517,6 @@ export function AddModelsModal({
{t(I18nKey.SETTINGS$MODEL_ROW_FAILED)}
</span>
)}
- <div className="w-48">
- <SettingsInput
- testId={`add-models-name-${row.model}`}
- label=""
- type="text"
- value={row.name}
- onChange={(value) => setRow(row.model, { name: value })}
- isDisabled={disabled}
- ariaInvalid={!valid || conflict}
- />
- </div>
- {conflict && (
- <span
- data-testid={`add-models-conflict-${row.model}`}
- className={cn("text-xs", "text-red-400")}
- >
- {t(I18nKey.SETTINGS$ADD_MODELS_NAME_TAKEN)}
- </span>
- )}
</li>
);
})}
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 12ce71569b..19c8385581 100644
--- a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx
+++ b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx
@@ -57,7 +57,14 @@ export function LlmProfilesManager({
const [profileToDelete, setProfileToDelete] = useState<ProfileInfo | null>(
null,
);
+ // One AddModelsModal serves both entry points: the top "Add from provider
+ // connections" button (chooser — no preselect) and a connection row's "..."
+ // (preselect to that connection). `addModelsConnectionId` is null in chooser
+ // mode and the connection id in preselect mode.
const [showAddModels, setShowAddModels] = useState(false);
+ const [addModelsConnectionId, setAddModelsConnectionId] = useState<
+ string | null
+ >(null);
const profiles = data?.profiles ?? [];
const active = data?.active_profile ?? null;
@@ -133,17 +140,21 @@ export function LlmProfilesManager({
<h2 className="text-base font-medium text-contrast">
{t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}
</h2>
- {onAddProfile && canManage ? (
- <>
+ <div className="ml-auto flex items-center gap-2">
+ {canManage && supportsConnections ? (
<BrandButton
testId="add-models-from-provider"
type="button"
variant="tertiary"
- className="ml-auto"
- onClick={() => setShowAddModels(true)}
+ onClick={() => {
+ setAddModelsConnectionId(null);
+ setShowAddModels(true);
+ }}
>
{t(I18nKey.SETTINGS$ADD_MODELS_FROM_PROVIDER)}
</BrandButton>
+ ) : null}
+ {onAddProfile && canManage ? (
<BrandButton
testId="add-llm-profile"
type="button"
@@ -152,8 +163,8 @@ export function LlmProfilesManager({
>
{t(I18nKey.SETTINGS$ADD_LLM_PROFILE)}
</BrandButton>
- </>
- ) : null}
+ ) : null}
+ </div>
</div>
<ProfilesBody
@@ -179,6 +190,10 @@ export function LlmProfilesManager({
linkedCountById={linkedCountById}
isLoading={isLoadingConnections}
loadError={connectionsError ?? null}
+ onAddModels={(connection) => {
+ setAddModelsConnectionId(connection.id);
+ setShowAddModels(true);
+ }}
/>
) : null}
</div>
@@ -193,6 +208,8 @@ export function LlmProfilesManager({
/>
<AddModelsModal
isOpen={showAddModels}
+ connections={connectionList}
+ initialConnectionId={addModelsConnectionId}
existingNames={profiles.map((p) => p.name)}
onClose={() => setShowAddModels(false)}
/>
diff --git a/src/components/features/settings/llm-profiles/provider-connection-actions-menu.tsx b/src/components/features/settings/llm-profiles/provider-connection-actions-menu.tsx
new file mode 100644
index 0000000000..fb9b1494d7
--- /dev/null
+++ b/src/components/features/settings/llm-profiles/provider-connection-actions-menu.tsx
@@ -0,0 +1,180 @@
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useCallback,
+ useState,
+} from "react";
+import ReactDOM from "react-dom";
+import { useTranslation } from "react-i18next";
+import { cn } from "#/utils/utils";
+import { dropdownMenuListClassName } from "#/utils/dropdown-classes";
+import { I18nKey } from "#/i18n/declaration";
+import EditIcon from "#/icons/u-edit.svg?react";
+import DeleteIcon from "#/icons/u-delete.svg?react";
+import AddModelsIcon from "#/icons/u-plus.svg?react";
+import { MenuItem } from "./profile-actions-menu-item";
+
+interface ProviderConnectionActionsMenuProps {
+ onAddModels: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+ onClose: () => void;
+ /**
+ * Element the menu should anchor against. When provided, the menu renders
+ * into a portal at the document body using fixed positioning so it cannot be
+ * clipped by ancestors with `overflow: auto/hidden` (e.g. the settings
+ * `<main>` scroll container).
+ */
+ anchorRef?: React.RefObject<HTMLElement | null>;
+}
+
+export function ProviderConnectionActionsMenu({
+ onAddModels,
+ onEdit,
+ onDelete,
+ onClose,
+ anchorRef,
+}: ProviderConnectionActionsMenuProps) {
+ const { t } = useTranslation("openhands");
+ const menuRef = useRef<HTMLDivElement>(null);
+ const menuItemsRef = useRef<(HTMLButtonElement | null)[]>([]);
+
+ const anchorElement = anchorRef?.current ?? null;
+ const [portalStyle, setPortalStyle] = useState<React.CSSProperties>();
+
+ useLayoutEffect(() => {
+ if (!anchorElement) return undefined;
+
+ const updatePosition = () => {
+ const rect = anchorElement.getBoundingClientRect();
+ if (!rect) return;
+ const gap = 8;
+ setPortalStyle({
+ position: "fixed",
+ zIndex: 9999,
+ top: rect.bottom + gap,
+ right: window.innerWidth - rect.right,
+ width: "max-content",
+ });
+ };
+
+ updatePosition();
+ window.addEventListener("resize", updatePosition);
+ window.addEventListener("scroll", updatePosition, true);
+ return () => {
+ window.removeEventListener("resize", updatePosition);
+ window.removeEventListener("scroll", updatePosition, true);
+ };
+ }, [anchorElement]);
+
+ useEffect(() => {
+ menuItemsRef.current[0]?.focus();
+ }, []);
+
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ const target = event.target as Node;
+ if (menuRef.current?.contains(target)) return;
+ if (anchorElement?.contains(target)) return;
+ onClose();
+ };
+
+ const handleEscape = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ onClose();
+ }
+ };
+
+ document.addEventListener("mousedown", handleClickOutside);
+ document.addEventListener("keydown", handleEscape);
+
+ return () => {
+ document.removeEventListener("mousedown", handleClickOutside);
+ document.removeEventListener("keydown", handleEscape);
+ };
+ }, [anchorElement, onClose]);
+
+ const handleAction = (action: () => void) => {
+ action();
+ onClose();
+ };
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent, currentIndex: number) => {
+ if (e.key === "Tab") {
+ onClose();
+ return;
+ }
+ const itemCount = menuItemsRef.current.filter(Boolean).length;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ const nextIndex = (currentIndex + 1) % itemCount;
+ menuItemsRef.current[nextIndex]?.focus();
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ const prevIndex = (currentIndex - 1 + itemCount) % itemCount;
+ menuItemsRef.current[prevIndex]?.focus();
+ }
+ },
+ [onClose],
+ );
+
+ const isPortaled = Boolean(anchorElement);
+
+ const menu = (
+ <div
+ ref={menuRef}
+ className={cn(
+ "absolute right-0 top-full z-10 mt-2 w-40 rounded-md border border-border-subtle bg-tertiary px-1 py-1 shadow-lg",
+ dropdownMenuListClassName,
+ isPortaled &&
+ "!static !top-auto !bottom-auto !left-auto !right-auto !mt-0",
+ )}
+ role="menu"
+ aria-orientation="vertical"
+ data-testid="provider-connection-actions-menu"
+ >
+ <MenuItem
+ index={0}
+ icon={<AddModelsIcon width={16} height={16} />}
+ label={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_BULK_ADD)}
+ onClick={() => handleAction(onAddModels)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ testId="provider-connection-add-models"
+ />
+ <MenuItem
+ index={1}
+ icon={<EditIcon width={16} height={16} />}
+ label={t(I18nKey.BUTTON$EDIT)}
+ onClick={() => handleAction(onEdit)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ testId="provider-connection-edit"
+ />
+ <MenuItem
+ index={2}
+ icon={<DeleteIcon width={16} height={16} />}
+ label={t(I18nKey.BUTTON$DELETE)}
+ onClick={() => handleAction(onDelete)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ testId="provider-connection-delete"
+ />
+ </div>
+ );
+
+ if (isPortaled) {
+ if (typeof document === "undefined" || !portalStyle) {
+ return null;
+ }
+ return ReactDOM.createPortal(
+ // portal position computed from DOM bounding rect at runtime
+ <div style={portalStyle}>{menu}</div>,
+ document.body,
+ );
+ }
+
+ return menu;
+}
diff --git a/src/components/features/settings/llm-profiles/provider-connection-row.tsx b/src/components/features/settings/llm-profiles/provider-connection-row.tsx
index 808eaaae8a..cf97c2d681 100644
--- a/src/components/features/settings/llm-profiles/provider-connection-row.tsx
+++ b/src/components/features/settings/llm-profiles/provider-connection-row.tsx
@@ -1,7 +1,8 @@
+import { useRef, useState } from "react";
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 { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";
+import { ProviderConnectionActionsMenu } from "./provider-connection-actions-menu";
import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
import { cn } from "#/utils/utils";
import {
@@ -14,6 +15,7 @@ interface ProviderConnectionRowProps {
connection: ProviderConnection;
/** Number of LLM profiles linked to this connection. */
linkedProfileCount: number;
+ onAddModels: (connection: ProviderConnection) => void;
onEdit: (connection: ProviderConnection) => void;
onDelete: (connection: ProviderConnection) => void;
}
@@ -21,10 +23,13 @@ interface ProviderConnectionRowProps {
export function ProviderConnectionRow({
connection,
linkedProfileCount,
+ onAddModels,
onEdit,
onDelete,
}: ProviderConnectionRowProps) {
const { t } = useTranslation("openhands");
+ const [menuOpen, setMenuOpen] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
return (
<div
@@ -48,25 +53,23 @@ export function ProviderConnectionRow({
</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)}
+ <div className="relative shrink-0">
+ <EllipsisButton
+ ref={triggerRef}
+ onClick={() => setMenuOpen((open) => !open)}
+ ariaLabel={t(I18nKey.SETTINGS$PROVIDER_CONNECTION_MENU)}
+ testId="provider-connection-menu-trigger"
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>
+ />
+ {menuOpen && (
+ <ProviderConnectionActionsMenu
+ anchorRef={triggerRef}
+ onAddModels={() => onAddModels(connection)}
+ onEdit={() => onEdit(connection)}
+ onDelete={() => onDelete(connection)}
+ onClose={() => setMenuOpen(false)}
+ />
+ )}
</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
index e90c363e60..83ce97aca2 100644
--- a/src/components/features/settings/llm-profiles/provider-connections-manager.test.tsx
+++ b/src/components/features/settings/llm-profiles/provider-connections-manager.test.tsx
@@ -26,6 +26,16 @@ vi.mock("#/hooks/query/use-search-providers", () => ({
}),
}));
+// The add-models modal hydrates its list through useProviderModels, which
+// pages ConfigService.searchModels; stub it to an empty list so the modal
+// renders its empty state without hitting a backend. The returned array is
+// module-level so its reference is stable across renders — the modal's row
+// effect keys off `data`, so a fresh array each render would loop forever.
+const STUB_MODELS: unknown[] = [];
+vi.mock("#/hooks/query/use-provider-models", () => ({
+ useProviderModels: () => ({ data: STUB_MODELS, isLoading: false }),
+}));
+
const renderWith = (ui: React.ReactElement) => renderWithProviders(ui);
const connection: ProviderConnection = {
@@ -54,6 +64,7 @@ describe("ProviderConnectionsManager", () => {
connections={[]}
linkedCountById={{}}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
@@ -71,6 +82,7 @@ describe("ProviderConnectionsManager", () => {
connections={[]}
linkedCountById={{}}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
@@ -107,6 +119,7 @@ describe("ProviderConnectionsManager", () => {
connections={[]}
linkedCountById={{}}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
@@ -142,6 +155,7 @@ describe("ProviderConnectionsManager", () => {
connections={[connection]}
linkedCountById={{ "conn-1": 3 }}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
@@ -151,6 +165,45 @@ describe("ProviderConnectionsManager", () => {
expect(screen.getByText("openai")).toBeInTheDocument();
});
+ it("renders a bulk-add-models action in each connection's menu", async () => {
+ const user = userEvent.setup();
+ renderWith(
+ <ProviderConnectionsManager
+ connections={[connection]}
+ linkedCountById={{}}
+ isLoading={false}
+ onAddModels={vi.fn()}
+ loadError={null}
+ />,
+ );
+
+ await user.click(screen.getByTestId("provider-connection-menu-trigger"));
+ expect(
+ await screen.findByTestId("provider-connection-add-models"),
+ ).toBeInTheDocument();
+ });
+
+ it("calls onAddModels with the clicked connection (parent opens the modal)", async () => {
+ const user = userEvent.setup();
+ const onAddModels = vi.fn();
+ renderWith(
+ <ProviderConnectionsManager
+ connections={[connection]}
+ linkedCountById={{}}
+ isLoading={false}
+ loadError={null}
+ onAddModels={onAddModels}
+ />,
+ );
+
+ await user.click(screen.getByTestId("provider-connection-menu-trigger"));
+ await user.click(screen.getByTestId("provider-connection-add-models"));
+
+ // The modal itself is owned by the parent (one shared instance for both
+ // entry points), so the row's job is to hand the clicked connection up.
+ expect(onAddModels).toHaveBeenCalledWith(connection);
+ });
+
it("shows supported providers in the edit-connection selector", async () => {
const user = userEvent.setup();
@@ -159,10 +212,12 @@ describe("ProviderConnectionsManager", () => {
connections={[connection]}
linkedCountById={{}}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
+ await user.click(screen.getByTestId("provider-connection-menu-trigger"));
await user.click(screen.getByTestId("provider-connection-edit"));
const providerSelector = screen.getByRole("combobox", {
@@ -191,10 +246,12 @@ describe("ProviderConnectionsManager", () => {
connections={[connection]}
linkedCountById={{ "conn-1": 1 }}
isLoading={false}
+ onAddModels={vi.fn()}
loadError={null}
/>,
);
+ fireEvent.click(screen.getByTestId("provider-connection-menu-trigger"));
fireEvent.click(screen.getByTestId("provider-connection-delete"));
fireEvent.click(screen.getByTestId("delete-provider-connection-confirm"));
diff --git a/src/components/features/settings/llm-profiles/provider-connections-manager.tsx b/src/components/features/settings/llm-profiles/provider-connections-manager.tsx
index f1d3e05093..12d849e40b 100644
--- a/src/components/features/settings/llm-profiles/provider-connections-manager.tsx
+++ b/src/components/features/settings/llm-profiles/provider-connections-manager.tsx
@@ -19,18 +19,26 @@ interface ProviderConnectionsManagerProps {
linkedCountById: Record<string, number>;
isLoading: boolean;
loadError: Error | null;
+ /**
+ * Called when a connection's "..." bulk-add action is clicked. The parent
+ * owns the single shared AddModelsModal and opens it preselected to this
+ * connection, so there is one modal for both entry points.
+ */
+ onAddModels: (connection: ProviderConnection) => void;
}
/**
* 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.
+ * which is the only backend exposing the endpoints. Each connection row carries
+ * its own "add models" action that bulk-creates profiles linked to it.
*/
export function ProviderConnectionsManager({
connections,
linkedCountById,
isLoading,
loadError,
+ onAddModels,
}: ProviderConnectionsManagerProps) {
const { t } = useTranslation("openhands");
const [isCreating, setIsCreating] = useState(false);
@@ -80,6 +88,7 @@ export function ProviderConnectionsManager({
key={connection.id}
connection={connection}
linkedProfileCount={linkedCountById[connection.id] ?? 0}
+ onAddModels={onAddModels}
onEdit={setConnectionToEdit}
onDelete={setConnectionToDelete}
/>
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 1c751ce862..60588547fb 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -32572,72 +32572,106 @@
"uk": "Для цього постачальника моделей не знайдено."
},
"SETTINGS$ADD_MODELS_FROM_PROVIDER": {
- "en": "Add from provider models",
- "ja": "プロバイダーのモデルから追加",
- "zh-CN": "从提供商模型添加",
- "zh-TW": "從供應商模型新增",
- "ko-KR": "제공업체 모델에서 추가",
- "no": "Legg til fra leverandørmodeller",
- "it": "Aggiungi dai modelli del provider",
- "pt": "Adicionar a partir de modelos do provedor",
- "es": "Añadir desde modelos del proveedor",
- "ar": "إضافة من نماذج المزوّد",
- "fr": "Ajouter depuis les modèles du fournisseur",
- "tr": "Sağlayıcı modellerinden ekle",
- "de": "Von Anbieter-Modellen hinzufügen",
- "ca": "Afegeix des de models del proveïdor",
- "uk": "Додати з моделей постачальника"
- },
- "SETTINGS$ADD_MODELS_NAME_TAKEN": {
- "en": "Name already exists",
- "ja": "この名前はすでに存在します",
- "zh-CN": "名称已存在",
- "zh-TW": "名稱已存在",
- "ko-KR": "이미 존재하는 이름입니다",
- "no": "Navnet finnes allerede",
- "it": "Nome già esistente",
- "pt": "Nome já existe",
- "es": "El nombre ya existe",
- "ar": "الاسم موجود بالفعل",
- "fr": "Ce nom existe déjà",
- "tr": "Bu ad zaten var",
- "de": "Name bereits vergeben",
- "ca": "El nom ja existeix",
- "uk": "Ім'я вже існує"
+ "ar": "إضافة من اتصالات المزود",
+ "ca": "Afegeix des de connexions de proveïdor",
+ "de": "Aus Anbieterverbindungen hinzufügen",
+ "en": "Add from provider connections",
+ "es": "Añadir desde conexiones de proveedor",
+ "fr": "Ajouter depuis les connexions fournisseur",
+ "it": "Aggiungi da connessioni provider",
+ "ja": "プロバイダー接続から追加",
+ "ko-KR": "공급자 연결에서 추가",
+ "no": "Legg til fra leverandørtilkoblinger",
+ "pt": "Adicionar de conexões de provedor",
+ "tr": "Sağlayıcı bağlantılarından ekle",
+ "uk": "Додати з підключень постачальника",
+ "zh-CN": "从提供商连接添加",
+ "zh-TW": "從提供者連線新增"
},
"SETTINGS$ADD_MODELS_PROVIDER_LABEL": {
+ "ar": "المزوّد",
+ "ca": "Proveïdor",
+ "de": "Anbieter",
"en": "Provider",
+ "es": "Proveedor",
+ "fr": "Fournisseur",
+ "it": "Provider",
"ja": "プロバイダー",
- "zh-CN": "提供商",
- "zh-TW": "供應商",
- "ko-KR": "제공업체",
+ "ko-KR": "공급자",
"no": "Leverandør",
- "it": "Provider",
"pt": "Provedor",
- "es": "Proveedor",
- "ar": "المزوّد",
- "fr": "Fournisseur",
"tr": "Sağlayıcı",
- "de": "Anbieter",
- "ca": "Proveïdor",
- "uk": "Постачальник"
+ "uk": "Постачальник",
+ "zh-CN": "提供商",
+ "zh-TW": "提供者"
},
"SETTINGS$ADD_MODELS_PROVIDER_PLACEHOLDER": {
+ "ar": "اختر مزوّداً",
+ "ca": "Selecciona un proveïdor",
+ "de": "Anbieter auswählen",
"en": "Select a provider",
+ "es": "Selecciona un proveedor",
+ "fr": "Sélectionner un fournisseur",
+ "it": "Seleziona un provider",
"ja": "プロバイダーを選択",
- "zh-CN": "选择提供商",
- "zh-TW": "選擇供應商",
- "ko-KR": "제공업체 선택",
+ "ko-KR": "공급자를 선택하세요",
"no": "Velg en leverandør",
- "it": "Seleziona un provider",
"pt": "Selecione um provedor",
- "es": "Selecciona un proveedor",
- "ar": "اختر مزوّدًا",
- "fr": "Sélectionner un fournisseur",
"tr": "Bir sağlayıcı seçin",
- "de": "Anbieter auswählen",
- "ca": "Selecciona un proveïdor",
- "uk": "Виберіть постачальника"
+ "uk": "Виберіть постачальника",
+ "zh-CN": "选择一个提供商",
+ "zh-TW": "選擇一個提供者"
+ },
+ "SETTINGS$ADD_MODELS_CONNECTION_LABEL": {
+ "ar": "اتصال المزوّد",
+ "ca": "Connexió de proveïdor",
+ "de": "Anbieterverbindung",
+ "en": "Provider connection",
+ "es": "Conexión de proveedor",
+ "fr": "Connexion 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$ADD_MODELS_NO_CONNECTION": {
+ "ar": "بدون اتصال (بدون مفتاح)",
+ "ca": "Sense connexió (sense clau)",
+ "de": "Keine Verbindung (schlüssellos)",
+ "en": "No connection (keyless)",
+ "es": "Sin conexión (sin clave)",
+ "fr": "Aucune connexion (sans clé)",
+ "it": "Nessuna connessione (senza chiave)",
+ "ja": "接続なし(キーなし)",
+ "ko-KR": "연결 없음 (키 없음)",
+ "no": "Ingen tilkobling (nøkkeløs)",
+ "pt": "Sem conexão (sem chave)",
+ "tr": "Bağlantı yok (anahtarsız)",
+ "uk": "Без підключення (без ключа)",
+ "zh-CN": "无连接(无密钥)",
+ "zh-TW": "無連線(無金鑰)"
+ },
+ "SETTINGS$ADD_MODELS_KEYLESS_NOTE": {
+ "ar": "بدون اتصال — ستحتاج الملفات الشخصية إلى مفتاح لاحقاً",
+ "ca": "Sense connexió — els perfils necessitaran una clau més endavant",
+ "de": "Keine Verbindung — Profile benötigen später einen Schlüssel",
+ "en": "No connection — profiles will need a key added later",
+ "es": "Sin conexión — los perfiles necesitarán una clave más adelante",
+ "fr": "Aucune connexion — les profils auront besoin d'une clé plus tard",
+ "it": "Nessuna connessione — i profili richiederanno una chiave in seguito",
+ "ja": "接続なし — プロファイルには後でキーが必要です",
+ "ko-KR": "연결 없음 — 프로필에 나중에 키가 필요합니다",
+ "no": "Ingen tilkobling — profiler trenger en nøkkel senere",
+ "pt": "Sem conexão — os perfis precisarão de uma chave depois",
+ "tr": "Bağlantı yok — profillerin daha sonra bir anahtara ihtiyacı olacak",
+ "uk": "Без підключення — профілям знадобиться ключ пізніше",
+ "zh-CN": "无连接 — 配置文件稍后需要添加密钥",
+ "zh-TW": "無連線 — 設定檔稍後需要新增金鑰"
},
"SETTINGS$ADD_MODELS_SELECT_ALL": {
"en": "Select all",
@@ -32673,22 +32707,22 @@
"ca": "Afegeix models com a perfils",
"uk": "Додати моделі як профілі"
},
- "SETTINGS$ADD_MODELS_VERIFIED_ONLY": {
- "en": "Verified models only",
- "ja": "検証済みモデルのみ",
- "zh-CN": "仅已验证的模型",
- "zh-TW": "僅已驗證的模型",
- "ko-KR": "검증된 모델만",
- "no": "Kun verifiserte modeller",
- "it": "Solo modelli verificati",
- "pt": "Apenas modelos verificados",
- "es": "Solo modelos verificados",
- "ar": "النماذج الموثّقة فقط",
- "fr": "Modèles vérifiés uniquement",
- "tr": "Yalnızca doğrulanmış modeller",
- "de": "Nur verifizierte Modelle",
- "ca": "Només models verificats",
- "uk": "Лише перевірені моделі"
+ "SETTINGS$ADD_MODELS_CONNECTION_BOUND": {
+ "en": "Linked to {{provider}} — profiles inherit this connection's key",
+ "ja": "{{provider}} にリンク — プロファイルはこの接続のキーを引き継ぎます",
+ "zh-CN": "已链接到 {{provider}} — 配置文件将继承此连接的密钥",
+ "zh-TW": "已連結至 {{provider}} — 設定檔將繼承此連線的金鑰",
+ "ko-KR": "{{provider}}에 연결됨 — 프로필이 이 연결의 키를 상속합니다",
+ "no": "Koblet til {{provider}} — profilene arver denne tilkoblingens nøkkel",
+ "it": "Collegato a {{provider}} — i profili ereditano la chiave di questa connessione",
+ "pt": "Vinculado a {{provider}} — os perfis herdam a chave desta conexão",
+ "es": "Vinculado a {{provider}} — los perfiles heredan la clave de esta conexión",
+ "ar": "مرتبط بـ {{provider}} — ترث الملفات الشخصية مفتاح هذا الاتصال",
+ "fr": "Lié à {{provider}} — les profils héritent de la clé de cette connexion",
+ "tr": "{{provider}} ile bağlandı — profiller bu bağlantının anahtarını miras alır",
+ "de": "Verknüpft mit {{provider}} — Profile erben den Schlüssel dieser Verbindung",
+ "ca": "Vinculat a {{provider}} — els perfils hereten la clau d'aquesta connexió",
+ "uk": "Прив'язано до {{provider}} — профілі успадковують ключ цього з'єднання"
},
"SETTINGS$ADD_N_PROFILES": {
"en": "Add {{count}} profiles",
@@ -42958,6 +42992,23 @@
"zh-CN": "编辑提供商连接",
"zh-TW": "編輯提供者連線"
},
+ "SETTINGS$PROVIDER_CONNECTION_MENU": {
+ "ar": "قائمة اتصال المزود",
+ "ca": "Menú de connexió de proveïdor",
+ "de": "Anbieterverbindungsmenü",
+ "en": "Provider connection menu",
+ "es": "Menú de conexión de proveedor",
+ "fr": "Menu de connexion fournisseur",
+ "it": "Menu connessione provider",
+ "ja": "プロバイダー接続メニュー",
+ "ko-KR": "공급자 연결 메뉴",
+ "no": "Leverandørtilkoblingsmeny",
+ "pt": "Menu de conexão de provedor",
+ "tr": "Sağlayıcı bağlantı menüsü",
+ "uk": "Меню підключення постачальника",
+ "zh-CN": "提供商连接菜单",
+ "zh-TW": "提供者連線選單"
+ },
"SETTINGS$PROVIDER_CONNECTION_MODEL_COUNT": {
"ar": "{{count}} نموذج",
"ca": "{{count}} model(s)",
@@ -43281,6 +43332,23 @@
"tr": "Erişilebilir çalışma alanı yok. Yöneticinizden erişim izinlerinizi kontrol etmesini isteyin.",
"uk": "Немає доступних робочих просторів. Попросіть адміністратора перевірити ваші права доступу."
},
+ "SETTINGS$PROVIDER_CONNECTION_BULK_ADD": {
+ "ar": "إضافة جماعية",
+ "ca": "Afegir en lot",
+ "de": "Massen hinzufügen",
+ "en": "Bulk add",
+ "es": "Añadir en lote",
+ "fr": "Ajout groupé",
+ "it": "Aggiungi in blocco",
+ "ja": "一括追加",
+ "ko-KR": "일괄 추가",
+ "no": "Legg til flere",
+ "pt": "Adicionar em lote",
+ "tr": "Toplu ekle",
+ "uk": "Масове додавання",
+ "zh-CN": "批量添加",
+ "zh-TW": "批次新增"
+ },
"HOME$LETS_START_BUILDING": {
"en": "Let's Start Building!",
"ja": "開発を始めましょう!",