🙌 OpenHands: AI-Driven Development
feat(settings): bulk-add provider models as LLM profiles (#16426)
george larson47a10808d785
diff --git a/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx b/__tests__/components/settings/llm-profiles/add-models-modal.test.tsxnew file mode 100644index 0000000000..07a102128d--- /dev/null+++ b/__tests__/components/settings/llm-profiles/add-models-modal.test.tsx@@ -0,0 +1,520 @@+import { render, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi, beforeEach } from "vitest";+import userEvent from "@testing-library/user-event";+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 ConfigService from "#/api/config-service/config-service.api";+import { displayErrorToast } from "#/utils/custom-toast-handlers";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, params?: Record<string, string>) => {+ const translations: Record<string, string> = {+ 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_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`,+ SETTINGS$MODELS_ADD_BLOCKED: `Added ${params?.added ?? "?"} profiles; the server refused the rest`,+ SETTINGS$MODEL_ROW_SAVED: "Saved",+ SETTINGS$MODEL_ROW_FAILED: "Failed",+ BUTTON$CANCEL: "Cancel",+ ERROR$GENERIC: "An error occurred",+ };+ return translations[key] || key;+ },+ }),+}));++vi.mock("#/api/profiles-service/profiles-service.api");+vi.mock("#/api/config-service/config-service.api");++// The provider/model hooks hydrate a verified-models map through the active+// backend's LLMMetadataClient; in tests there is no backend, so stub the map.+vi.mock("#/hooks/query/use-verified-models", async (importOriginal) => {+ const orig =+ await importOriginal<typeof import("#/hooks/query/use-verified-models")>();+ return {+ ...orig,+ fetchVerifiedModelsByProvider: vi.fn().mockResolvedValue({}),+ };+});++vi.mock("#/utils/custom-toast-handlers", () => ({+ displaySuccessToast: vi.fn(),+ 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+ * with a plain-text or detail-less body leaves nothing for the modal to quote.+ */+const httpError = (status: number, detail?: string) => {+ const error = new Error(detail ?? `HTTP ${status}`);+ error.name = "HttpError";+ return Object.assign(error, {+ status,+ response: detail === undefined ? null : { detail },+ });+};++const MODELS = {+ items: [+ { provider: "openhands", name: "trinity-large-thinking", verified: true },+ { provider: "openhands", name: "deepseek-v4-flash", verified: true },+ { provider: "openhands", name: "unverified-model", verified: false },+ ],+ next_page_id: null,+};++describe("AddModelsModal", () => {+ let queryClient: QueryClient;++ const renderModal = (existingNames: string[] = [], onClose = vi.fn()) => {+ const view = render(+ <QueryClientProvider client={queryClient}>+ <AddModelsModal+ isOpen+ existingNames={existingNames}+ onClose={onClose}+ />+ </QueryClientProvider>,+ );+ // The manager renders the modal unconditionally and drives it with+ // `isOpen`, so the component never unmounts between openings.+ const setOpen = (isOpen: boolean) =>+ view.rerender(+ <QueryClientProvider client={queryClient}>+ <AddModelsModal+ isOpen={isOpen}+ existingNames={existingNames}+ onClose={onClose}+ />+ </QueryClientProvider>,+ );+ return { ...view, setOpen };+ };++ const showUnverified = async () => {+ await userEvent.click(screen.getByTestId("add-models-verified-only"));+ await screen.findByTestId("add-models-row-openhands/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");+ };++ beforeEach(() => {+ vi.clearAllMocks();+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ 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",+ );+ 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"),+ ).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 () => {+ 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");+ });++ 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 },+ ],+ next_page_id: null,+ });+ 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");+ });++ it("says the provider is empty when it really has no models", async () => {+ vi.mocked(ConfigService.searchModels).mockResolvedValue({+ items: [],+ 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");++ 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"));+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(+ "Add 1 profiles",+ );+ });++ it("selects nothing until the user chooses", async () => {+ renderModal();+ await pickProvider();+ await screen.findByTestId(+ "add-models-row-openhands/trinity-large-thinking",+ );++ expect(+ screen.getByTestId("add-models-check-openhands/trinity-large-thinking"),+ ).not.toBeChecked();+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(+ "Add 0 profiles",+ );+ expect(screen.getByTestId("add-models-submit")).toBeDisabled();+ });++ it("groups unverified providers under a separate divider", async () => {+ 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);+ 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"]);+ });++ it("creates one profile per selected model, keyless", async () => {+ const onClose = vi.fn();+ renderModal([], onClose);+ await pickProvider();+ await screen.findByTestId(+ "add-models-row-openhands/trinity-large-thinking",+ );++ // pick one; only that one is created+ await userEvent.click(+ screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),+ );+ 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,+ },+ );+ });++ 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"));+ renderModal([], onClose);+ await pickProvider();+ await screen.findByTestId(+ "add-models-row-openhands/trinity-large-thinking",+ );++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ 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);+ });++ it("stops the run and reports the server's reason when it refuses with 409", async () => {+ const onClose = vi.fn();+ 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",+ );+ await showUnverified();++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ await userEvent.click(screen.getByTestId("add-models-submit"));++ await waitFor(() =>+ expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),+ );+ // A second refusal confirms the wall; the third row is never attempted.+ expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(2);+ expect(displayErrorToast).toHaveBeenCalledWith(+ "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" });+ renderModal();+ await pickProvider();+ await screen.findByTestId(+ "add-models-row-openhands/trinity-large-thinking",+ );++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ 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(displayErrorToast).toHaveBeenCalledWith(+ "Added 1 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 showUnverified();++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ await userEvent.click(screen.getByTestId("add-models-submit"));++ await waitFor(() =>+ expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),+ );+ expect(displayErrorToast).toHaveBeenCalledWith(+ "Added 0 profiles; the server refused the rest",+ );+ expect(displayErrorToast).not.toHaveBeenCalledWith(+ "Profile 'x' already exists.",+ );+ });++ 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 showUnverified();++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ await userEvent.click(screen.getByTestId("add-models-submit"));++ await waitFor(() =>+ expect(screen.getByTestId("add-models-submit")).not.toBeDisabled(),+ );+ expect(displayErrorToast).toHaveBeenCalledWith(+ "Added 0 profiles; the server refused the rest",+ );+ });++ it("keeps selections and edited names across a filter toggle", async () => {+ 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 showUnverified();++ expect(+ screen.getByTestId("add-models-name-openhands/deepseek-v4-flash"),+ ).toHaveValue("my-flash");+ expect(+ screen.getByTestId("add-models-check-openhands/deepseek-v4-flash"),+ ).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 userEvent.click(screen.getByTestId("add-models-submit"));+ await waitFor(() => expect(screen.getAllByText("Failed")).toHaveLength(2));++ 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",+ );++ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(+ "Add 0 profiles",+ );+ expect(screen.getByTestId("add-models-submit")).toBeDisabled();++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(+ "Add 2 profiles",+ );++ await userEvent.click(screen.getByTestId("add-models-select-all"));+ expect(screen.getByTestId("add-models-submit")).toHaveTextContent(+ "Add 0 profiles",+ );+ });+});diff --git a/src/components/features/settings/llm-profiles/add-models-modal.tsx b/src/components/features/settings/llm-profiles/add-models-modal.tsxnew file mode 100644index 0000000000..32d6eb5f19--- /dev/null+++ b/src/components/features/settings/llm-profiles/add-models-modal.tsx@@ -0,0 +1,432 @@+import { useEffect, useMemo, 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 { 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 {+ 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+ ?.detail;+ return typeof detail === "string" && detail.trim() ? detail : null;+}++interface AddModelsModalProps {+ isOpen: boolean;+ existingNames: string[];+ onClose: () => void;+}++type RowStatus = "idle" | "saving" | "saved" | "failed";++interface ModelRow {+ /** Full model id, e.g. "openhands/deepseek-v4-flash". */+ model: string;+ /** Editable profile name. */+ name: string;+ verified: boolean;+ selected: boolean;+ status: RowStatus;+}++/**+ * 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.+ */+export function AddModelsModal({+ isOpen,+ existingNames,+ onClose,+}: AddModelsModalProps) {+ const { t } = useTranslation("openhands");+ const [provider, setProvider] = useState<string | null>(null);+ const [verifiedOnly, setVerifiedOnly] = useState(true);+ const [rows, setRows] = useState<ModelRow[]>([]);+ const [submitting, setSubmitting] = useState(false);++ const providers = useSearchProviders();+ const models = useProviderModels(provider);+ 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.+ useEffect(() => {+ const items = models.data ?? [];+ setRows((prev) => {+ const prior = new Map(prev.map((row) => [row.model, row]));+ return items.map((m) => {+ const full =+ m.provider && !m.name.startsWith(`${m.provider}/`)+ ? `${m.provider}/${m.name}`+ : m.name;+ const verified = !!m.verified;+ 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,+ };+ });+ });+ }, [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.+ useEffect(() => {+ if (!isOpen) {+ setProvider(null);+ setVerifiedOnly(true);+ setRows([]);+ setSubmitting(false);+ }+ }, [isOpen]);++ 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;++ const isSelectable = (row: ModelRow) =>+ !hasConflict(row) && isProfileNameValid(row.name, { isRequired: true });+ const selectable = visibleRows.filter(isSelectable);+ const selectedRows = selectable.filter((row) => row.selected);++ const setRow = (model: string, patch: Partial<ModelRow>) =>+ setRows((prev) =>+ prev.map((row) => (row.model === model ? { ...row, ...patch } : row)),+ );++ const allSelected =+ selectable.length > 0 && selectedRows.length === selectable.length;++ const toggleAll = () => {+ const next = !allSelected;+ const reachable = new Set(selectable.map((row) => row.model));+ setRows((prev) =>+ prev.map((row) =>+ reachable.has(row.model) ? { ...row, selected: next } : row,+ ),+ );+ };++ const handleSubmit = async () => {+ setSubmitting(true);+ const targets = selectedRows;+ for (const row of targets) setRow(row.model, { status: "saving" });++ // Sequential, not a parallel fan-out: the server enforces a profile limit,+ // and firing every create at once turns one refusal into a wall of+ // identical failures.+ //+ // A 409 is ambiguous. It means the profile ceiling, which every remaining+ // create would hit too — or a name taken since this list loaded, which+ // says nothing about the rows behind it. Stopping on the first one halts+ // a run that would have succeeded; ignoring it spends the whole selection+ // against a wall. So one 409 fails its own row and the run continues, and+ // a second confirms the wall at a cost of exactly one extra request.+ let added = 0;+ let failed = 0;+ let conflicts = 0;+ let blocked = false;+ let blockedReason: string | null = null;++ for (const [i, row] of targets.entries()) {+ try {+ await saveProfile.mutateAsync({+ name: row.name,+ request: {+ llm: { model: row.model } as SaveProfileRequest["llm"],+ include_secrets: false,+ },+ });+ setRow(row.model, { status: "saved" });+ added += 1;+ } catch (error) {+ // Surface the server's reason — a silent "failed" row is undebuggable.+ console.error(`profile create failed for ${row.model}:`, error);+ setRow(row.model, { status: "failed" });+ failed += 1;+ if (isSdkHttpStatusError(error, 409)) {+ conflicts += 1;+ if (conflicts >= 2) {+ blocked = true;+ // Read the reason off the refusal that actually stopped the run.+ // Carrying an earlier 409's detail forward would report a raced+ // duplicate name as the cause of a halt it had nothing to do with.+ blockedReason = getServerDetail(error);+ // Rows past this one were marked "saving" up front and are now+ // never attempted; leave them idle rather than spinning forever.+ for (const skipped of targets.slice(i + 1)) {+ setRow(skipped.model, { status: "idle" });+ }+ break;+ }+ }+ }+ }++ setSubmitting(false);+ if (blocked) {+ // Quote the server when it explained itself. When it did not, say so+ // plainly: the partial-count wording below counts only the rows that+ // were attempted, so it reads as a smaller failure than it was.+ displayErrorToast(+ blockedReason ??+ t(I18nKey.SETTINGS$MODELS_ADD_BLOCKED, { added: String(added) }),+ );+ } else if (failed === 0) {+ displaySuccessToast(+ t(I18nKey.SETTINGS$MODELS_ADDED, { count: String(added) }),+ );+ onClose();+ } else {+ displayErrorToast(+ t(I18nKey.SETTINGS$MODELS_ADDED_PARTIAL, {+ added: String(added),+ failed: String(failed),+ }),+ );+ }+ };++ const handleClose = () => {+ 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 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;++ const footer = (+ <>+ <BrandButton+ type="button"+ variant="tertiary"+ onClick={handleClose}+ isDisabled={submitting}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="add-models-submit"+ type="button"+ variant="primary"+ onClick={handleSubmit}+ isDisabled={submitting || selectedRows.length === 0}+ >+ {submitting ? (+ <LoadingSpinner size="small" />+ ) : (+ t(I18nKey.SETTINGS$ADD_N_PROFILES, {+ count: String(selectedRows.length),+ })+ )}+ </BrandButton>+ </>+ );++ return (+ <ApiKeyModalBase+ isOpen+ title={t(I18nKey.SETTINGS$ADD_MODELS_TITLE)}+ footer={footer}+ 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">+ {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)}+ 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>+ )}+ </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)}+ disabled={submitting}+ />+ {t(I18nKey.SETTINGS$ADD_MODELS_VERIFIED_ONLY)}+ </label>+ )}++ {isLoadingModels && (+ <div data-testid="add-models-loading" className="py-4 text-center">+ <LoadingSpinner size="small" />+ </div>+ )}++ {showEmpty && (+ <p+ data-testid="add-models-empty"+ className="text-sm text-[var(--oh-muted)]"+ >+ {t(emptyMessage)}+ </p>+ )}++ {visibleRows.length > 0 && (+ <>+ <label className="flex items-center gap-2 text-sm text-white">+ <input+ data-testid="add-models-select-all"+ type="checkbox"+ checked={allSelected}+ onChange={toggleAll}+ disabled={submitting || selectable.length === 0}+ />+ {t(I18nKey.SETTINGS$ADD_MODELS_SELECT_ALL)}+ </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";+ return (+ <li+ key={row.model}+ data-testid={`add-models-row-${row.model}`}+ className="flex items-center gap-2"+ >+ <input+ data-testid={`add-models-check-${row.model}`}+ type="checkbox"+ checked={row.selected && !conflict}+ onChange={(e) =>+ setRow(row.model, { selected: e.target.checked })+ }+ disabled={disabled || !valid}+ />+ <span+ className="min-w-0 flex-1 truncate text-sm text-white"+ title={row.model}+ >+ {row.model}+ </span>+ {row.status === "saving" && <LoadingSpinner size="small" />}+ {row.status === "saved" && (+ <span className="text-xs text-green-400">+ {t(I18nKey.SETTINGS$MODEL_ROW_SAVED)}+ </span>+ )}+ {row.status === "failed" && (+ <span className="text-xs text-red-400">+ {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>+ );+ })}+ </ul>+ </>+ )}+ </div>+ </ApiKeyModalBase>+ );+}diff --git a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsxindex dab1bca6ca..12ce71569b 100644--- a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx+++ b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx@@ -3,6 +3,7 @@ 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 { AddModelsModal } from "./add-models-modal";import { ProfilesBody } from "./profiles-body";import { ProviderConnectionsManager } from "./provider-connections-manager";import ProfilesService, {@@ -56,6 +57,7 @@ export function LlmProfilesManager({const [profileToDelete, setProfileToDelete] = useState<ProfileInfo | null>(null,);+ const [showAddModels, setShowAddModels] = useState(false);const profiles = data?.profiles ?? [];const active = data?.active_profile ?? null;@@ -132,15 +134,25 @@ export function LlmProfilesManager({{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>+ <>+ <BrandButton+ testId="add-models-from-provider"+ type="button"+ variant="tertiary"+ className="ml-auto"+ onClick={() => setShowAddModels(true)}+ >+ {t(I18nKey.SETTINGS$ADD_MODELS_FROM_PROVIDER)}+ </BrandButton>+ <BrandButton+ testId="add-llm-profile"+ type="button"+ variant="secondary"+ onClick={onAddProfile}+ >+ {t(I18nKey.SETTINGS$ADD_LLM_PROFILE)}+ </BrandButton>+ </>) : null}</div>@@ -179,6 +191,11 @@ export function LlmProfilesManager({profile={profileToDelete}onClose={() => setProfileToDelete(null)}/>+ <AddModelsModal+ isOpen={showAddModels}+ existingNames={profiles.map((p) => p.name)}+ onClose={() => setShowAddModels(false)}+ /></>);}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 921b7450a3..381b206e5e 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -31808,6 +31808,244 @@"uk": "Назад","ca": "Tornar"},+ "SETTINGS$ADD_MODELS_EMPTY": {+ "en": "No models found for this provider.",+ "ja": "このプロバイダーのモデルが見つかりません。",+ "zh-CN": "未找到此提供商的模型。",+ "zh-TW": "找不到此供應商的模型。",+ "ko-KR": "이 제공업체의 모델을 찾을 수 없습니다.",+ "no": "Ingen modeller funnet for denne leverandøren.",+ "it": "Nessun modello trovato per questo provider.",+ "pt": "Nenhum modelo encontrado para este provedor.",+ "es": "No se encontraron modelos para este proveedor.",+ "ar": "لم يتم العثور على نماذج لهذا المزوّد.",+ "fr": "Aucun modèle trouvé pour ce fournisseur.",+ "tr": "Bu sağlayıcı için model bulunamadı.",+ "de": "Keine Modelle für diesen Anbieter gefunden.",+ "ca": "No s'han trobat models per a aquest proveïdor.",+ "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": "Ім'я вже існує"+ },+ "SETTINGS$ADD_MODELS_PROVIDER_LABEL": {+ "en": "Provider",+ "ja": "プロバイダー",+ "zh-CN": "提供商",+ "zh-TW": "供應商",+ "ko-KR": "제공업체",+ "no": "Leverandør",+ "it": "Provider",+ "pt": "Provedor",+ "es": "Proveedor",+ "ar": "المزوّد",+ "fr": "Fournisseur",+ "tr": "Sağlayıcı",+ "de": "Anbieter",+ "ca": "Proveïdor",+ "uk": "Постачальник"+ },+ "SETTINGS$ADD_MODELS_PROVIDER_PLACEHOLDER": {+ "en": "Select a provider",+ "ja": "プロバイダーを選択",+ "zh-CN": "选择提供商",+ "zh-TW": "選擇供應商",+ "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": "Виберіть постачальника"+ },+ "SETTINGS$ADD_MODELS_SELECT_ALL": {+ "en": "Select all",+ "ja": "すべて選択",+ "zh-CN": "全选",+ "zh-TW": "全選",+ "ko-KR": "모두 선택",+ "no": "Velg alle",+ "it": "Seleziona tutto",+ "pt": "Selecionar tudo",+ "es": "Seleccionar todo",+ "ar": "تحديد الكل",+ "fr": "Tout sélectionner",+ "tr": "Tümünü seç",+ "de": "Alle auswählen",+ "ca": "Selecciona-ho tot",+ "uk": "Вибрати все"+ },+ "SETTINGS$ADD_MODELS_TITLE": {+ "en": "Add models as profiles",+ "ja": "モデルをプロファイルとして追加",+ "zh-CN": "将模型添加为配置文件",+ "zh-TW": "將模型新增為設定檔",+ "ko-KR": "모델을 프로필로 추가",+ "no": "Legg til modeller som profiler",+ "it": "Aggiungi modelli come profili",+ "pt": "Adicionar modelos como perfis",+ "es": "Añadir modelos como perfiles",+ "ar": "إضافة النماذج كملفات شخصية",+ "fr": "Ajouter des modèles comme profils",+ "tr": "Modelleri profil olarak ekle",+ "de": "Modelle als Profile hinzufügen",+ "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_N_PROFILES": {+ "en": "Add {{count}} profiles",+ "ja": "{{count}} 件のプロファイルを追加",+ "zh-CN": "添加 {{count}} 个配置文件",+ "zh-TW": "新增 {{count}} 個設定檔",+ "ko-KR": "프로필 {{count}}개 추가",+ "no": "Legg til {{count}} profiler",+ "it": "Aggiungi {{count}} profili",+ "pt": "Adicionar {{count}} perfis",+ "es": "Añadir {{count}} perfiles",+ "ar": "إضافة {{count}} ملفات شخصية",+ "fr": "Ajouter {{count}} profils",+ "tr": "{{count}} profil ekle",+ "de": "{{count}} Profile hinzufügen",+ "ca": "Afegeix {{count}} perfils",+ "uk": "Додати {{count}} профілів"+ },+ "SETTINGS$MODELS_ADDED": {+ "en": "Added {{count}} profiles",+ "ja": "{{count}} 件のプロファイルを追加しました",+ "zh-CN": "已添加 {{count}} 个配置文件",+ "zh-TW": "已新增 {{count}} 個設定檔",+ "ko-KR": "프로필 {{count}}개를 추가했습니다",+ "no": "La til {{count}} profiler",+ "it": "Aggiunti {{count}} profili",+ "pt": "{{count}} perfis adicionados",+ "es": "{{count}} perfiles añadidos",+ "ar": "تمت إضافة {{count}} ملفات شخصية",+ "fr": "{{count}} profils ajoutés",+ "tr": "{{count}} profil eklendi",+ "de": "{{count}} Profile hinzugefügt",+ "ca": "S'han afegit {{count}} perfils",+ "uk": "Додано {{count}} профілів"+ },+ "SETTINGS$MODELS_ADDED_PARTIAL": {+ "en": "Added {{added}} profiles; {{failed}} failed",+ "ja": "{{added}} 件追加、{{failed}} 件失敗",+ "zh-CN": "已添加 {{added}} 个配置文件;{{failed}} 个失败",+ "zh-TW": "已新增 {{added}} 個設定檔;{{failed}} 個失敗",+ "ko-KR": "{{added}}개 추가, {{failed}}개 실패",+ "no": "La til {{added}} profiler; {{failed}} mislyktes",+ "it": "Aggiunti {{added}} profili; {{failed}} non riusciti",+ "pt": "{{added}} perfis adicionados; {{failed}} falharam",+ "es": "{{added}} perfiles añadidos; {{failed}} fallaron",+ "ar": "تمت إضافة {{added}}؛ فشل {{failed}}",+ "fr": "{{added}} profils ajoutés ; {{failed}} échoués",+ "tr": "{{added}} profil eklendi; {{failed}} başarısız",+ "de": "{{added}} Profile hinzugefügt; {{failed}} fehlgeschlagen",+ "ca": "S'han afegit {{added}} perfils; {{failed}} han fallat",+ "uk": "Додано {{added}} профілів; {{failed}} не вдалося"+ },+ "SETTINGS$MODELS_ADD_BLOCKED": {+ "en": "Added {{added}} profiles; the server refused the rest",+ "ja": "{{added}} 件追加、残りはサーバーに拒否されました",+ "zh-CN": "已添加 {{added}} 个配置文件;服务器拒绝了其余的",+ "zh-TW": "已新增 {{added}} 個設定檔;伺服器拒絕了其餘的",+ "ko-KR": "{{added}}개 추가, 나머지는 서버가 거부했습니다",+ "no": "La til {{added}} profiler; serveren avviste resten",+ "it": "Aggiunti {{added}} profili; il server ha rifiutato il resto",+ "pt": "{{added}} perfis adicionados; o servidor recusou os restantes",+ "es": "{{added}} perfiles añadidos; el servidor rechazó el resto",+ "ar": "تمت إضافة {{added}}؛ رفض الخادم البقية",+ "fr": "{{added}} profils ajoutés ; le serveur a refusé les autres",+ "tr": "{{added}} profil eklendi; sunucu geri kalanı reddetti",+ "de": "{{added}} Profile hinzugefügt; den Rest hat der Server abgelehnt",+ "ca": "S'han afegit {{added}} perfils; el servidor ha rebutjat la resta",+ "uk": "Додано {{added}} профілів; решту сервер відхилив"+ },+ "SETTINGS$MODEL_ROW_FAILED": {+ "en": "Failed",+ "ja": "失敗",+ "zh-CN": "失败",+ "zh-TW": "失敗",+ "ko-KR": "실패",+ "no": "Mislyktes",+ "it": "Non riuscito",+ "pt": "Falhou",+ "es": "Falló",+ "ar": "فشل",+ "fr": "Échec",+ "tr": "Başarısız",+ "de": "Fehlgeschlagen",+ "ca": "Ha fallat",+ "uk": "Не вдалося"+ },+ "SETTINGS$MODEL_ROW_SAVED": {+ "en": "Saved",+ "ja": "保存済み",+ "zh-CN": "已保存",+ "zh-TW": "已儲存",+ "ko-KR": "저장됨",+ "no": "Lagret",+ "it": "Salvato",+ "pt": "Salvo",+ "es": "Guardado",+ "ar": "تم الحفظ",+ "fr": "Enregistré",+ "tr": "Kaydedildi",+ "de": "Gespeichert",+ "ca": "Desat",+ "uk": "Збережено"+ },"SETTINGS$ADD_LLM_PROFILE": {"en": "Add LLM Profile","ja": "LLMプロファイルを追加",