🙌 OpenHands: AI-Driven Development
feat(settings): add saved LLM profiles (FE) - OSS (#14149)
Vasco Schiavobcc175b7d40a
diff --git a/frontend/__tests__/api/profiles-service.test.ts b/frontend/__tests__/api/profiles-service.test.tsnew file mode 100644index 0000000000..00b43e580a--- /dev/null+++ b/frontend/__tests__/api/profiles-service.test.ts@@ -0,0 +1,153 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { openHands } from "#/api/open-hands-axios";+import ProfilesService from "#/api/settings-service/profiles-service.api";++vi.mock("#/api/open-hands-axios", () => ({+ openHands: {+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn(),+ },+}));++describe("ProfilesService", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe("listProfiles", () => {+ it("GETs /api/v1/settings/profiles and returns the body", async () => {+ const body = {+ profiles: [+ {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: "openai_gpt-4o",+ };+ vi.mocked(openHands.get).mockResolvedValue({ data: body });++ await expect(ProfilesService.listProfiles()).resolves.toEqual(body);+ expect(openHands.get).toHaveBeenCalledWith("/api/v1/settings/profiles");+ });+ });++ describe("saveProfile", () => {+ it("POSTs the name-encoded URL with the provided request body", async () => {+ vi.mocked(openHands.post).mockResolvedValue({ data: {} });++ await ProfilesService.saveProfile("openai_gpt-4o", {+ include_secrets: true,+ llm: { model: "openai/gpt-4o" },+ });++ expect(openHands.post).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/openai_gpt-4o",+ { include_secrets: true, llm: { model: "openai/gpt-4o" } },+ );+ });++ it("defaults to an empty body when none is provided", async () => {+ vi.mocked(openHands.post).mockResolvedValue({ data: {} });++ await ProfilesService.saveProfile("my-profile");++ expect(openHands.post).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/my-profile",+ {},+ );+ });++ it("URL-encodes the name segment", async () => {+ vi.mocked(openHands.post).mockResolvedValue({ data: {} });++ // Even though the backend rejects "/" in names, any future-legal+ // unicode should survive round-tripping through encodeURIComponent.+ await ProfilesService.saveProfile("my profile");++ expect(openHands.post).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/my%20profile",+ {},+ );+ });+ });++ describe("deleteProfile", () => {+ it("DELETEs the name-encoded URL", async () => {+ vi.mocked(openHands.delete).mockResolvedValue({ data: {} });++ await ProfilesService.deleteProfile("openai_gpt-4o");++ expect(openHands.delete).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/openai_gpt-4o",+ );+ });+ });++ describe("activateProfile", () => {+ it("POSTs to the /activate sub-resource", async () => {+ vi.mocked(openHands.post).mockResolvedValue({ data: {} });++ await ProfilesService.activateProfile("openai_gpt-4o");++ expect(openHands.post).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/openai_gpt-4o/activate",+ );+ });+ });++ describe("renameProfile", () => {+ it("POSTs to /rename with the new_name body", async () => {+ vi.mocked(openHands.post).mockResolvedValue({ data: {} });++ await ProfilesService.renameProfile("old", "new");++ expect(openHands.post).toHaveBeenCalledWith(+ "/api/v1/settings/profiles/old/rename",+ { new_name: "new" },+ );+ });+ });++ describe("error propagation", () => {+ // The hooks that call these methods rely on promise rejection to route+ // errors into mutateWithToast — if a method ever swallows an axios+ // error, toasts stop working and callers lose visibility.+ it("rejects when listProfiles fails", async () => {+ const err = new Error("network down");+ vi.mocked(openHands.get).mockRejectedValue(err);+ await expect(ProfilesService.listProfiles()).rejects.toThrow(+ "network down",+ );+ });++ it("rejects when saveProfile fails", async () => {+ vi.mocked(openHands.post).mockRejectedValue(new Error("409 conflict"));+ await expect(ProfilesService.saveProfile("x")).rejects.toThrow(+ "409 conflict",+ );+ });++ it("rejects when deleteProfile fails", async () => {+ vi.mocked(openHands.delete).mockRejectedValue(new Error("boom"));+ await expect(ProfilesService.deleteProfile("x")).rejects.toThrow("boom");+ });++ it("rejects when activateProfile fails", async () => {+ vi.mocked(openHands.post).mockRejectedValue(new Error("not found"));+ await expect(ProfilesService.activateProfile("x")).rejects.toThrow(+ "not found",+ );+ });++ it("rejects when renameProfile fails", async () => {+ vi.mocked(openHands.post).mockRejectedValue(new Error("already exists"));+ await expect(ProfilesService.renameProfile("a", "b")).rejects.toThrow(+ "already exists",+ );+ });+ });+});diff --git a/frontend/__tests__/components/features/settings/delete-profile-modal.test.tsx b/frontend/__tests__/components/features/settings/delete-profile-modal.test.tsxnew file mode 100644index 0000000000..700f6dc709--- /dev/null+++ b/frontend/__tests__/components/features/settings/delete-profile-modal.test.tsx@@ -0,0 +1,69 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { DeleteProfileModal } from "#/components/features/settings/delete-profile-modal";++const deleteMock = vi.fn();+vi.mock("#/hooks/mutation/use-delete-llm-profile", () => ({+ useDeleteLlmProfile: () => ({ mutateAsync: deleteMock, isPending: false }),+}));++const toastMocks = vi.hoisted(() => ({+ displayErrorToast: vi.fn(),+ displaySuccessToast: vi.fn(),+}));+vi.mock("#/utils/custom-toast-handlers", () => toastMocks);++const profile: LlmProfileSummary = {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+};++beforeEach(() => {+ deleteMock.mockReset().mockResolvedValue(undefined);+ toastMocks.displayErrorToast.mockReset();+ toastMocks.displaySuccessToast.mockReset();+});++describe("DeleteProfileModal", () => {+ it("renders nothing when profile is null", () => {+ const { container } = render(+ <DeleteProfileModal profile={null} onClose={vi.fn()} />,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("renders the confirmation copy interpolated with the profile name", () => {+ render(<DeleteProfileModal profile={profile} onClose={vi.fn()} />);++ expect(+ screen.getByText("SETTINGS$PROFILE_DELETE_CONFIRMATION"),+ ).toBeInTheDocument();+ });++ it("calls deleteProfile and onClose when the user confirms", async () => {+ const onClose = vi.fn();+ render(<DeleteProfileModal profile={profile} onClose={onClose} />);++ await userEvent.click(screen.getByTestId("delete-profile-confirm"));++ expect(deleteMock).toHaveBeenCalledWith("openai_gpt-4o");+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("calls onClose without invoking the mutation on Cancel", async () => {+ const onClose = vi.fn();+ render(<DeleteProfileModal profile={profile} onClose={onClose} />);++ await userEvent.click(+ screen.getByRole("button", { name: "BUTTON$CANCEL" }),+ );++ expect(deleteMock).not.toHaveBeenCalled();+ expect(onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/__tests__/components/features/settings/llm-profiles-manager.test.tsx b/frontend/__tests__/components/features/settings/llm-profiles-manager.test.tsxnew file mode 100644index 0000000000..45217ce17e--- /dev/null+++ b/frontend/__tests__/components/features/settings/llm-profiles-manager.test.tsx@@ -0,0 +1,358 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { LlmProfilesManager } from "#/components/features/settings/llm-profiles-manager";++// Same shape as the service's listProfiles response — redeclared here+// instead of imported because the source type is module-private.+type ProfilesList = {+ profiles: LlmProfileSummary[];+ active_profile: string | null;+};++// State driven by the tests: the mocked useLlmProfiles hook reads from it.+const profilesState: {+ data: ProfilesList | undefined;+ isLoading: boolean;+ error: Error | null;+} = { data: undefined, isLoading: false, error: null };++const saveMock = vi.fn();+const deleteMock = vi.fn();+const activateMock = vi.fn();+const renameMock = vi.fn();++vi.mock("#/hooks/query/use-llm-profiles", async () => {+ const actual = await vi.importActual<+ typeof import("#/hooks/query/use-llm-profiles")+ >("#/hooks/query/use-llm-profiles");+ return {+ ...actual,+ useLlmProfiles: () => profilesState,+ };+});++vi.mock("#/hooks/mutation/use-save-llm-profile", () => ({+ useSaveLlmProfile: () => ({ mutateAsync: saveMock, isPending: false }),+}));+vi.mock("#/hooks/mutation/use-delete-llm-profile", () => ({+ useDeleteLlmProfile: () => ({ mutateAsync: deleteMock, isPending: false }),+}));+vi.mock("#/hooks/mutation/use-activate-llm-profile", () => ({+ useActivateLlmProfile: () => ({+ mutateAsync: activateMock,+ isPending: false,+ }),+}));+vi.mock("#/hooks/mutation/use-rename-llm-profile", () => ({+ useRenameLlmProfile: () => ({ mutateAsync: renameMock, isPending: false }),+}));++const toastMocks = vi.hoisted(() => ({+ displayErrorToast: vi.fn(),+ displaySuccessToast: vi.fn(),+}));+vi.mock("#/utils/custom-toast-handlers", () => toastMocks);++function renderManager({+ onAddProfile,+ onEditProfile,+}: {+ onAddProfile?: () => void;+ onEditProfile?: (profile: LlmProfileSummary) => void;+} = {}) {+ return render(+ <QueryClientProvider client={new QueryClient()}>+ <LlmProfilesManager+ onAddProfile={onAddProfile}+ onEditProfile={onEditProfile}+ />+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ profilesState.data = undefined;+ profilesState.isLoading = false;+ profilesState.error = null;+ saveMock.mockReset().mockResolvedValue(undefined);+ deleteMock.mockReset().mockResolvedValue(undefined);+ activateMock.mockReset().mockResolvedValue(undefined);+ renameMock.mockReset().mockResolvedValue(undefined);+ toastMocks.displayErrorToast.mockReset();+ toastMocks.displaySuccessToast.mockReset();+});++// A realistic two-profile response used by several tests.+const sampleProfiles: ProfilesList = {+ profiles: [+ {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "anthropic_claude",+ model: "anthropic/claude-3-5-sonnet",+ base_url: "https://api.anthropic.com",+ api_key_set: false,+ },+ ],+ active_profile: "openai_gpt-4o",+};++describe("LlmProfilesManager", () => {+ it("shows the Available Profiles heading", () => {+ profilesState.data = sampleProfiles;+ renderManager();++ expect(+ screen.getByText("SETTINGS$AVAILABLE_PROFILES"),+ ).toBeInTheDocument();+ });++ it("renders the Add LLM Profile button when an onAddProfile callback is supplied", async () => {+ profilesState.data = sampleProfiles;+ const onAddProfile = vi.fn();+ renderManager({ onAddProfile });+ const user = userEvent.setup();++ const button = screen.getByTestId("add-llm-profile");+ expect(button).toBeInTheDocument();+ await user.click(button);+ expect(onAddProfile).toHaveBeenCalledTimes(1);+ });++ it("omits the Add LLM Profile button when no callback is provided", () => {+ profilesState.data = sampleProfiles;+ renderManager();++ expect(screen.queryByTestId("add-llm-profile")).not.toBeInTheDocument();+ });++ it("shows the empty-state message when no profiles are saved", () => {+ profilesState.data = { profiles: [], active_profile: null };+ renderManager();++ expect(screen.getByText("SETTINGS$PROFILES_EMPTY")).toBeInTheDocument();+ expect(screen.queryByTestId("profile-row")).not.toBeInTheDocument();+ });++ it("shows the loading spinner while fetching", () => {+ profilesState.isLoading = true;+ renderManager();++ expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();+ });++ it("shows the error message when the query fails", () => {+ profilesState.error = new Error("boom");+ renderManager();++ expect(+ screen.getByText("SETTINGS$PROFILES_LOAD_ERROR"),+ ).toBeInTheDocument();+ });++ it("renders one row per profile and marks the active one with the Active badge", () => {+ profilesState.data = sampleProfiles;+ renderManager();++ const rows = screen.getAllByTestId("profile-row");+ expect(rows).toHaveLength(2);++ const activeRow = rows[0];+ expect(activeRow).toHaveTextContent("openai_gpt-4o");+ expect(activeRow).toHaveTextContent("openai/gpt-4o");+ expect(activeRow).toHaveTextContent("SETTINGS$PROFILE_ACTIVE_BADGE");++ const otherRow = rows[1];+ expect(otherRow).toHaveTextContent("anthropic_claude");+ expect(otherRow).not.toHaveTextContent("SETTINGS$PROFILE_ACTIVE_BADGE");+ });++ it("fires onEditProfile on Edit without activating the profile (inactive row)", async () => {+ profilesState.data = sampleProfiles;+ const onEditProfile = vi.fn();+ renderManager({ onEditProfile });+ const user = userEvent.setup();++ // Open the menu on the inactive (second) row.+ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-edit"));++ // Edit must not activate the profile — activation is reserved for the+ // explicit "Set as active" action and the post-save flow.+ expect(activateMock).not.toHaveBeenCalled();+ expect(onEditProfile).toHaveBeenCalledTimes(1);+ expect(onEditProfile).toHaveBeenCalledWith(sampleProfiles.profiles[1]);+ });++ it("does not activate the profile when Edit is clicked on the active row", async () => {+ profilesState.data = sampleProfiles;+ const onEditProfile = vi.fn();+ renderManager({ onEditProfile });+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ await user.click(screen.getByTestId("profile-edit"));++ expect(activateMock).not.toHaveBeenCalled();+ expect(onEditProfile).toHaveBeenCalledWith(sampleProfiles.profiles[0]);+ });++ it("activates the profile when Set as active is clicked", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-set-active"));++ expect(activateMock).toHaveBeenCalledTimes(1);+ expect(activateMock).toHaveBeenCalledWith("anthropic_claude");+ });++ it("disables Set as active on the already-active row", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ expect(screen.getByTestId("profile-set-active")).toBeDisabled();+ });++ it("opens the rename modal prefilled with the current name", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ await user.click(screen.getByTestId("profile-rename"));++ const input = screen.getByTestId(+ "rename-profile-input",+ ) as HTMLInputElement;+ expect(input.value).toBe("openai_gpt-4o");+ });++ it("calls renameProfile with the trimmed new name", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ await user.click(screen.getByTestId("profile-rename"));++ const input = screen.getByTestId("rename-profile-input");+ await user.clear(input);+ await user.type(input, " my-favourite ");+ await user.click(screen.getByTestId("rename-profile-submit"));++ expect(renameMock).toHaveBeenCalledTimes(1);+ expect(renameMock).toHaveBeenCalledWith({+ name: "openai_gpt-4o",+ newName: "my-favourite",+ });+ });++ it("rejects invalid rename names and does not call the mutation", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ await user.click(screen.getByTestId("profile-rename"));++ const input = screen.getByTestId("rename-profile-input");+ await user.clear(input);+ await user.type(input, "has space");+ expect(screen.getByTestId("rename-profile-submit")).toBeDisabled();+ expect(renameMock).not.toHaveBeenCalled();+ });++ it("opens the delete modal and calls deleteProfile on confirmation", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-delete"));++ expect(screen.getByTestId("delete-profile-confirm")).toBeInTheDocument();+ await user.click(screen.getByTestId("delete-profile-confirm"));++ expect(deleteMock).toHaveBeenCalledTimes(1);+ expect(deleteMock).toHaveBeenCalledWith("anthropic_claude");+ });++ it("closes the delete modal and skips the mutation when Cancel is clicked", async () => {+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-delete"));+ await user.click(screen.getByRole("button", { name: "BUTTON$CANCEL" }));++ expect(deleteMock).not.toHaveBeenCalled();+ expect(+ screen.queryByTestId("delete-profile-confirm"),+ ).not.toBeInTheDocument();+ });++ it("surfaces the server detail on a delete failure and keeps the modal open", async () => {+ deleteMock.mockRejectedValue({+ response: { data: { detail: "Profile 'x' not found" } },+ });+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-delete"));+ await user.click(screen.getByTestId("delete-profile-confirm"));++ expect(toastMocks.displayErrorToast).toHaveBeenCalledWith(+ "Profile 'x' not found",+ );+ expect(screen.getByTestId("delete-profile-confirm")).toBeInTheDocument();+ });++ it("falls back to a generic message when an activate failure has no detail", async () => {+ activateMock.mockRejectedValue({ message: "Network Error" });+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[1]);+ await user.click(screen.getByTestId("profile-set-active"));++ expect(toastMocks.displayErrorToast).toHaveBeenCalledWith("Network Error");+ });++ it("surfaces the server detail on a rename collision and keeps the modal open", async () => {+ renameMock.mockRejectedValue({+ response: { data: { detail: "Profile 'b' already exists" } },+ });+ profilesState.data = sampleProfiles;+ renderManager();+ const user = userEvent.setup();++ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);+ await user.click(screen.getByTestId("profile-rename"));++ const input = screen.getByTestId("rename-profile-input");+ await user.clear(input);+ await user.type(input, "anthropic_claude");+ await user.click(screen.getByTestId("rename-profile-submit"));++ expect(toastMocks.displayErrorToast).toHaveBeenCalledWith(+ "Profile 'b' already exists",+ );+ expect(screen.getByTestId("rename-profile-submit")).toBeInTheDocument();+ });+});diff --git a/frontend/__tests__/components/features/settings/openhands-api-key-help.test.tsx b/frontend/__tests__/components/features/settings/openhands-api-key-help.test.tsxnew file mode 100644index 0000000000..919c4e4698--- /dev/null+++ b/frontend/__tests__/components/features/settings/openhands-api-key-help.test.tsx@@ -0,0 +1,26 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { OpenHandsApiKeyHelp } from "#/components/features/settings/openhands-api-key-help";++describe("OpenHandsApiKeyHelp", () => {+ it("renders the help link with the provided testId", () => {+ render(<OpenHandsApiKeyHelp testId="oh-api-key-help" />);++ expect(screen.getByTestId("oh-api-key-help")).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: "SETTINGS$NAV_API_KEYS" }),+ ).toHaveAttribute("href", "https://app.all-hands.dev/settings/api-keys");+ });++ it("renders the billing info paragraph with the pricing-details link", () => {+ render(<OpenHandsApiKeyHelp testId="oh-api-key-help" />);++ expect(screen.getByText("SETTINGS$LLM_BILLING_INFO")).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: "SETTINGS$SEE_PRICING_DETAILS" }),+ ).toHaveAttribute(+ "href",+ "https://docs.openhands.dev/usage/llms/openhands-llms",+ );+ });+});diff --git a/frontend/__tests__/components/features/settings/profile-actions-menu.test.tsx b/frontend/__tests__/components/features/settings/profile-actions-menu.test.tsxnew file mode 100644index 0000000000..cda8e14bcf--- /dev/null+++ b/frontend/__tests__/components/features/settings/profile-actions-menu.test.tsx@@ -0,0 +1,56 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ProfileActionsMenu } from "#/components/features/settings/profile-actions-menu";++function renderMenu(+ overrides: Partial<React.ComponentProps<typeof ProfileActionsMenu>> = {},+) {+ const props = {+ onEdit: vi.fn(),+ onRename: vi.fn(),+ onSetActive: vi.fn(),+ onDelete: vi.fn(),+ onClose: vi.fn(),+ isActive: false,+ isActivating: false,+ ...overrides,+ };+ return {+ // eslint-disable-next-line react/jsx-props-no-spreading+ ...render(<ProfileActionsMenu {...props} />),+ props,+ };+}++describe("ProfileActionsMenu", () => {+ it("renders edit, rename, set-active, and delete items", () => {+ renderMenu();++ expect(screen.getByTestId("profile-edit")).toBeInTheDocument();+ expect(screen.getByTestId("profile-rename")).toBeInTheDocument();+ expect(screen.getByTestId("profile-set-active")).toBeInTheDocument();+ expect(screen.getByTestId("profile-delete")).toBeInTheDocument();+ });++ it("invokes the matching callback then onClose when an item is clicked", async () => {+ const { props } = renderMenu();+ const user = userEvent.setup();++ await user.click(screen.getByTestId("profile-edit"));+ expect(props.onEdit).toHaveBeenCalledTimes(1);+ expect(props.onClose).toHaveBeenCalledTimes(1);+ });++ it("disables Set as active when the profile is already active", () => {+ renderMenu({ isActive: true });++ expect(screen.getByTestId("profile-set-active")).toBeDisabled();+ });++ it("disables Set as active while an activation is in flight", () => {+ renderMenu({ isActivating: true });++ expect(screen.getByTestId("profile-set-active")).toBeDisabled();+ });+});diff --git a/frontend/__tests__/components/features/settings/profile-name-input.test.tsx b/frontend/__tests__/components/features/settings/profile-name-input.test.tsxnew file mode 100644index 0000000000..8e5d6f2754--- /dev/null+++ b/frontend/__tests__/components/features/settings/profile-name-input.test.tsx@@ -0,0 +1,47 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ProfileNameInput } from "#/components/features/settings/profile-name-input";++describe("ProfileNameInput", () => {+ it("uses the plain Name label by default", () => {+ render(<ProfileNameInput value="" onChange={vi.fn()} />);++ expect(screen.getByText("SETTINGS$NAME")).toBeInTheDocument();+ expect(screen.queryByText(/COMMON\$OPTIONAL/)).not.toBeInTheDocument();+ });++ it("renders an Optional suffix when isOptional is true", () => {+ render(<ProfileNameInput value="" onChange={vi.fn()} isOptional />);++ expect(+ screen.getByText("SETTINGS$NAME (COMMON$OPTIONAL)"),+ ).toBeInTheDocument();+ });++ it("flags the rule paragraph red when the value violates the pattern", () => {+ const { rerender } = render(+ <ProfileNameInput value="ok-name" onChange={vi.fn()} ruleTestId="rule" />,+ );+ expect(screen.getByTestId("rule")).toHaveClass("text-gray-400");++ rerender(+ <ProfileNameInput+ value="has space"+ onChange={vi.fn()}+ ruleTestId="rule"+ />,+ );+ expect(screen.getByTestId("rule")).toHaveClass("text-red-400");+ });++ it("forwards typed input to onChange", async () => {+ const onChange = vi.fn();+ render(+ <ProfileNameInput value="" onChange={onChange} testId="name-input" />,+ );++ await userEvent.type(screen.getByTestId("name-input"), "x");+ expect(onChange).toHaveBeenCalledWith("x");+ });+});diff --git a/frontend/__tests__/components/features/settings/profile-row.test.tsx b/frontend/__tests__/components/features/settings/profile-row.test.tsxnew file mode 100644index 0000000000..781ef0e422--- /dev/null+++ b/frontend/__tests__/components/features/settings/profile-row.test.tsx@@ -0,0 +1,61 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { ProfileRow } from "#/components/features/settings/profile-row";++const profile: LlmProfileSummary = {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+};++function renderRow(+ overrides: Partial<React.ComponentProps<typeof ProfileRow>> = {},+) {+ const props = {+ profile,+ isActive: false,+ onActivate: vi.fn(),+ onEdit: vi.fn(),+ onRename: vi.fn(),+ onDelete: vi.fn(),+ isActivating: false,+ ...overrides,+ };+ return {+ // eslint-disable-next-line react/jsx-props-no-spreading+ ...render(<ProfileRow {...props} />),+ props,+ };+}++describe("ProfileRow", () => {+ it("renders the profile name and model", () => {+ renderRow();++ expect(screen.getByText("openai_gpt-4o")).toBeInTheDocument();+ expect(screen.getByText("openai/gpt-4o")).toBeInTheDocument();+ expect(+ screen.queryByTestId("profile-active-badge"),+ ).not.toBeInTheDocument();+ });++ it("shows the active badge when isActive is true", () => {+ renderRow({ isActive: true });++ expect(screen.getByTestId("profile-active-badge")).toHaveTextContent(+ "SETTINGS$PROFILE_ACTIVE_BADGE",+ );+ });++ it("opens the actions menu when the trigger is clicked", async () => {+ renderRow();+ const user = userEvent.setup();++ expect(screen.queryByTestId("profile-edit")).not.toBeInTheDocument();+ await user.click(screen.getByTestId("profile-menu-trigger"));+ expect(screen.getByTestId("profile-edit")).toBeInTheDocument();+ });+});diff --git a/frontend/__tests__/components/features/settings/profiles-body.test.tsx b/frontend/__tests__/components/features/settings/profiles-body.test.tsxnew file mode 100644index 0000000000..6487522cf6--- /dev/null+++ b/frontend/__tests__/components/features/settings/profiles-body.test.tsx@@ -0,0 +1,89 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { ProfilesBody } from "#/components/features/settings/profiles-body";++const profiles: LlmProfileSummary[] = [+ { name: "p1", model: "openai/gpt-4o", base_url: null, api_key_set: true },+ { name: "p2", model: "anthropic/claude", base_url: null, api_key_set: true },+];++describe("ProfilesBody", () => {+ it("shows a loading spinner while isLoading is true", () => {+ render(+ <ProfilesBody+ isLoading+ loadError={null}+ profiles={[]}+ active={null}+ onActivate={vi.fn()}+ onEdit={vi.fn()}+ onRename={vi.fn()}+ onDelete={vi.fn()}+ isActivating={false}+ />,+ );++ expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();+ });++ it("shows the load-error paragraph when loadError is set", () => {+ render(+ <ProfilesBody+ isLoading={false}+ loadError={new Error("boom")}+ profiles={[]}+ active={null}+ onActivate={vi.fn()}+ onEdit={vi.fn()}+ onRename={vi.fn()}+ onDelete={vi.fn()}+ isActivating={false}+ />,+ );++ expect(+ screen.getByText("SETTINGS$PROFILES_LOAD_ERROR"),+ ).toBeInTheDocument();+ });++ it("shows the empty-state paragraph when no profiles are passed", () => {+ render(+ <ProfilesBody+ isLoading={false}+ loadError={null}+ profiles={[]}+ active={null}+ onActivate={vi.fn()}+ onEdit={vi.fn()}+ onRename={vi.fn()}+ onDelete={vi.fn()}+ isActivating={false}+ />,+ );++ expect(screen.getByText("SETTINGS$PROFILES_EMPTY")).toBeInTheDocument();+ });++ it("renders one ProfileRow per profile and marks the active one", () => {+ render(+ <ProfilesBody+ isLoading={false}+ loadError={null}+ profiles={profiles}+ active="p1"+ onActivate={vi.fn()}+ onEdit={vi.fn()}+ onRename={vi.fn()}+ onDelete={vi.fn()}+ isActivating={false}+ />,+ );++ const rows = screen.getAllByTestId("profile-row");+ expect(rows).toHaveLength(2);+ expect(rows[0]).toHaveTextContent("p1");+ expect(rows[0]).toHaveTextContent("SETTINGS$PROFILE_ACTIVE_BADGE");+ expect(rows[1]).not.toHaveTextContent("SETTINGS$PROFILE_ACTIVE_BADGE");+ });+});diff --git a/frontend/__tests__/components/features/settings/rename-profile-modal.test.tsx b/frontend/__tests__/components/features/settings/rename-profile-modal.test.tsxnew file mode 100644index 0000000000..d76337f820--- /dev/null+++ b/frontend/__tests__/components/features/settings/rename-profile-modal.test.tsx@@ -0,0 +1,87 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi, beforeEach } from "vitest";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { RenameProfileModal } from "#/components/features/settings/rename-profile-modal";++const renameMock = vi.fn();+vi.mock("#/hooks/mutation/use-rename-llm-profile", () => ({+ useRenameLlmProfile: () => ({ mutateAsync: renameMock, isPending: false }),+}));++const toastMocks = vi.hoisted(() => ({+ displayErrorToast: vi.fn(),+ displaySuccessToast: vi.fn(),+}));+vi.mock("#/utils/custom-toast-handlers", () => toastMocks);++const profile: LlmProfileSummary = {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+};++beforeEach(() => {+ renameMock.mockReset().mockResolvedValue(undefined);+ toastMocks.displayErrorToast.mockReset();+ toastMocks.displaySuccessToast.mockReset();+});++describe("RenameProfileModal", () => {+ it("renders nothing when profile is null", () => {+ const { container } = render(+ <RenameProfileModal profile={null} onClose={vi.fn()} />,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("prefills the input with the current profile name", () => {+ render(<RenameProfileModal profile={profile} onClose={vi.fn()} />);++ const input = screen.getByTestId(+ "rename-profile-input",+ ) as HTMLInputElement;+ expect(input.value).toBe("openai_gpt-4o");+ });++ it("submits the trimmed new name and closes on success", async () => {+ const onClose = vi.fn();+ render(<RenameProfileModal profile={profile} onClose={onClose} />);+ const user = userEvent.setup();++ const input = screen.getByTestId("rename-profile-input");+ await user.clear(input);+ await user.type(input, " new_name ");+ await user.click(screen.getByTestId("rename-profile-submit"));++ expect(renameMock).toHaveBeenCalledWith({+ name: "openai_gpt-4o",+ newName: "new_name",+ });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("disables submit and skips the mutation when the input is invalid", async () => {+ render(<RenameProfileModal profile={profile} onClose={vi.fn()} />);+ const user = userEvent.setup();++ const input = screen.getByTestId("rename-profile-input");+ await user.clear(input);+ await user.type(input, "has space");++ expect(screen.getByTestId("rename-profile-submit")).toBeDisabled();+ expect(renameMock).not.toHaveBeenCalled();+ });++ it("closes without renaming when the name is unchanged", async () => {+ const onClose = vi.fn();+ render(<RenameProfileModal profile={profile} onClose={onClose} />);++ await userEvent.click(screen.getByTestId("rename-profile-submit"));++ expect(renameMock).not.toHaveBeenCalled();+ expect(onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx b/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsxindex e574b03598..6acc8a6920 100644--- a/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx+++ b/frontend/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx@@ -613,6 +613,28 @@ describe("SdkSectionPage", () => {});});+ it("renders trailingActions after the view toggle buttons", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSavableSettings(),+ );++ renderSdkSectionPage({+ sectionKeys: ["llm"],+ trailingActions: (+ <button type="button" data-testid="trailing-action">+ Extra+ </button>+ ),+ });++ // The slot has no view toggles (buildSavableSettings schema has only a+ // critical field), so this also locks the behavior that trailingActions+ // alone is enough to force the strip to render.+ expect(+ await screen.findByTestId("trailing-action"),+ ).toBeInTheDocument();+ });+it("allows saving custom payloads when only external state is dirty", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());const saveSettingsSpy = vidiff --git a/frontend/__tests__/hooks/profiles-hooks.test.tsx b/frontend/__tests__/hooks/profiles-hooks.test.tsxnew file mode 100644index 0000000000..ec20a31eeb--- /dev/null+++ b/frontend/__tests__/hooks/profiles-hooks.test.tsx@@ -0,0 +1,259 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import ProfilesService from "#/api/settings-service/profiles-service.api";+import {+ LLM_PROFILES_QUERY_KEY,+ useLlmProfiles,+} from "#/hooks/query/use-llm-profiles";+import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";+import { useDeleteLlmProfile } from "#/hooks/mutation/use-delete-llm-profile";+import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";+import { useRenameLlmProfile } from "#/hooks/mutation/use-rename-llm-profile";++vi.mock("#/api/settings-service/profiles-service.api", () => ({+ default: {+ listProfiles: vi.fn(),+ saveProfile: vi.fn(),+ deleteProfile: vi.fn(),+ activateProfile: vi.fn(),+ renameProfile: vi.fn(),+ },+}));++// Controlled per-test so one case can flip authentication off and assert+// the query is gated.+const authState: { data: boolean } = { data: true };+vi.mock("#/hooks/query/use-is-authed", () => ({+ useIsAuthed: () => authState,+}));++function makeClient() {+ return new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+}++function wrapperFor(client: QueryClient) {+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ authState.data = true;+});++describe("useLlmProfiles", () => {+ it("fetches the list via ProfilesService.listProfiles", async () => {+ const body = {+ profiles: [+ {+ name: "openai_gpt-4o",+ model: "openai/gpt-4o",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: "openai_gpt-4o",+ };+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue(body);++ const { result } = renderHook(() => useLlmProfiles(), {+ wrapper: wrapperFor(makeClient()),+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(result.current.data).toEqual(body);+ expect(ProfilesService.listProfiles).toHaveBeenCalledTimes(1);+ });++ it("does not fetch while the user is unauthenticated", async () => {+ authState.data = false;++ const { result } = renderHook(() => useLlmProfiles(), {+ wrapper: wrapperFor(makeClient()),+ });+ // Give react-query a tick to settle — if it were going to fetch, it+ // would have called the service by now.+ await new Promise((r) => {+ setTimeout(r, 0);+ });+ expect(ProfilesService.listProfiles).not.toHaveBeenCalled();+ expect(result.current.fetchStatus).toBe("idle");+ });+});++describe("useSaveLlmProfile", () => {+ it("calls saveProfile and invalidates the profiles query on success", async () => {+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue();+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useSaveLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await result.current.mutateAsync({+ name: "my-profile",+ request: { include_secrets: true, llm: { model: "openai/gpt-4o" } },+ });++ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("my-profile", {+ include_secrets: true,+ llm: { model: "openai/gpt-4o" },+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: [LLM_PROFILES_QUERY_KEY],+ });+ });++ it("passes an empty request when none is provided", async () => {+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue();++ const { result } = renderHook(() => useSaveLlmProfile(), {+ wrapper: wrapperFor(makeClient()),+ });+ await result.current.mutateAsync({ name: "snapshot" });++ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("snapshot", {});+ });+});++describe("useDeleteLlmProfile", () => {+ it("invalidates both the profiles list and the settings cache", async () => {+ // Deleting the active profile clears ``llm_profiles.active`` on the+ // backend — the settings query has to refetch or the LLM page will+ // keep showing the deleted profile as in-use.+ vi.mocked(ProfilesService.deleteProfile).mockResolvedValue();+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useDeleteLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await result.current.mutateAsync("my-profile");++ expect(ProfilesService.deleteProfile).toHaveBeenCalledWith("my-profile");+ const invalidatedKeys = invalidateSpy.mock.calls.map(+ ([arg]) => (arg as { queryKey: unknown[] }).queryKey,+ );+ expect(invalidatedKeys).toEqual(+ expect.arrayContaining([[LLM_PROFILES_QUERY_KEY], ["settings"]]),+ );+ });+});++describe("useActivateLlmProfile", () => {+ it("invalidates both the profiles list and the settings cache", async () => {+ // Activating a profile mutates agent_settings.llm on the backend — the+ // settings query has to refetch or the LLM page will render stale data.+ vi.mocked(ProfilesService.activateProfile).mockResolvedValue();+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useActivateLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await result.current.mutateAsync("my-profile");++ expect(ProfilesService.activateProfile).toHaveBeenCalledWith("my-profile");+ const invalidatedKeys = invalidateSpy.mock.calls.map(+ ([arg]) => (arg as { queryKey: unknown[] }).queryKey,+ );+ expect(invalidatedKeys).toEqual(+ expect.arrayContaining([[LLM_PROFILES_QUERY_KEY], ["settings"]]),+ );+ });+});++describe("useRenameLlmProfile", () => {+ it("invalidates both the profiles list and the settings cache", async () => {+ // Renaming the active profile renames ``llm_profiles.active`` on the+ // backend — the settings query has to refetch or any UI surface that+ // reads the active-profile name will stay stale.+ vi.mocked(ProfilesService.renameProfile).mockResolvedValue();+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useRenameLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await result.current.mutateAsync({ name: "old", newName: "new" });++ expect(ProfilesService.renameProfile).toHaveBeenCalledWith("old", "new");+ const invalidatedKeys = invalidateSpy.mock.calls.map(+ ([arg]) => (arg as { queryKey: unknown[] }).queryKey,+ );+ expect(invalidatedKeys).toEqual(+ expect.arrayContaining([[LLM_PROFILES_QUERY_KEY], ["settings"]]),+ );+ });+});++describe("mutation failure paths", () => {+ // onSuccess runs only on success. If a future refactor moves the+ // invalidate call into onSettled, it will fire even on failure — these+ // tests catch that regression.+ it("propagates the rejection and does not invalidate when save fails", async () => {+ vi.mocked(ProfilesService.saveProfile).mockRejectedValue(+ new Error("conflict"),+ );+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useSaveLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await expect(result.current.mutateAsync({ name: "x" })).rejects.toThrow(+ "conflict",+ );+ expect(invalidateSpy).not.toHaveBeenCalled();+ });++ it("propagates the rejection and does not invalidate when delete fails", async () => {+ vi.mocked(ProfilesService.deleteProfile).mockRejectedValue(+ new Error("boom"),+ );+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useDeleteLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await expect(result.current.mutateAsync("x")).rejects.toThrow("boom");+ expect(invalidateSpy).not.toHaveBeenCalled();+ });++ it("propagates the rejection and does not invalidate when activate fails", async () => {+ vi.mocked(ProfilesService.activateProfile).mockRejectedValue(+ new Error("missing"),+ );+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useActivateLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await expect(result.current.mutateAsync("x")).rejects.toThrow("missing");+ expect(invalidateSpy).not.toHaveBeenCalled();+ });++ it("propagates the rejection and does not invalidate when rename fails", async () => {+ vi.mocked(ProfilesService.renameProfile).mockRejectedValue(+ new Error("exists"),+ );+ const client = makeClient();+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");++ const { result } = renderHook(() => useRenameLlmProfile(), {+ wrapper: wrapperFor(client),+ });+ await expect(+ result.current.mutateAsync({ name: "a", newName: "b" }),+ ).rejects.toThrow("exists");+ expect(invalidateSpy).not.toHaveBeenCalled();+ });+});diff --git a/frontend/__tests__/routes/llm-settings.test.tsx b/frontend/__tests__/routes/llm-settings.test.tsxindex 130d2d2461..863c63ba92 100644--- a/frontend/__tests__/routes/llm-settings.test.tsx+++ b/frontend/__tests__/routes/llm-settings.test.tsx@@ -4,6 +4,7 @@ import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { organizationService } from "#/api/organization-service/organization-service.api";+import ProfilesService from "#/api/settings-service/profiles-service.api";import SettingsService from "#/api/settings-service/settings-service.api";import {MOCK_DEFAULT_USER_SETTINGS,@@ -14,6 +15,56 @@ import { useSelectedOrganizationStore } from "#/stores/selected-organization-stoimport { Organization, OrganizationMember } from "#/types/org";import { Settings, SettingsValue } from "#/types/settings";+// ProfilesService is mocked because the LLM screen's auto-profile flow+// calls save + activate after every successful settings save. The default+// resolved values are reapplied in beforeEach — the existing suite-wide+// ``vi.restoreAllMocks()`` would otherwise wipe them between tests.+vi.mock("#/api/settings-service/profiles-service.api", () => ({+ default: {+ listProfiles: vi.fn(),+ saveProfile: vi.fn(),+ deleteProfile: vi.fn(),+ activateProfile: vi.fn(),+ renameProfile: vi.fn(),+ },+}));++function resetProfilesServiceDefaults() {+ vi.mocked(ProfilesService.listProfiles)+ .mockReset()+ .mockResolvedValue({ profiles: [], active_profile: null });+ vi.mocked(ProfilesService.saveProfile)+ .mockReset()+ .mockResolvedValue(undefined);+ vi.mocked(ProfilesService.deleteProfile)+ .mockReset()+ .mockResolvedValue(undefined);+ vi.mocked(ProfilesService.activateProfile)+ .mockReset()+ .mockResolvedValue(undefined);+ vi.mocked(ProfilesService.renameProfile)+ .mockReset()+ .mockResolvedValue(undefined);+}++// Stub the profile mutation hooks so auto-save doesn't invalidate the+// settings query — tests in this file pin exact getSettings call counts.+// The mutateAsync implementations forward to the service mock so the+// auto-profile tests can still assert what was called.+vi.mock("#/hooks/mutation/use-save-llm-profile", () => ({+ useSaveLlmProfile: () => ({+ mutateAsync: (vars: { name: string; request?: unknown }) =>+ ProfilesService.saveProfile(vars.name, vars.request as never),+ isPending: false,+ }),+}));+vi.mock("#/hooks/mutation/use-activate-llm-profile", () => ({+ useActivateLlmProfile: () => ({+ mutateAsync: (name: string) => ProfilesService.activateProfile(name),+ isPending: false,+ }),+}));+const mockUseSearchParams = vi.fn();vi.mock("react-router", async () => {const actual =@@ -144,25 +195,30 @@ async function selectModel(modelLabel: string) {return modelInput;}-function getPayloadAgentSettings(payload: Record<string, unknown>,): Record<string, unknown> {return (payload.agent_settings_diff as Record<string, unknown>) ?? {};}-function renderLlmSettingsScreen({+async function renderLlmSettingsScreen({appMode = "oss",organizationId = "1",meData,organizations,scope = "personal",+ view = "form",}: {appMode?: "oss" | "saas";organizationId?: string;meData?: OrganizationMember;organizations?: Organization[];scope?: "personal" | "org";+ // Personal scope now lands on the Available Models list by default; set+ // ``view`` to ``"form"`` (the default) to auto-click into the SDK form+ // so existing form-oriented assertions keep working unchanged, or to+ // ``"profiles"`` to test the list view itself.+ view?: "form" | "profiles";} = {}) {const queryClient = new QueryClient({defaultOptions: {@@ -190,15 +246,22 @@ function renderLlmSettingsScreen({});}- return render(<LlmSettingsScreen scope={scope} />, {+ const rendered = render(<LlmSettingsScreen scope={scope} />, {wrapper: ({ children }) => (<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>),});++ if (scope === "personal" && view === "form") {+ await userEvent.click(await screen.findByTestId("add-llm-profile"));+ }++ return rendered;}beforeEach(() => {vi.restoreAllMocks();+ resetProfilesServiceDefaults();resetTestHandlersMockSettings();mockUseSearchParams.mockReturnValue([{ get: () => null }, vi.fn()]);mockUseConfig.mockReturnValue({@@ -212,7 +275,7 @@ describe("LlmSettingsScreen", () => {it("renders the schema-driven basic LLM form in OSS mode", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-screen");expect(screen.getByTestId("llm-settings-form-basic")).toBeInTheDocument();@@ -236,7 +299,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-advanced");expect(screen.getByTestId("llm-custom-model-input")).toBeInTheDocument();@@ -256,10 +319,7 @@ describe("LlmSettingsScreen", () => {});it("keeps Advanced visible but hides All in SaaS mode for the default LLM route schema", async () => {- vi.spyOn(- organizationService,- "getOrganizationSettings",- ).mockResolvedValue(+ vi.spyOn(organizationService, "getOrganizationSettings").mockResolvedValue(buildSettings({agent_settings: {llm: {@@ -281,7 +341,9 @@ describe("LlmSettingsScreen", () => {await userEvent.click(screen.getByTestId("sdk-section-advanced-toggle"));- expect(screen.getByTestId("llm-settings-form-advanced")).toBeInTheDocument();+ expect(+ screen.getByTestId("llm-settings-form-advanced"),+ ).toBeInTheDocument();expect(screen.getByTestId("llm-custom-model-input")).toBeInTheDocument();expect(screen.getByTestId("base-url-input")).toBeInTheDocument();});@@ -326,7 +388,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");await userEvent.click(screen.getByTestId("sdk-section-advanced-toggle"));@@ -376,7 +438,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-advanced");@@ -395,7 +457,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-screen");@@ -453,10 +515,7 @@ describe("LlmSettingsScreen", () => {],});- vi.spyOn(- organizationService,- "getOrganizationSettings",- ).mockResolvedValue(+ vi.spyOn(organizationService, "getOrganizationSettings").mockResolvedValue(buildSettings({llm_model: "gpt-4",llm_base_url: "https://api.openai.com",@@ -471,7 +530,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "saas", scope: "org" });+ await renderLlmSettingsScreen({ appMode: "saas", scope: "org" });await screen.findByTestId("llm-settings-form-basic");expect(@@ -522,7 +581,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-form-basic");expect(@@ -536,7 +595,7 @@ describe("LlmSettingsScreen", () => {it("hides the API key input for OpenHands provider in SaaS mode", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");expect(screen.queryByTestId("llm-api-key-input")).not.toBeInTheDocument();@@ -551,7 +610,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");expect(screen.getByTestId("llm-api-key-input")).toBeInTheDocument();@@ -560,7 +619,7 @@ describe("LlmSettingsScreen", () => {it("keeps personal settings editable for team members in SaaS mode", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",meData: buildOrganizationMember({ role: "member" }),});@@ -575,7 +634,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "3",meData: buildOrganizationMember({ org_id: "3", role: "admin" }),@@ -592,7 +651,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "2",meData: buildOrganizationMember({ org_id: "2", role: "member" }),@@ -609,7 +668,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "1",meData: buildOrganizationMember({ org_id: "1", role: "owner" }),@@ -626,7 +685,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-screen");expect(@@ -646,7 +705,7 @@ describe("LlmSettingsScreen", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });const apiKeyInput = await screen.findByTestId("llm-api-key-input");await userEvent.type(apiKeyInput, "test-api-key");@@ -734,7 +793,7 @@ describe("LlmSettingsScreen", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-advanced");await userEvent.click(screen.getByTestId("sdk-section-basic-toggle"));@@ -838,7 +897,8 @@ describe("LlmSettingsScreen", () => {string,SettingsValue>) ?? {}),- ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ??+ {}),},};@@ -910,7 +970,8 @@ describe("LlmSettingsScreen", () => {string,SettingsValue>) ?? {}),- ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ??+ {}),};persistedSettings = buildSettings({@@ -921,7 +982,7 @@ describe("LlmSettingsScreen", () => {return true;});- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");@@ -949,15 +1010,20 @@ describe("LlmSettingsScreen", () => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);});+ // Personal scope flips to the Available Models list after a successful+ // save (``handleSaveSuccess`` → ``setShowProfiles(true)``).await waitFor(() => {- expect(screen.getByTestId("llm-settings-form-basic")).toBeInTheDocument();+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();+ expect(+ screen.queryByTestId("llm-settings-form-basic"),+ ).not.toBeInTheDocument();expect(screen.queryByTestId("llm-settings-form-advanced"),).not.toBeInTheDocument();});});- it("keeps the basic view after save on SaaS personal settings when an inherited org search API key remains set on refetch", async () => {+ it("returns to the profiles list after save on SaaS personal settings even when an inherited org search API key remains set on refetch", async () => {let persistedSettings = buildSettingsWithAdvancedToggle({llm_model: "openai/gpt-4o",search_api_key_set: true,@@ -988,7 +1054,8 @@ describe("LlmSettingsScreen", () => {string,SettingsValue>) ?? {}),- ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ??+ {}),};persistedSettings = buildSettingsWithAdvancedToggle({@@ -1001,7 +1068,7 @@ describe("LlmSettingsScreen", () => {return true;});- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-form-basic");@@ -1029,6 +1096,19 @@ describe("LlmSettingsScreen", () => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);});+ // After save on personal SaaS, the screen returns to the Available+ // Models list — not the advanced form — even though the refetched+ // settings still carry an inherited search_api_key flag.+ await waitFor(() => {+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();+ expect(+ screen.queryByTestId("llm-settings-form-advanced"),+ ).not.toBeInTheDocument();+ });++ // Re-entering the form via Add Profile must land on basic, not get+ // bumped into advanced by the lingering search_api_key on refetch.+ await userEvent.click(screen.getByTestId("add-llm-profile"));await waitFor(() => {expect(screen.getByTestId("llm-settings-form-basic")).toBeInTheDocument();expect(@@ -1083,7 +1163,7 @@ describe("LlmSettingsScreen", () => {return persistedSettings;});- renderLlmSettingsScreen({ appMode: "saas", scope: "org" });+ await renderLlmSettingsScreen({ appMode: "saas", scope: "org" });await screen.findByTestId("llm-settings-form-advanced");await userEvent.click(screen.getByTestId("sdk-section-basic-toggle"));@@ -1124,7 +1204,7 @@ describe("LlmSettingsScreen", () => {});});- it("keeps the basic view after save when a stale legacy base URL lingers on refetch", async () => {+ it("returns to the profiles list after save and re-enters the form in basic view even when a stale legacy base URL lingers on refetch", async () => {let persistedSettings = buildSettingsWithAdvancedToggle({llm_base_url: "https://stale.example/v1",agent_settings: {@@ -1154,7 +1234,8 @@ describe("LlmSettingsScreen", () => {string,SettingsValue>) ?? {}),- ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ??+ {}),};persistedSettings = buildSettingsWithAdvancedToggle({@@ -1165,7 +1246,7 @@ describe("LlmSettingsScreen", () => {return true;});- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-advanced");await userEvent.click(screen.getByTestId("sdk-section-basic-toggle"));@@ -1191,6 +1272,17 @@ describe("LlmSettingsScreen", () => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);});+ // Personal scope returns to Available Models after save.+ await waitFor(() => {+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();+ expect(+ screen.queryByTestId("llm-settings-form-advanced"),+ ).not.toBeInTheDocument();+ });++ // Re-entering the form must not get bumped into advanced by the+ // stale legacy base_url on refetch.+ await userEvent.click(screen.getByTestId("add-llm-profile"));await waitFor(() => {expect(screen.getByTestId("llm-settings-form-basic")).toBeInTheDocument();expect(@@ -1199,7 +1291,7 @@ describe("LlmSettingsScreen", () => {});});- it("keeps the basic view after saving a basic model change when refetch includes a provider base URL", async () => {+ it("returns to the profiles list after saving a basic model change and re-enters the form in basic view even when refetch includes a provider base URL", async () => {let persistedSettings = buildSettingsWithAdvancedToggle();const getSettingsSpy = vi@@ -1222,7 +1314,8 @@ describe("LlmSettingsScreen", () => {string,SettingsValue>) ?? {}),- ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ?? {}),+ ...((payloadAgentSettings.llm as Record<string, SettingsValue>) ??+ {}),};persistedSettings = buildSettingsWithAdvancedToggle({@@ -1240,7 +1333,7 @@ describe("LlmSettingsScreen", () => {return true;});- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");await selectProvider("OpenAI");@@ -1268,6 +1361,17 @@ describe("LlmSettingsScreen", () => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);});+ // Personal scope returns to Available Models after save.+ await waitFor(() => {+ expect(screen.getByTestId("add-llm-profile")).toBeInTheDocument();+ expect(+ screen.queryByTestId("llm-settings-form-advanced"),+ ).not.toBeInTheDocument();+ });++ // Re-entering the form must land on basic — the provider-default+ // base_url that came back on refetch must not pop us into advanced.+ await userEvent.click(screen.getByTestId("add-llm-profile"));await waitFor(() => {expect(screen.getByTestId("llm-settings-form-basic")).toBeInTheDocument();expect(@@ -1281,7 +1385,7 @@ describe("LlmSettingsScreen", () => {buildSettingsWithAdvancedToggle(),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");await userEvent.click(screen.getByTestId("sdk-section-advanced-toggle"));@@ -1372,7 +1476,7 @@ describe("LlmSettingsScreen", () => {},);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");await userEvent.click(screen.getByTestId("sdk-section-all-toggle"));@@ -1443,7 +1547,7 @@ describe("LlmSettingsScreen", () => {return true;});- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-form-basic");expect(@@ -1483,7 +1587,7 @@ describe("LlmSettingsScreen", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });const baseUrlInput = await screen.findByTestId("base-url-input");await userEvent.type(baseUrlInput, "/extra");@@ -1514,7 +1618,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1540,7 +1644,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1563,7 +1667,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1589,7 +1693,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "oss" });+ await renderLlmSettingsScreen({ appMode: "oss" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1615,7 +1719,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1640,7 +1744,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({ appMode: "saas" });+ await renderLlmSettingsScreen({ appMode: "saas" });await screen.findByTestId("llm-settings-screen");const basicForm = screen.getByTestId("llm-settings-form-basic");@@ -1669,7 +1773,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "2",meData: buildOrganizationMember({ org_id: "2", role: "member" }),@@ -1694,7 +1798,7 @@ describe("LlmSettingsScreen", () => {buildSettings(),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "2",meData: buildOrganizationMember({ org_id: "2", role: "member" }),@@ -1709,7 +1813,7 @@ describe("LlmSettingsScreen", () => {buildSettingsWithAdvancedToggle(),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "2",meData: buildOrganizationMember({ org_id: "2", role: "member" }),@@ -1738,7 +1842,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "1",meData: buildOrganizationMember({ org_id: "1", role: "owner" }),@@ -1766,7 +1870,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "1",meData: buildOrganizationMember({ org_id: "1", role: "owner" }),@@ -1800,7 +1904,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "1",meData: buildOrganizationMember({ org_id: "1", role: "owner" }),@@ -1831,7 +1935,7 @@ describe("LlmSettingsScreen", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "1",meData: buildOrganizationMember({ org_id: "1", role: "owner" }),@@ -1859,7 +1963,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "3",meData: buildOrganizationMember({ org_id: "3", role: "admin" }),@@ -1887,7 +1991,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "3",meData: buildOrganizationMember({ org_id: "3", role: "admin" }),@@ -1921,7 +2025,7 @@ describe("LlmSettingsScreen", () => {}),);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "3",meData: buildOrganizationMember({ org_id: "3", role: "admin" }),@@ -1952,7 +2056,7 @@ describe("LlmSettingsScreen", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderLlmSettingsScreen({+ await renderLlmSettingsScreen({appMode: "saas",organizationId: "3",meData: buildOrganizationMember({ org_id: "3", role: "admin" }),@@ -1977,4 +2081,207 @@ describe("LlmSettingsScreen", () => {});});});++ // ── Auto-profile flow ───────────────────────────────────────────────+ //+ // After a successful LLM settings save the screen should snapshot the+ // just-saved agent_settings.llm into a profile named after the model+ // and activate it — that's how Profiles tab populates in the first+ // place. These tests pin that chain.++ describe("auto-profile on save", () => {+ it("saves + activates a profile named after the model after a personal-scope save", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openai/gpt-4o",+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);++ await renderLlmSettingsScreen({ appMode: "oss" });++ await userEvent.type(+ await screen.findByTestId("llm-api-key-input"),+ "test-api-key",+ );+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith(+ "openai_gpt-4o",+ { include_secrets: true },+ );+ });+ await waitFor(() => {+ expect(ProfilesService.activateProfile).toHaveBeenCalledWith(+ "openai_gpt-4o",+ );+ });+ });++ it("does NOT auto-save a profile on the org-default settings screen", async () => {+ // Org defaults reuse this screen with scope="org". Profiles are a+ // per-user feature, so touching the profiles endpoints here would+ // incorrectly spawn profiles on the signed-in user's settings.+ vi.spyOn(+ organizationService,+ "getOrganizationSettings",+ ).mockResolvedValue(+ buildSettings({+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(+ organizationService,+ "saveOrganizationSettings",+ ).mockResolvedValue({+ agent_settings: {},+ conversation_settings: {},+ search_api_key: undefined,+ llm_api_key_set: false,+ });++ await renderLlmSettingsScreen({+ appMode: "saas",+ scope: "org",+ organizationId: "3",+ meData: buildOrganizationMember({ org_id: "3", role: "admin" }),+ });++ await userEvent.type(+ await screen.findByTestId("llm-api-key-input"),+ "test-api-key",+ );+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(organizationService.saveOrganizationSettings).toHaveBeenCalled();+ });+ expect(ProfilesService.saveProfile).not.toHaveBeenCalled();+ expect(ProfilesService.activateProfile).not.toHaveBeenCalled();+ });++ it("uses the user-typed profile name instead of the model-derived default", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openai/gpt-4o",+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);++ await renderLlmSettingsScreen({ appMode: "oss" });++ await userEvent.type(+ await screen.findByTestId("llm-profile-name-input"),+ "my-custom-name",+ );+ await userEvent.type(+ await screen.findByTestId("llm-api-key-input"),+ "test-api-key",+ );+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith(+ "my-custom-name",+ { include_secrets: true },+ );+ });+ await waitFor(() => {+ expect(ProfilesService.activateProfile).toHaveBeenCalledWith(+ "my-custom-name",+ );+ });+ });++ it("falls back to the derived name when the user-typed name fails the regex", async () => {+ // "has space" is invalid (PROFILE_NAME_PATTERN forbids whitespace).+ // The helper text turns red but save proceeds with the derived name —+ // we don't want a settings save to silently succeed while the profile+ // step blows up server-side with a 422.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openai/gpt-4o",+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);++ await renderLlmSettingsScreen({ appMode: "oss" });++ await userEvent.type(+ await screen.findByTestId("llm-profile-name-input"),+ "has space",+ );+ await userEvent.type(+ await screen.findByTestId("llm-api-key-input"),+ "test-api-key",+ );+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith(+ "openai_gpt-4o",+ { include_secrets: true },+ );+ });+ });++ it("does not render the profile-name input on the org-default settings screen", async () => {+ vi.spyOn(+ organizationService,+ "getOrganizationSettings",+ ).mockResolvedValue(+ buildSettings({+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );++ await renderLlmSettingsScreen({+ appMode: "saas",+ scope: "org",+ organizationId: "3",+ meData: buildOrganizationMember({ org_id: "3", role: "admin" }),+ });++ // Wait for the form to render (org-defaults takes the same screen+ // but should never offer to name a profile).+ await screen.findByTestId("llm-api-key-input");+ expect(+ screen.queryByTestId("llm-profile-name-input"),+ ).not.toBeInTheDocument();+ });++ it("swallows profile-save failures so the user still sees the settings-saved toast", async () => {+ // If the profiles endpoint is down (e.g. hit the MAX_PROFILES_PER_USER+ // cap), the settings save itself must still be treated as succeeded.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openai/gpt-4o",+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ vi.mocked(ProfilesService.saveProfile).mockRejectedValueOnce(+ new Error("409 conflict"),+ );++ await renderLlmSettingsScreen({ appMode: "oss" });++ await userEvent.type(+ await screen.findByTestId("llm-api-key-input"),+ "test-api-key",+ );+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalled();+ });+ // Activate must NOT run when save already failed — otherwise we'd+ // activate a profile that doesn't exist on the backend.+ expect(ProfilesService.activateProfile).not.toHaveBeenCalled();+ });+ });});diff --git a/frontend/__tests__/utils/derive-profile-name.test.ts b/frontend/__tests__/utils/derive-profile-name.test.tsnew file mode 100644index 0000000000..76fc4aa009--- /dev/null+++ b/frontend/__tests__/utils/derive-profile-name.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect } from "vitest";+import { deriveProfileNameFromModel } from "#/utils/derive-profile-name";++describe("deriveProfileNameFromModel", () => {+ it("replaces the provider slash with an underscore", () => {+ expect(deriveProfileNameFromModel("openai/gpt-4o")).toBe("openai_gpt-4o");+ expect(deriveProfileNameFromModel("anthropic/claude-3-5-sonnet")).toBe(+ "anthropic_claude-3-5-sonnet",+ );+ });++ it("collapses disallowed characters into single underscores", () => {+ // Colons, spaces, plus signs, etc. are not in [A-Za-z0-9._-].+ expect(deriveProfileNameFromModel("openai/gpt-4o:custom")).toBe(+ "openai_gpt-4o_custom",+ );+ expect(deriveProfileNameFromModel("a b c")).toBe("a_b_c");+ expect(deriveProfileNameFromModel("a+++b")).toBe("a_b");+ });++ it("preserves dots, dashes, and underscores as-is", () => {+ expect(deriveProfileNameFromModel("foo.bar-baz_qux")).toBe(+ "foo.bar-baz_qux",+ );+ });++ it("trims leading/trailing separator characters", () => {+ expect(deriveProfileNameFromModel(" ___openai/gpt-4o___ ")).toBe(+ "openai_gpt-4o",+ );+ });++ it("returns null for empty or unusable input", () => {+ expect(deriveProfileNameFromModel("")).toBeNull();+ expect(deriveProfileNameFromModel(" ")).toBeNull();+ expect(deriveProfileNameFromModel("///")).toBeNull();+ expect(deriveProfileNameFromModel("!!!")).toBeNull();+ });++ it("truncates at 64 characters to respect the backend cap", () => {+ const long = "a".repeat(200);+ const result = deriveProfileNameFromModel(long);+ expect(result).not.toBeNull();+ expect(result!.length).toBe(64);+ });++ it("passes through an already-valid name unchanged", () => {+ expect(deriveProfileNameFromModel("my-profile")).toBe("my-profile");+ expect(deriveProfileNameFromModel("foo_bar.baz-1")).toBe("foo_bar.baz-1");+ });++ it("leaves names exactly 64 characters long untouched", () => {+ const name = "a".repeat(64);+ expect(deriveProfileNameFromModel(name)).toBe(name);+ });++ it("truncates names of 65+ characters down to 64", () => {+ const over = "a".repeat(65);+ const result = deriveProfileNameFromModel(over);+ expect(result).not.toBeNull();+ expect(result!.length).toBe(64);+ });++ it("produces names that satisfy the backend regex", () => {+ const pattern = /^[A-Za-z0-9._-]{1,64}$/;+ for (const model of [+ "openai/gpt-4o",+ "anthropic/claude-3-5-sonnet",+ "openhands/claude-sonnet-4-20250514",+ "azure/standard/1024-x-1024/dall-e-2",+ "openai/gpt-4o:custom",+ ]) {+ const name = deriveProfileNameFromModel(model);+ expect(name).not.toBeNull();+ expect(pattern.test(name!)).toBe(true);+ }+ });+});diff --git a/frontend/src/api/settings-service/profiles-service.api.ts b/frontend/src/api/settings-service/profiles-service.api.tsnew file mode 100644index 0000000000..d7d9cdca37--- /dev/null+++ b/frontend/src/api/settings-service/profiles-service.api.ts@@ -0,0 +1,63 @@+import { openHands } from "../open-hands-axios";++export interface LlmProfileSummary {+ name: string;+ model: string | null;+ base_url: string | null;+ api_key_set: boolean;+}++// Not exported — only `listProfiles` reads it as its response shape.+interface LlmProfileListResponse {+ profiles: LlmProfileSummary[];+ active_profile: string | null;+}++export interface SaveLlmProfileRequest {+ include_secrets?: boolean;+ llm?: {+ model: string;+ base_url?: string | null;+ api_key?: string | null;+ } & Record<string, unknown>;+}++class ProfilesService {+ static async listProfiles(): Promise<LlmProfileListResponse> {+ const { data } = await openHands.get<LlmProfileListResponse>(+ "/api/v1/settings/profiles",+ );+ return data;+ }++ static async saveProfile(+ name: string,+ request: SaveLlmProfileRequest = {},+ ): Promise<void> {+ await openHands.post(+ `/api/v1/settings/profiles/${encodeURIComponent(name)}`,+ request,+ );+ }++ static async deleteProfile(name: string): Promise<void> {+ await openHands.delete(+ `/api/v1/settings/profiles/${encodeURIComponent(name)}`,+ );+ }++ static async activateProfile(name: string): Promise<void> {+ await openHands.post(+ `/api/v1/settings/profiles/${encodeURIComponent(name)}/activate`,+ );+ }++ static async renameProfile(name: string, newName: string): Promise<void> {+ await openHands.post(+ `/api/v1/settings/profiles/${encodeURIComponent(name)}/rename`,+ { new_name: newName },+ );+ }+}++export default ProfilesService;diff --git a/frontend/src/components/features/settings/delete-profile-modal.tsx b/frontend/src/components/features/settings/delete-profile-modal.tsxnew file mode 100644index 0000000000..62bfd0eb73--- /dev/null+++ b/frontend/src/components/features/settings/delete-profile-modal.tsx@@ -0,0 +1,75 @@+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 { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { useDeleteLlmProfile } from "#/hooks/mutation/use-delete-llm-profile";+import { mutateWithToast } from "#/utils/mutate-with-toast";+import { extractErrorMessage } from "#/utils/extract-error-message";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";++interface DeleteProfileModalProps {+ profile: LlmProfileSummary | null;+ onClose: () => void;+}++export function DeleteProfileModal({+ profile,+ onClose,+}: DeleteProfileModalProps) {+ const { t } = useTranslation();+ const deleteProfile = useDeleteLlmProfile();++ if (!profile) return null;++ const handleDelete = async () => {+ const ok = await mutateWithToast(deleteProfile, profile.name, {+ success: t(I18nKey.SETTINGS$PROFILE_DELETED, { name: profile.name }),+ error: (err) => extractErrorMessage(err, t(I18nKey.ERROR$GENERIC)),+ }).catch(() => null);+ if (ok !== null) onClose();+ };++ const footer = (+ <>+ <BrandButton+ testId="delete-profile-confirm"+ type="button"+ variant="danger"+ className="grow"+ onClick={handleDelete}+ isDisabled={deleteProfile.isPending}+ >+ {deleteProfile.isPending ? (+ <LoadingSpinner size="small" />+ ) : (+ t(I18nKey.BUTTON$DELETE)+ )}+ </BrandButton>+ <BrandButton+ type="button"+ variant="secondary"+ className="grow"+ onClick={onClose}+ isDisabled={deleteProfile.isPending}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ </>+ );++ return (+ <ApiKeyModalBase+ isOpen+ title={t(I18nKey.SETTINGS$PROFILE_DELETE_TITLE)}+ footer={footer}+ >+ <Typography.Paragraph className="text-sm break-all">+ {t(I18nKey.SETTINGS$PROFILE_DELETE_CONFIRMATION, {+ name: profile.name,+ })}+ </Typography.Paragraph>+ </ApiKeyModalBase>+ );+}diff --git a/frontend/src/components/features/settings/llm-profiles-manager.tsx b/frontend/src/components/features/settings/llm-profiles-manager.tsxnew file mode 100644index 0000000000..e7f91ce3c2--- /dev/null+++ b/frontend/src/components/features/settings/llm-profiles-manager.tsx@@ -0,0 +1,88 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { RenameProfileModal } from "#/components/features/settings/rename-profile-modal";+import { DeleteProfileModal } from "#/components/features/settings/delete-profile-modal";+import { ProfilesBody } from "#/components/features/settings/profiles-body";+import { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";+import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";+import { mutateWithToast } from "#/utils/mutate-with-toast";+import { extractErrorMessage } from "#/utils/extract-error-message";+import { I18nKey } from "#/i18n/declaration";++interface LlmProfilesManagerProps {+ onAddProfile?: () => void;+ onEditProfile?: (profile: LlmProfileSummary) => void;+}++export function LlmProfilesManager({+ onAddProfile,+ onEditProfile,+}: LlmProfilesManagerProps = {}) {+ const { t } = useTranslation();+ const { data, isLoading, error } = useLlmProfiles();+ const activateProfile = useActivateLlmProfile();+ const [profileToRename, setProfileToRename] =+ useState<LlmProfileSummary | null>(null);+ const [profileToDelete, setProfileToDelete] =+ useState<LlmProfileSummary | null>(null);++ const profiles = data?.profiles ?? [];+ const active = data?.active_profile ?? null;++ const handleActivate = async (name: string) => {+ await mutateWithToast(activateProfile, name, {+ success: t(I18nKey.SETTINGS$PROFILE_ACTIVATED, { name }),+ error: (err) => extractErrorMessage(err, t(I18nKey.ERROR$GENERIC)),+ }).catch(() => null);+ };++ const handleEdit = (profile: LlmProfileSummary) => {+ onEditProfile?.(profile);+ };++ return (+ <>+ <div className="flex flex-col gap-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h2 className="text-base font-semibold text-white">+ {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}+ </h2>+ {onAddProfile ? (+ <BrandButton+ testId="add-llm-profile"+ type="button"+ variant="primary"+ className="ml-auto"+ onClick={onAddProfile}+ >+ {t(I18nKey.SETTINGS$ADD_LLM_PROFILE)}+ </BrandButton>+ ) : null}+ </div>++ <ProfilesBody+ isLoading={isLoading}+ loadError={error ?? null}+ profiles={profiles}+ active={active}+ onActivate={handleActivate}+ onEdit={handleEdit}+ onRename={setProfileToRename}+ onDelete={setProfileToDelete}+ isActivating={activateProfile.isPending}+ />+ </div>++ <RenameProfileModal+ profile={profileToRename}+ onClose={() => setProfileToRename(null)}+ />+ <DeleteProfileModal+ profile={profileToDelete}+ onClose={() => setProfileToDelete(null)}+ />+ </>+ );+}diff --git a/frontend/src/components/features/settings/openhands-api-key-help.tsx b/frontend/src/components/features/settings/openhands-api-key-help.tsxnew file mode 100644index 0000000000..0bd0f45903--- /dev/null+++ b/frontend/src/components/features/settings/openhands-api-key-help.tsx@@ -0,0 +1,35 @@+import { useTranslation } from "react-i18next";+import { HelpLink } from "#/ui/help-link";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";++interface OpenHandsApiKeyHelpProps {+ testId: string;+}++export function OpenHandsApiKeyHelp({ testId }: OpenHandsApiKeyHelpProps) {+ const { t } = useTranslation();++ return (+ <>+ <HelpLink+ testId={testId}+ text={t(I18nKey.SETTINGS$OPENHANDS_API_KEY_HELP_TEXT)}+ linkText={t(I18nKey.SETTINGS$NAV_API_KEYS)}+ href="https://app.all-hands.dev/settings/api-keys"+ suffix={` ${t(I18nKey.SETTINGS$OPENHANDS_API_KEY_HELP_SUFFIX)}`}+ />+ <Typography.Paragraph className="text-xs">+ {t(I18nKey.SETTINGS$LLM_BILLING_INFO)}{" "}+ <a+ href="https://docs.openhands.dev/usage/llms/openhands-llms"+ rel="noreferrer noopener"+ target="_blank"+ className="underline underline-offset-2"+ >+ {t(I18nKey.SETTINGS$SEE_PRICING_DETAILS)}+ </a>+ </Typography.Paragraph>+ </>+ );+}diff --git a/frontend/src/components/features/settings/profile-actions-menu.tsx b/frontend/src/components/features/settings/profile-actions-menu.tsxnew file mode 100644index 0000000000..b4b4c8bae1--- /dev/null+++ b/frontend/src/components/features/settings/profile-actions-menu.tsx@@ -0,0 +1,112 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { ContextMenu } from "#/ui/context-menu";+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";+import { ConversationNameContextMenuIconText } from "#/components/features/conversation/conversation-name-context-menu-icon-text";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { I18nKey } from "#/i18n/declaration";+import SettingsGearIcon from "#/icons/settings-gear.svg?react";+import EditIcon from "#/icons/u-edit.svg?react";+import DeleteIcon from "#/icons/u-delete.svg?react";+import CheckmarkIcon from "#/icons/checkmark.svg?react";++interface ProfileActionsMenuProps {+ onEdit: () => void;+ onRename: () => void;+ onSetActive: () => void;+ onDelete: () => void;+ isActive: boolean;+ isActivating: boolean;+ onClose: () => void;+}++type MenuIcon = React.ComponentType<{ width: number; height: number }>;++interface MenuItemSpec {+ testId: string;+ icon: MenuIcon;+ label: string;+ onSelect: () => void;+ isDisabled?: boolean;+ isDestructive?: boolean;+}++export function ProfileActionsMenu({+ onEdit,+ onRename,+ onSetActive,+ onDelete,+ isActive,+ isActivating,+ onClose,+}: ProfileActionsMenuProps) {+ const { t } = useTranslation();+ const ref = useClickOutsideElement<HTMLUListElement>(onClose);++ const items: MenuItemSpec[] = [+ {+ testId: "profile-edit",+ icon: SettingsGearIcon,+ label: t(I18nKey.SETTINGS$PROFILE_EDIT),+ onSelect: onEdit,+ },+ {+ testId: "profile-rename",+ icon: EditIcon,+ label: t(I18nKey.BUTTON$RENAME),+ onSelect: onRename,+ },+ {+ testId: "profile-set-active",+ icon: CheckmarkIcon,+ label: t(I18nKey.SETTINGS$PROFILE_SET_ACTIVE),+ onSelect: onSetActive,+ isDisabled: isActive || isActivating,+ },+ {+ testId: "profile-delete",+ icon: DeleteIcon,+ label: t(I18nKey.BUTTON$DELETE),+ onSelect: onDelete,+ isDestructive: true,+ },+ ];++ return (+ <ContextMenu+ ref={ref}+ testId="profile-actions-menu"+ alignment="right"+ position="bottom"+ className="min-w-[180px]"+ >+ {items.map(+ ({+ testId,+ icon: Icon,+ label,+ onSelect,+ isDisabled,+ isDestructive,+ }) => (+ <ContextMenuListItem+ key={testId}+ testId={testId}+ onClick={() => {+ onSelect();+ onClose();+ }}+ isDisabled={isDisabled}+ className="cursor-pointer p-0 h-auto hover:bg-transparent"+ >+ <ConversationNameContextMenuIconText+ icon={<Icon width={16} height={16} />}+ text={label}+ className={isDestructive ? "text-red-400" : undefined}+ />+ </ContextMenuListItem>+ ),+ )}+ </ContextMenu>+ );+}diff --git a/frontend/src/components/features/settings/profile-name-input.tsx b/frontend/src/components/features/settings/profile-name-input.tsxnew file mode 100644index 0000000000..24d634fc20--- /dev/null+++ b/frontend/src/components/features/settings/profile-name-input.tsx@@ -0,0 +1,54 @@+import { useTranslation } from "react-i18next";+import { SettingsInput } from "#/components/features/settings/settings-input";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";+import { PROFILE_NAME_PATTERN } from "#/utils/derive-profile-name";++interface ProfileNameInputProps {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ isDisabled?: boolean;+ /** Render label as "Name (Optional)" when this field isn't required. */+ isOptional?: boolean;+ testId?: string;+ ruleTestId?: string;+}++export function ProfileNameInput({+ value,+ onChange,+ placeholder,+ isDisabled,+ isOptional,+ testId,+ ruleTestId,+}: ProfileNameInputProps) {+ const { t } = useTranslation();+ const trimmed = value.trim();+ const isInvalid = trimmed.length > 0 && !PROFILE_NAME_PATTERN.test(trimmed);+ const label = isOptional+ ? `${t(I18nKey.SETTINGS$NAME)} (${t(I18nKey.COMMON$OPTIONAL)})`+ : t(I18nKey.SETTINGS$NAME);++ return (+ <div className="flex flex-col gap-1">+ <SettingsInput+ testId={testId}+ label={label}+ type="text"+ className="w-full"+ value={value}+ placeholder={placeholder}+ onChange={onChange}+ isDisabled={isDisabled}+ />+ <Typography.Paragraph+ testId={ruleTestId}+ className={`text-xs ${isInvalid ? "text-red-400" : "text-gray-400"}`}+ >+ {t(I18nKey.SETTINGS$PROFILE_NAME_RULE)}+ </Typography.Paragraph>+ </div>+ );+}diff --git a/frontend/src/components/features/settings/profile-row.tsx b/frontend/src/components/features/settings/profile-row.tsxnew file mode 100644index 0000000000..8f7cbed13a--- /dev/null+++ b/frontend/src/components/features/settings/profile-row.tsx@@ -0,0 +1,84 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { ProfileActionsMenu } from "#/components/features/settings/profile-actions-menu";+import { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";+import ThreeDotsVerticalIcon from "#/icons/three-dots-vertical.svg?react";++interface ProfileRowProps {+ profile: LlmProfileSummary;+ isActive: boolean;+ onActivate: (name: string) => void;+ onEdit: (profile: LlmProfileSummary) => void;+ onRename: (profile: LlmProfileSummary) => void;+ onDelete: (profile: LlmProfileSummary) => void;+ isActivating: boolean;+}++export function ProfileRow({+ profile,+ isActive,+ onActivate,+ onEdit,+ onRename,+ onDelete,+ isActivating,+}: ProfileRowProps) {+ const { t } = useTranslation();+ const [menuOpen, setMenuOpen] = useState(false);++ return (+ <div+ data-testid="profile-row"+ className="flex items-center justify-between gap-3 px-5 py-4"+ >+ <div className="flex flex-col gap-1 min-w-0 flex-1 sm:flex-row sm:items-center sm:gap-3">+ <Typography.Text+ className="font-medium text-white truncate min-w-0 max-w-full"+ title={profile.name}+ >+ {profile.name}+ </Typography.Text>+ {profile.model ? (+ <Typography.Text+ className="text-sm text-gray-400 truncate min-w-0 max-w-full"+ title={profile.model}+ >+ {profile.model}+ </Typography.Text>+ ) : null}+ {isActive && (+ <Typography.Text+ className="text-xs bg-primary text-[#0D0F11] font-semibold rounded-full px-2 py-0.5 whitespace-nowrap self-start sm:self-auto"+ testId="profile-active-badge"+ >+ {t(I18nKey.SETTINGS$PROFILE_ACTIVE_BADGE)}+ </Typography.Text>+ )}+ </div>+ <div className="relative shrink-0">+ <button+ type="button"+ onClick={() => setMenuOpen((open) => !open)}+ aria-label={t(I18nKey.SETTINGS$PROFILE_MENU)}+ className="cursor-pointer text-gray-300 hover:text-white p-2 border border-tertiary rounded-md"+ data-testid="profile-menu-trigger"+ >+ <ThreeDotsVerticalIcon width={16} height={16} />+ </button>+ {menuOpen && (+ <ProfileActionsMenu+ onEdit={() => onEdit(profile)}+ onRename={() => onRename(profile)}+ onSetActive={() => onActivate(profile.name)}+ onDelete={() => onDelete(profile)}+ isActive={isActive}+ isActivating={isActivating}+ onClose={() => setMenuOpen(false)}+ />+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/features/settings/profiles-body.tsx b/frontend/src/components/features/settings/profiles-body.tsxnew file mode 100644index 0000000000..7a2bd03e9e--- /dev/null+++ b/frontend/src/components/features/settings/profiles-body.tsx@@ -0,0 +1,70 @@+import { useTranslation } from "react-i18next";+import { LoadingSpinner } from "#/components/shared/loading-spinner";+import { ProfileRow } from "#/components/features/settings/profile-row";+import { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { I18nKey } from "#/i18n/declaration";+import { Typography } from "#/ui/typography";++interface ProfilesBodyProps {+ isLoading: boolean;+ loadError: Error | null;+ profiles: LlmProfileSummary[];+ active: string | null;+ onActivate: (name: string) => void;+ onEdit: (profile: LlmProfileSummary) => void;+ onRename: (profile: LlmProfileSummary) => void;+ onDelete: (profile: LlmProfileSummary) => void;+ isActivating: boolean;+}++export function ProfilesBody({+ isLoading,+ loadError,+ profiles,+ active,+ onActivate,+ onEdit,+ onRename,+ onDelete,+ isActivating,+}: ProfilesBodyProps) {+ const { t } = useTranslation();++ if (isLoading) {+ return (+ <div className="flex justify-center p-4">+ <LoadingSpinner size="large" />+ </div>+ );+ }+ if (loadError) {+ return (+ <Typography.Paragraph className="text-sm text-red-400">+ {t(I18nKey.SETTINGS$PROFILES_LOAD_ERROR)}+ </Typography.Paragraph>+ );+ }+ if (profiles.length === 0) {+ return (+ <Typography.Paragraph className="text-sm text-gray-400 italic">+ {t(I18nKey.SETTINGS$PROFILES_EMPTY)}+ </Typography.Paragraph>+ );+ }+ return (+ <div className="border border-tertiary rounded-md divide-y divide-tertiary">+ {profiles.map((profile) => (+ <ProfileRow+ key={profile.name}+ profile={profile}+ isActive={profile.name === active}+ onActivate={onActivate}+ onEdit={onEdit}+ onRename={onRename}+ onDelete={onDelete}+ isActivating={isActivating}+ />+ ))}+ </div>+ );+}diff --git a/frontend/src/components/features/settings/rename-profile-modal.tsx b/frontend/src/components/features/settings/rename-profile-modal.tsxnew file mode 100644index 0000000000..a2b3c21729--- /dev/null+++ b/frontend/src/components/features/settings/rename-profile-modal.tsx@@ -0,0 +1,102 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { ProfileNameInput } from "#/components/features/settings/profile-name-input";+import { LoadingSpinner } from "#/components/shared/loading-spinner";+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";+import { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";+import { useRenameLlmProfile } from "#/hooks/mutation/use-rename-llm-profile";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { mutateWithToast } from "#/utils/mutate-with-toast";+import { extractErrorMessage } from "#/utils/extract-error-message";+import { I18nKey } from "#/i18n/declaration";+import { PROFILE_NAME_PATTERN } from "#/utils/derive-profile-name";++interface RenameProfileModalProps {+ profile: LlmProfileSummary | null;+ onClose: () => void;+}++export function RenameProfileModal({+ profile,+ onClose,+}: RenameProfileModalProps) {+ const { t } = useTranslation();+ const [newName, setNewName] = useState("");+ const renameProfile = useRenameLlmProfile();++ useEffect(() => {+ setNewName(profile?.name ?? "");+ }, [profile?.name]);++ if (!profile) return null;++ const trimmed = newName.trim();+ const isUnchanged = trimmed === profile.name;+ const isValid = PROFILE_NAME_PATTERN.test(trimmed);++ const handleSubmit = async () => {+ if (!isValid) {+ displayErrorToast(t(I18nKey.SETTINGS$PROFILE_NAME_RULE));+ return;+ }+ if (isUnchanged) {+ onClose();+ return;+ }+ const ok = await mutateWithToast(+ renameProfile,+ { name: profile.name, newName: trimmed },+ {+ success: t(I18nKey.SETTINGS$PROFILE_RENAMED, { name: trimmed }),+ error: (err) => extractErrorMessage(err, t(I18nKey.ERROR$GENERIC)),+ },+ ).catch(() => null);+ if (ok !== null) onClose();+ };++ const footer = (+ <>+ <BrandButton+ testId="rename-profile-submit"+ type="button"+ variant="primary"+ className="grow"+ onClick={handleSubmit}+ isDisabled={renameProfile.isPending || !isValid}+ >+ {renameProfile.isPending ? (+ <LoadingSpinner size="small" />+ ) : (+ t(I18nKey.BUTTON$RENAME)+ )}+ </BrandButton>+ <BrandButton+ type="button"+ variant="secondary"+ className="grow"+ onClick={onClose}+ isDisabled={renameProfile.isPending}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ </>+ );++ return (+ <ApiKeyModalBase+ isOpen+ title={t(I18nKey.SETTINGS$PROFILE_RENAME_TITLE)}+ footer={footer}+ >+ <div data-testid="rename-profile-modal" className="flex flex-col gap-3">+ <ProfileNameInput+ testId="rename-profile-input"+ ruleTestId="rename-profile-rule"+ value={newName}+ onChange={setNewName}+ />+ </div>+ </ApiKeyModalBase>+ );+}diff --git a/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx b/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsxindex 882667c26b..03cce8630f 100644--- a/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx+++ b/frontend/src/components/features/settings/sdk-settings/sdk-section-page.tsx@@ -106,6 +106,7 @@ export function SdkSectionPage({getInitialView,forceShowAdvancedView = false,allowAllView = true,+ trailingActions,testId = "sdk-section-settings-screen",}: {sectionKeys: string[];@@ -128,6 +129,10 @@ export function SdkSectionPage({settings: Settings,filteredSchema: SettingsSchema,) => SettingsView;+ // Extra buttons slotted into the Basic/Advanced/All control strip,+ // after the view toggles. Used by the LLM page to drop a Profiles+ // navigation button into the same row.+ trailingActions?: React.ReactNode;forceShowAdvancedView?: boolean;allowAllView?: boolean;testId?: string;@@ -320,6 +325,7 @@ export function SdkSectionPage({showAdvanced={showAdvanced}showAll={showAll}isDisabled={isReadOnly}+ trailing={trailingActions}/><div className="flex flex-col gap-8 pb-20">diff --git a/frontend/src/components/features/settings/sdk-settings/view-toggle.tsx b/frontend/src/components/features/settings/sdk-settings/view-toggle.tsxindex c07342bc0a..d5e24163ed 100644--- a/frontend/src/components/features/settings/sdk-settings/view-toggle.tsx+++ b/frontend/src/components/features/settings/sdk-settings/view-toggle.tsx@@ -9,6 +9,10 @@ interface ViewToggleProps {showAdvanced: boolean;showAll: boolean;isDisabled?: boolean;+ // Extra buttons rendered in the same flex row as Basic/Advanced/All,+ // placed after them. Used to slot section-level nav (e.g. a Profiles+ // button) into the same control strip as the view toggles.+ trailing?: React.ReactNode;}export function ViewToggle({@@ -17,22 +21,26 @@ export function ViewToggle({showAdvanced,showAll,isDisabled = false,+ trailing,}: ViewToggleProps) {const { t } = useTranslation();- if (!showAdvanced && !showAll) return null;+ const hasViewButtons = showAdvanced || showAll;+ if (!hasViewButtons && !trailing) return null;return (- <div className="flex items-center gap-2 mb-6">- <BrandButton- testId="sdk-section-basic-toggle"- variant={view === "basic" ? "primary" : "secondary"}- type="button"- isDisabled={isDisabled}- onClick={() => setView("basic")}- >- {t(I18nKey.SETTINGS$BASIC)}- </BrandButton>+ <div className="flex items-center gap-2 mb-6 flex-wrap">+ {hasViewButtons ? (+ <BrandButton+ testId="sdk-section-basic-toggle"+ variant={view === "basic" ? "primary" : "secondary"}+ type="button"+ isDisabled={isDisabled}+ onClick={() => setView("basic")}+ >+ {t(I18nKey.SETTINGS$BASIC)}+ </BrandButton>+ ) : null}{showAdvanced ? (<BrandButtontestId="sdk-section-advanced-toggle"@@ -55,6 +63,7 @@ export function ViewToggle({{t(I18nKey.SETTINGS$ALL)}</BrandButton>) : null}+ {trailing}</div>);}diff --git a/frontend/src/components/features/settings/settings-layout.tsx b/frontend/src/components/features/settings/settings-layout.tsxindex 06dc68f961..476c8561e9 100644--- a/frontend/src/components/features/settings/settings-layout.tsx+++ b/frontend/src/components/features/settings/settings-layout.tsx@@ -33,7 +33,7 @@ export function SettingsLayout({navigationItems={navigationItems}/>{/* Main content */}- <main className="flex-1 overflow-auto custom-scrollbar-always">+ <main className="flex-1 min-w-0 overflow-auto custom-scrollbar-always">{children}</main></div>diff --git a/frontend/src/hooks/mutation/use-activate-llm-profile.ts b/frontend/src/hooks/mutation/use-activate-llm-profile.tsnew file mode 100644index 0000000000..786fee65af--- /dev/null+++ b/frontend/src/hooks/mutation/use-activate-llm-profile.ts@@ -0,0 +1,17 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/settings-service/profiles-service.api";+import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";++export function useActivateLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (name: string) => {+ await ProfilesService.activateProfile(name);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [LLM_PROFILES_QUERY_KEY] });+ queryClient.invalidateQueries({ queryKey: ["settings"] });+ },+ });+}diff --git a/frontend/src/hooks/mutation/use-delete-llm-profile.ts b/frontend/src/hooks/mutation/use-delete-llm-profile.tsnew file mode 100644index 0000000000..94502a41e8--- /dev/null+++ b/frontend/src/hooks/mutation/use-delete-llm-profile.ts@@ -0,0 +1,20 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/settings-service/profiles-service.api";+import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";++export function useDeleteLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (name: string) => {+ await ProfilesService.deleteProfile(name);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [LLM_PROFILES_QUERY_KEY] });+ // Deleting the active profile clears ``llm_profiles.active`` server-side;+ // the settings cache must refetch or the LLM page will keep showing+ // the deleted profile as in-use.+ queryClient.invalidateQueries({ queryKey: ["settings"] });+ },+ });+}diff --git a/frontend/src/hooks/mutation/use-rename-llm-profile.ts b/frontend/src/hooks/mutation/use-rename-llm-profile.tsnew file mode 100644index 0000000000..0420e17501--- /dev/null+++ b/frontend/src/hooks/mutation/use-rename-llm-profile.ts@@ -0,0 +1,25 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/settings-service/profiles-service.api";+import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";++interface RenameLlmProfileVariables {+ name: string;+ newName: string;+}++export function useRenameLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async ({ name, newName }: RenameLlmProfileVariables) => {+ await ProfilesService.renameProfile(name, newName);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [LLM_PROFILES_QUERY_KEY] });+ // Renaming the active profile changes ``llm_profiles.active`` to the+ // new name; the settings cache must refetch so any UI that reads the+ // active-profile name stays in sync.+ queryClient.invalidateQueries({ queryKey: ["settings"] });+ },+ });+}diff --git a/frontend/src/hooks/mutation/use-save-llm-profile.ts b/frontend/src/hooks/mutation/use-save-llm-profile.tsnew file mode 100644index 0000000000..f82423d3e8--- /dev/null+++ b/frontend/src/hooks/mutation/use-save-llm-profile.ts@@ -0,0 +1,23 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService, {+ SaveLlmProfileRequest,+} from "#/api/settings-service/profiles-service.api";+import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";++interface SaveLlmProfileVariables {+ name: string;+ request?: SaveLlmProfileRequest;+}++export function useSaveLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async ({ name, request }: SaveLlmProfileVariables) => {+ await ProfilesService.saveProfile(name, request ?? {});+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [LLM_PROFILES_QUERY_KEY] });+ },+ });+}diff --git a/frontend/src/hooks/query/use-llm-profiles.ts b/frontend/src/hooks/query/use-llm-profiles.tsnew file mode 100644index 0000000000..13d2c68781--- /dev/null+++ b/frontend/src/hooks/query/use-llm-profiles.ts@@ -0,0 +1,19 @@+import { useQuery } from "@tanstack/react-query";+import ProfilesService from "#/api/settings-service/profiles-service.api";+import { useIsAuthed } from "./use-is-authed";++export const LLM_PROFILES_QUERY_KEY = "llm-profiles";++export function useLlmProfiles() {+ const { data: userIsAuthenticated } = useIsAuthed();++ return useQuery({+ queryKey: [LLM_PROFILES_QUERY_KEY],+ queryFn: ProfilesService.listProfiles,+ enabled: !!userIsAuthenticated,+ retry: (_, error) => error.status !== 404,+ staleTime: 1000 * 60 * 5,+ gcTime: 1000 * 60 * 15,+ meta: { disableToast: true },+ });+}diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex 428bbc4b41..63fba0df8f 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -1420,4 +1420,22 @@ export enum I18nKey {ORG$CLAIM_ERROR = "ORG$CLAIM_ERROR",ORG$DISCONNECT_ERROR = "ORG$DISCONNECT_ERROR",ORG$NO_GIT_ORGANIZATIONS = "ORG$NO_GIT_ORGANIZATIONS",+ SETTINGS$PROFILES_DESCRIPTION = "SETTINGS$PROFILES_DESCRIPTION",+ SETTINGS$PROFILES_EMPTY = "SETTINGS$PROFILES_EMPTY",+ SETTINGS$PROFILES_LOAD_ERROR = "SETTINGS$PROFILES_LOAD_ERROR",+ SETTINGS$PROFILE_ACTIVE_BADGE = "SETTINGS$PROFILE_ACTIVE_BADGE",+ SETTINGS$PROFILE_USE = "SETTINGS$PROFILE_USE",+ SETTINGS$PROFILE_RENAME_TITLE = "SETTINGS$PROFILE_RENAME_TITLE",+ SETTINGS$PROFILE_DELETE_TITLE = "SETTINGS$PROFILE_DELETE_TITLE",+ SETTINGS$PROFILE_DELETE_CONFIRMATION = "SETTINGS$PROFILE_DELETE_CONFIRMATION",+ SETTINGS$PROFILE_NAME_RULE = "SETTINGS$PROFILE_NAME_RULE",+ SETTINGS$PROFILE_RENAMED = "SETTINGS$PROFILE_RENAMED",+ SETTINGS$PROFILE_DELETED = "SETTINGS$PROFILE_DELETED",+ SETTINGS$PROFILE_ACTIVATED = "SETTINGS$PROFILE_ACTIVATED",+ SETTINGS$AVAILABLE_PROFILES = "SETTINGS$AVAILABLE_PROFILES",+ SETTINGS$BACK_TO_LLM_LIST = "SETTINGS$BACK_TO_LLM_LIST",+ SETTINGS$ADD_LLM_PROFILE = "SETTINGS$ADD_LLM_PROFILE",+ SETTINGS$PROFILE_EDIT = "SETTINGS$PROFILE_EDIT",+ SETTINGS$PROFILE_SET_ACTIVE = "SETTINGS$PROFILE_SET_ACTIVE",+ SETTINGS$PROFILE_MENU = "SETTINGS$PROFILE_MENU",}diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex c2bb2d9704..2f898b4a59 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -24138,5 +24138,311 @@"de": "Keine Git-Organisationen gefunden.","uk": "Організації Git не знайдено.","ca": "No s'han trobat organitzacions Git."+ },+ "SETTINGS$PROFILES_DESCRIPTION": {+ "en": "Profiles are created automatically when you save a configuration on the LLM page. The newest one becomes active; switch, rename, or delete saved profiles from this list.",+ "ja": "LLMページで設定を保存すると、プロファイルが自動的に作成されます。最新のプロファイルがアクティブになり、このリストから切り替え、名前の変更、削除ができます。",+ "zh-CN": "在 LLM 页面保存配置时会自动创建配置文件。最新的配置文件会变为活动状态;可在此列表中切换、重命名或删除已保存的配置文件。",+ "zh-TW": "在 LLM 頁面儲存設定時會自動建立設定檔。最新的設定檔會變為使用中;可在此清單中切換、重新命名或刪除已儲存的設定檔。",+ "ko-KR": "LLM 페이지에서 구성을 저장하면 프로필이 자동으로 생성됩니다. 가장 최근 프로필이 활성화되며, 이 목록에서 저장된 프로필을 전환, 이름 변경 또는 삭제할 수 있습니다.",+ "no": "Profiler opprettes automatisk når du lagrer en konfigurasjon på LLM-siden. Den nyeste blir aktiv; bytt, gi nytt navn til eller slett lagrede profiler fra denne listen.",+ "ar": "يتم إنشاء ملفات التعريف تلقائيًا عند حفظ تكوين في صفحة LLM. يصبح الأحدث نشطًا؛ يمكنك التبديل بينها أو إعادة تسميتها أو حذفها من هذه القائمة.",+ "de": "Profile werden automatisch erstellt, wenn Sie eine Konfiguration auf der LLM-Seite speichern. Das neueste wird aktiv; wechseln, umbenennen oder löschen Sie gespeicherte Profile aus dieser Liste.",+ "fr": "Les profils sont créés automatiquement lorsque vous enregistrez une configuration sur la page LLM. Le plus récent devient actif ; changez, renommez ou supprimez les profils enregistrés depuis cette liste.",+ "it": "I profili vengono creati automaticamente quando salvi una configurazione nella pagina LLM. Il più recente diventa attivo; da questo elenco puoi cambiare, rinominare o eliminare i profili salvati.",+ "pt": "Os perfis são criados automaticamente quando você salva uma configuração na página LLM. O mais recente torna-se ativo; alterne, renomeie ou exclua perfis salvos nesta lista.",+ "es": "Los perfiles se crean automáticamente cuando guardas una configuración en la página LLM. El más reciente se activa; cambia, renombra o elimina los perfiles guardados desde esta lista.",+ "ca": "Els perfils es creen automàticament quan deseu una configuració a la pàgina LLM. El més recent es converteix en actiu; canvieu, reanomeneu o suprimiu els perfils desats des d'aquesta llista.",+ "tr": "LLM sayfasında bir yapılandırma kaydettiğinizde profiller otomatik olarak oluşturulur. En yenisi aktif olur; bu listeden kayıtlı profilleri değiştirebilir, yeniden adlandırabilir veya silebilirsiniz.",+ "uk": "Профілі створюються автоматично під час збереження конфігурації на сторінці LLM. Найновіший стає активним; перемикайте, перейменовуйте або видаляйте збережені профілі з цього списку."+ },+ "SETTINGS$PROFILES_EMPTY": {+ "en": "No profiles saved yet. Configure a model on the LLM page — it will be saved here automatically.",+ "ja": "まだプロファイルは保存されていません。LLMページでモデルを設定すると、ここに自動的に保存されます。",+ "zh-CN": "尚未保存配置文件。在 LLM 页面配置模型后,它会自动保存到此处。",+ "zh-TW": "尚未儲存設定檔。在 LLM 頁面設定模型後,它會自動儲存到此處。",+ "ko-KR": "아직 저장된 프로필이 없습니다. LLM 페이지에서 모델을 구성하면 여기에 자동으로 저장됩니다.",+ "no": "Ingen profiler lagret ennå. Konfigurer en modell på LLM-siden — den lagres automatisk her.",+ "ar": "لا توجد ملفات تعريف محفوظة بعد. قم بتكوين نموذج في صفحة LLM — سيتم حفظه هنا تلقائيًا.",+ "de": "Noch keine Profile gespeichert. Konfigurieren Sie ein Modell auf der LLM-Seite — es wird hier automatisch gespeichert.",+ "fr": "Aucun profil enregistré pour le moment. Configurez un modèle sur la page LLM — il sera enregistré ici automatiquement.",+ "it": "Nessun profilo salvato. Configura un modello nella pagina LLM — verrà salvato qui automaticamente.",+ "pt": "Nenhum perfil salvo ainda. Configure um modelo na página LLM — ele será salvo aqui automaticamente.",+ "es": "Aún no hay perfiles guardados. Configura un modelo en la página LLM — se guardará aquí automáticamente.",+ "ca": "Encara no hi ha perfils desats. Configureu un model a la pàgina LLM — es desarà aquí automàticament.",+ "tr": "Henüz kayıtlı profil yok. LLM sayfasında bir model yapılandırın — otomatik olarak buraya kaydedilecektir.",+ "uk": "Ще немає збережених профілів. Налаштуйте модель на сторінці LLM — вона буде автоматично збережена тут."+ },+ "SETTINGS$PROFILES_LOAD_ERROR": {+ "en": "Failed to load profiles. Please try again.",+ "ja": "プロファイルの読み込みに失敗しました。もう一度お試しください。",+ "zh-CN": "加载配置文件失败。请重试。",+ "zh-TW": "載入設定檔失敗。請重試。",+ "ko-KR": "프로필을 불러오지 못했습니다. 다시 시도해 주세요.",+ "no": "Kunne ikke laste profiler. Prøv igjen.",+ "ar": "فشل تحميل ملفات التعريف. الرجاء المحاولة مرة أخرى.",+ "de": "Profile konnten nicht geladen werden. Bitte erneut versuchen.",+ "fr": "Échec du chargement des profils. Veuillez réessayer.",+ "it": "Impossibile caricare i profili. Riprova.",+ "pt": "Falha ao carregar perfis. Tente novamente.",+ "es": "Error al cargar los perfiles. Inténtalo de nuevo.",+ "ca": "No s'han pogut carregar els perfils. Torneu-ho a provar.",+ "tr": "Profiller yüklenemedi. Lütfen tekrar deneyin.",+ "uk": "Не вдалося завантажити профілі. Спробуйте ще раз."+ },+ "SETTINGS$PROFILE_ACTIVE_BADGE": {+ "en": "Active",+ "ja": "アクティブ",+ "zh-CN": "活动",+ "zh-TW": "使用中",+ "ko-KR": "활성",+ "no": "Aktiv",+ "ar": "نشط",+ "de": "Aktiv",+ "fr": "Actif",+ "it": "Attivo",+ "pt": "Ativo",+ "es": "Activo",+ "ca": "Actiu",+ "tr": "Aktif",+ "uk": "Активний"+ },+ "SETTINGS$PROFILE_USE": {+ "en": "Use",+ "ja": "使用",+ "zh-CN": "使用",+ "zh-TW": "使用",+ "ko-KR": "사용",+ "no": "Bruk",+ "ar": "استخدام",+ "de": "Verwenden",+ "fr": "Utiliser",+ "it": "Usa",+ "pt": "Usar",+ "es": "Usar",+ "ca": "Usa",+ "tr": "Kullan",+ "uk": "Використати"+ },+ "SETTINGS$PROFILE_RENAME_TITLE": {+ "en": "Rename Profile",+ "ja": "プロファイルの名前変更",+ "zh-CN": "重命名配置文件",+ "zh-TW": "重新命名設定檔",+ "ko-KR": "프로필 이름 변경",+ "no": "Gi nytt navn til profil",+ "ar": "إعادة تسمية ملف التعريف",+ "de": "Profil umbenennen",+ "fr": "Renommer le profil",+ "it": "Rinomina profilo",+ "pt": "Renomear perfil",+ "es": "Renombrar perfil",+ "ca": "Canvia el nom del perfil",+ "tr": "Profili Yeniden Adlandır",+ "uk": "Перейменувати профіль"+ },+ "SETTINGS$PROFILE_DELETE_TITLE": {+ "en": "Delete Profile",+ "ja": "プロファイルの削除",+ "zh-CN": "删除配置文件",+ "zh-TW": "刪除設定檔",+ "ko-KR": "프로필 삭제",+ "no": "Slett profil",+ "ar": "حذف ملف التعريف",+ "de": "Profil löschen",+ "fr": "Supprimer le profil",+ "it": "Elimina profilo",+ "pt": "Excluir perfil",+ "es": "Eliminar perfil",+ "ca": "Suprimeix el perfil",+ "tr": "Profili Sil",+ "uk": "Видалити профіль"+ },+ "SETTINGS$PROFILE_DELETE_CONFIRMATION": {+ "en": "Delete profile \"{{name}}\"? This cannot be undone.",+ "ja": "プロファイル\"{{name}}\"を削除しますか?この操作は取り消せません。",+ "zh-CN": "删除配置文件 \"{{name}}\"?此操作无法撤消。",+ "zh-TW": "刪除設定檔 \"{{name}}\"?此操作無法撤消。",+ "ko-KR": "프로필 \"{{name}}\"을(를) 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",+ "no": "Slette profilen \"{{name}}\"? Dette kan ikke angres.",+ "ar": "حذف ملف التعريف \"{{name}}\"؟ لا يمكن التراجع عن هذا الإجراء.",+ "de": "Profil \"{{name}}\" löschen? Dies kann nicht rückgängig gemacht werden.",+ "fr": "Supprimer le profil \"{{name}}\" ? Cette action est irréversible.",+ "it": "Eliminare il profilo \"{{name}}\"? L'operazione non può essere annullata.",+ "pt": "Excluir perfil \"{{name}}\"? Esta ação não pode ser desfeita.",+ "es": "¿Eliminar el perfil \"{{name}}\"? Esta acción no se puede deshacer.",+ "ca": "Voleu suprimir el perfil \"{{name}}\"? Aquesta acció no es pot desfer.",+ "tr": "\"{{name}}\" profili silinsin mi? Bu işlem geri alınamaz.",+ "uk": "Видалити профіль \"{{name}}\"? Цю дію не можна скасувати."+ },+ "SETTINGS$PROFILE_NAME_RULE": {+ "en": "Name must be 1–64 characters: letters, digits, dot, dash, or underscore.",+ "ja": "名前は1〜64文字で、英数字、ドット、ハイフン、アンダースコアのみ使用できます。",+ "zh-CN": "名称必须为 1–64 个字符,只能包含字母、数字、点、短划线或下划线。",+ "zh-TW": "名稱必須為 1–64 個字元,僅能包含字母、數字、點、短橫線或底線。",+ "ko-KR": "이름은 1–64자여야 하며 문자, 숫자, 점, 대시 또는 밑줄만 사용할 수 있습니다.",+ "no": "Navnet må være 1–64 tegn, med bokstaver, tall, punktum, bindestrek eller understrek.",+ "ar": "يجب أن يتراوح طول الاسم بين 1 و64 حرفًا، ويتكون من أحرف أو أرقام أو نقطة أو شرطة أو شرطة سفلية.",+ "de": "Der Name muss 1–64 Zeichen lang sein und darf nur Buchstaben, Ziffern, Punkt, Bindestrich oder Unterstrich enthalten.",+ "fr": "Le nom doit comporter de 1 à 64 caractères : lettres, chiffres, point, tiret ou tiret bas.",+ "it": "Il nome deve contenere da 1 a 64 caratteri tra lettere, cifre, punto, trattino o trattino basso.",+ "pt": "O nome deve ter de 1 a 64 caracteres: letras, dígitos, ponto, traço ou sublinhado.",+ "es": "El nombre debe tener entre 1 y 64 caracteres: letras, dígitos, punto, guion o guion bajo.",+ "ca": "El nom ha de tenir entre 1 i 64 caràcters: lletres, dígits, punt, guió o guió baix.",+ "tr": "Ad 1–64 karakter olmalı ve yalnızca harf, rakam, nokta, tire veya alt çizgi içermelidir.",+ "uk": "Ім'я має містити 1–64 символи: літери, цифри, крапку, дефіс або підкреслення."+ },+ "SETTINGS$PROFILE_RENAMED": {+ "en": "Profile renamed to \"{{name}}\"",+ "ja": "プロファイルの名前を\"{{name}}\"に変更しました",+ "zh-CN": "配置文件已重命名为 \"{{name}}\"",+ "zh-TW": "設定檔已重新命名為 \"{{name}}\"",+ "ko-KR": "프로필 이름이 \"{{name}}\"(으)로 변경되었습니다",+ "no": "Profilen er omdøpt til \"{{name}}\"",+ "ar": "تمت إعادة تسمية ملف التعريف إلى \"{{name}}\"",+ "de": "Profil in \"{{name}}\" umbenannt",+ "fr": "Profil renommé en \"{{name}}\"",+ "it": "Profilo rinominato in \"{{name}}\"",+ "pt": "Perfil renomeado para \"{{name}}\"",+ "es": "Perfil renombrado a \"{{name}}\"",+ "ca": "S'ha canviat el nom del perfil a \"{{name}}\"",+ "tr": "Profil \"{{name}}\" olarak yeniden adlandırıldı",+ "uk": "Профіль перейменовано на \"{{name}}\""+ },+ "SETTINGS$PROFILE_DELETED": {+ "en": "Profile \"{{name}}\" deleted",+ "ja": "プロファイル\"{{name}}\"を削除しました",+ "zh-CN": "已删除配置文件 \"{{name}}\"",+ "zh-TW": "已刪除設定檔 \"{{name}}\"",+ "ko-KR": "프로필 \"{{name}}\"이(가) 삭제되었습니다",+ "no": "Profilen \"{{name}}\" er slettet",+ "ar": "تم حذف ملف التعريف \"{{name}}\"",+ "de": "Profil \"{{name}}\" gelöscht",+ "fr": "Profil \"{{name}}\" supprimé",+ "it": "Profilo \"{{name}}\" eliminato",+ "pt": "Perfil \"{{name}}\" excluído",+ "es": "Perfil \"{{name}}\" eliminado",+ "ca": "Perfil \"{{name}}\" suprimit",+ "tr": "\"{{name}}\" profili silindi",+ "uk": "Профіль \"{{name}}\" видалено"+ },+ "SETTINGS$PROFILE_ACTIVATED": {+ "en": "Switched to profile \"{{name}}\"",+ "ja": "プロファイル\"{{name}}\"に切り替えました",+ "zh-CN": "已切换到配置文件 \"{{name}}\"",+ "zh-TW": "已切換到設定檔 \"{{name}}\"",+ "ko-KR": "프로필 \"{{name}}\"(으)로 전환했습니다",+ "no": "Byttet til profilen \"{{name}}\"",+ "ar": "تم التبديل إلى ملف التعريف \"{{name}}\"",+ "de": "Zu Profil \"{{name}}\" gewechselt",+ "fr": "Bascule vers le profil \"{{name}}\"",+ "it": "Passato al profilo \"{{name}}\"",+ "pt": "Alternado para o perfil \"{{name}}\"",+ "es": "Cambiado al perfil \"{{name}}\"",+ "ca": "S'ha canviat al perfil \"{{name}}\"",+ "tr": "\"{{name}}\" profiline geçildi",+ "uk": "Перемкнуто на профіль \"{{name}}\""+ },+ "SETTINGS$AVAILABLE_PROFILES": {+ "en": "Available Profiles",+ "ja": "利用可能なプロファイル",+ "zh-CN": "可用配置文件",+ "zh-TW": "可用設定檔",+ "ko-KR": "사용 가능한 프로필",+ "no": "Tilgjengelige profiler",+ "ar": "ملفات التعريف المتاحة",+ "de": "Verfügbare Profile",+ "fr": "Profils disponibles",+ "it": "Profili disponibili",+ "pt": "Perfis disponíveis",+ "es": "Perfiles disponibles",+ "ca": "Perfils disponibles",+ "tr": "Kullanılabilir Profiller",+ "uk": "Доступні профілі"+ },+ "SETTINGS$BACK_TO_LLM_LIST": {+ "en": "Back to LLM profiles list",+ "ja": "LLMプロファイルリストに戻る",+ "zh-CN": "返回 LLM 配置文件列表",+ "zh-TW": "返回 LLM 設定檔列表",+ "ko-KR": "LLM 프로파일 목록으로 돌아가기",+ "no": "Tilbake til listen over LLM-profiler",+ "ar": "العودة إلى قائمة ملفات تعريف LLM",+ "de": "Zurück zur LLM-Profilliste",+ "fr": "Retour à la liste des profils LLM",+ "it": "Torna all'elenco dei profili LLM",+ "pt": "Voltar à lista de perfis LLM",+ "es": "Volver a la lista de perfiles LLM",+ "ca": "Torna a la llista de perfils LLM",+ "tr": "LLM profilleri listesine dön",+ "uk": "Назад до списку профілів LLM"+ },+ "SETTINGS$ADD_LLM_PROFILE": {+ "en": "Add LLM Profile",+ "ja": "LLMプロファイルを追加",+ "zh-CN": "添加 LLM 配置文件",+ "zh-TW": "新增 LLM 設定檔",+ "ko-KR": "LLM 프로필 추가",+ "no": "Legg til LLM-profil",+ "ar": "إضافة ملف تعريف LLM",+ "de": "LLM-Profil hinzufügen",+ "fr": "Ajouter un profil LLM",+ "it": "Aggiungi profilo LLM",+ "pt": "Adicionar perfil de LLM",+ "es": "Añadir perfil de LLM",+ "ca": "Afegeix un perfil LLM",+ "tr": "LLM Profili Ekle",+ "uk": "Додати профіль LLM"+ },+ "SETTINGS$PROFILE_EDIT": {+ "en": "Edit",+ "ja": "編集",+ "zh-CN": "编辑",+ "zh-TW": "編輯",+ "ko-KR": "편집",+ "no": "Rediger",+ "ar": "تعديل",+ "de": "Bearbeiten",+ "fr": "Modifier",+ "it": "Modifica",+ "pt": "Editar",+ "es": "Editar",+ "ca": "Edita",+ "tr": "Düzenle",+ "uk": "Редагувати"+ },+ "SETTINGS$PROFILE_SET_ACTIVE": {+ "en": "Set as active",+ "ja": "アクティブに設定",+ "zh-CN": "设为活动",+ "zh-TW": "設為使用中",+ "ko-KR": "활성으로 설정",+ "no": "Angi som aktiv",+ "ar": "تعيين كنشط",+ "de": "Als aktiv festlegen",+ "fr": "Définir comme actif",+ "it": "Imposta come attivo",+ "pt": "Definir como ativo",+ "es": "Establecer como activo",+ "ca": "Estableix com a actiu",+ "tr": "Aktif olarak ayarla",+ "uk": "Зробити активним"+ },+ "SETTINGS$PROFILE_MENU": {+ "en": "Profile actions",+ "ja": "プロファイルのアクション",+ "zh-CN": "配置文件操作",+ "zh-TW": "設定檔操作",+ "ko-KR": "프로필 작업",+ "no": "Profilhandlinger",+ "ar": "إجراءات ملف التعريف",+ "de": "Profilaktionen",+ "fr": "Actions du profil",+ "it": "Azioni del profilo",+ "pt": "Ações do perfil",+ "es": "Acciones del perfil",+ "ca": "Accions del perfil",+ "tr": "Profil işlemleri",+ "uk": "Дії профілю"}}diff --git a/frontend/src/routes/llm-settings.tsx b/frontend/src/routes/llm-settings.tsxindex 960bb7a3e3..7dac5ba1fa 100644--- a/frontend/src/routes/llm-settings.tsx+++ b/frontend/src/routes/llm-settings.tsx@@ -1,6 +1,7 @@import React from "react";import { useSearchParams } from "react-router";import { useTranslation } from "react-i18next";+import { FaChevronLeft } from "react-icons/fa6";import { ModelSelector } from "#/components/shared/modals/settings/model-selector";import { createPermissionGuard } from "#/utils/org/permission-guard";import { requireOrgDefaultsRedirect } from "#/utils/org/saas-redirect-to-org-defaults-guard";@@ -10,6 +11,7 @@ import { SettingsInput } from "#/components/features/settings/settings-input";import { HelpLink } from "#/ui/help-link";import { useConfig } from "#/hooks/query/use-config";import { KeyStatusIcon } from "#/components/features/settings/key-status-icon";+import { OpenHandsApiKeyHelp } from "#/components/features/settings/openhands-api-key-help";import {SdkSectionHeaderProps,SdkSectionPage,@@ -26,6 +28,16 @@ import {type SettingsView,} from "#/utils/sdk-settings-schema";import { DEFAULT_SETTINGS } from "#/services/settings";+import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";+import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";+import { useRenameLlmProfile } from "#/hooks/mutation/use-rename-llm-profile";+import {+ deriveProfileNameFromModel,+ PROFILE_NAME_PATTERN,+} from "#/utils/derive-profile-name";+import { LlmProfilesManager } from "#/components/features/settings/llm-profiles-manager";+import { ProfileNameInput } from "#/components/features/settings/profile-name-input";+import { Typography } from "#/ui/typography";const LLM_EXCLUDED_KEYS = new Set(["llm.model", "llm.api_key", "llm.base_url"]);@@ -80,37 +92,6 @@ const isProviderDefaultBaseUrl = (model: string, baseUrl: string) => {);};-interface OpenHandsApiKeyHelpProps {- testId: string;-}--function OpenHandsApiKeyHelp({ testId }: OpenHandsApiKeyHelpProps) {- const { t } = useTranslation();-- return (- <>- <HelpLink- testId={testId}- text={t(I18nKey.SETTINGS$OPENHANDS_API_KEY_HELP_TEXT)}- linkText={t(I18nKey.SETTINGS$NAV_API_KEYS)}- href="https://app.all-hands.dev/settings/api-keys"- suffix={` ${t(I18nKey.SETTINGS$OPENHANDS_API_KEY_HELP_SUFFIX)}`}- />- <p className="text-xs">- {t(I18nKey.SETTINGS$LLM_BILLING_INFO)}{" "}- <a- href="https://docs.openhands.dev/usage/llms/openhands-llms"- rel="noreferrer noopener"- target="_blank"- className="underline underline-offset-2"- >- {t(I18nKey.SETTINGS$SEE_PRICING_DETAILS)}- </a>- </p>- </>- );-}-export function LlmSettingsScreen({scope = "personal",}: {@@ -129,6 +110,34 @@ export function LlmSettingsScreen({null,);const hasHydratedInitialPersonalSaasViewRef = React.useRef(false);+ // Captured during buildPayload so onSaveSuccess can derive a profile name+ // from the exact model that was just persisted.+ const lastSavedModelRef = React.useRef<string | null>(null);+ const saveProfile = useSaveLlmProfile();+ const activateProfile = useActivateLlmProfile();+ const renameProfile = useRenameLlmProfile();++ // Controls whether the LLM form or the Profiles list is shown. Flipping+ // this unmounts the inactive branch, so the SdkSectionPage re-hydrates+ // its view from ``initialViewHint`` when coming back from profiles.+ // Personal scope lands on the Available Models list first; org-scope+ // defaults (which don't have profiles) always open straight into the form.+ const [showProfiles, setShowProfiles] = React.useState(scope === "personal");+ // User-supplied profile name. Empty → fall back to deriveProfileNameFromModel+ // in handleSaveSuccess. Reset on every form open so a stale name from the+ // previous Add doesn't leak in.+ const [profileName, setProfileName] = React.useState("");+ // Snapshotted on form open so we can flag the form dirty when the user+ // edits *only* the name — the SDK section page tracks the LLM fields but+ // not the profile-name input that lives outside its schema.+ const [initialProfileName, setInitialProfileName] = React.useState("");+ // When the user clicks Basic / Advanced / All from inside the profiles+ // view, we want the LLM form to open on *that* tier — not whatever the+ // schema happened to infer. We stash the choice here and consume it in+ // getInitialView below.+ const [initialViewHint, setInitialViewHint] =+ React.useState<SettingsView | null>(null);+ const isProfilesView = scope === "personal" && showProfiles;const defaultModel = String((DEFAULT_SETTINGS.agent_settings?.llm as Record<string, unknown>)?.model ??@@ -144,12 +153,6 @@ export function LlmSettingsScreen({}}, [settings?.llm_model]);- React.useEffect(() => {- if (settings && isSaasMode && scope !== "org") {- hasHydratedInitialPersonalSaasViewRef.current = true;- }- }, [isSaasMode, scope, settings]);-React.useEffect(() => {const checkout = searchParams.get("checkout");@@ -174,11 +177,22 @@ export function LlmSettingsScreen({currentSettings: Settings,filteredSchema: SettingsSchema,): SettingsView => {+ // A hint set by the Profiles mirror-strip beats every other rule —+ // the user explicitly asked for this tier when leaving profiles.+ if (initialViewHint) {+ return initialViewHint;+ }++ // Personal SaaS users now land on Available Models first; the form+ // is mounted on-demand (Add / Edit). The first form mount per session+ // should still default to basic so users aren't dropped straight into+ // advanced/all even if the active profile has complex fields.if (isSaasMode &&scope !== "org" &&!hasHydratedInitialPersonalSaasViewRef.current) {+ hasHydratedInitialPersonalSaasViewRef.current = true;return "basic";}@@ -195,7 +209,7 @@ export function LlmSettingsScreen({return hasCustomBaseUrl ? "all" : "basic";},- [isSaasMode, scope],+ [initialViewHint, isSaasMode, scope],);const buildHeader = React.useCallback(@@ -254,15 +268,30 @@ export function LlmSettingsScreen({);};+ const profileNamePlaceholder =+ deriveProfileNameFromModel(modelValue) ?? "";+return (<div className="flex flex-col gap-6">{infoMessageKey ? (- <p- data-testid="llm-settings-info-message"+ <Typography.Paragraph+ testId="llm-settings-info-message"className="text-sm text-tertiary-alt">{t(infoMessageKey)}- </p>+ </Typography.Paragraph>+ ) : null}++ {scope === "personal" ? (+ <ProfileNameInput+ testId="llm-profile-name-input"+ ruleTestId="llm-profile-name-rule"+ value={profileName}+ placeholder={profileNamePlaceholder}+ onChange={setProfileName}+ isDisabled={isDisabled}+ isOptional+ />) : null}{view === "basic" ? (@@ -336,6 +365,8 @@ export function LlmSettingsScreen({infoMessageKey,isSaasMode,defaultModel,+ profileName,+ scope,selectedProvider,settings?.llm_api_key_set,t,@@ -378,23 +409,124 @@ export function LlmSettingsScreen({agentSettings.llm = llm;}+ // Remember the model currently shown in the form — this is what the+ // user is saving regardless of whether `llm.model` was toggled dirty+ // this turn. ``basePayload`` only includes dirty fields, so falling+ // back to ``context.values`` makes the profile auto-creation fire on+ // same-value re-saves (e.g. save → delete profile → save again).+ lastSavedModelRef.current = modelValue || null;+return { agent_settings_diff: agentSettings };},[isSaasMode, schema, selectedProvider],);+ const handleSaveSuccess = React.useCallback(async () => {+ const savedModel = lastSavedModelRef.current;+ const trimmedUserName = profileName.trim();+ // Use the user-supplied name only if it matches the backend regex —+ // otherwise silently fall back to the model-derived default (the helper+ // text under the input has already warned them their name was invalid).+ const userName = PROFILE_NAME_PATTERN.test(trimmedUserName)+ ? trimmedUserName+ : null;+ const derivedName = savedModel+ ? deriveProfileNameFromModel(savedModel)+ : null;+ const name = userName ?? derivedName;++ // Auto-saved profiles are a personal-scope feature — organization default+ // LLM settings reuse this screen but shouldn't spawn per-user profiles.+ if (scope !== "org" && name) {+ try {+ // Editing an existing profile and renaming it via the form should+ // rename the record in place rather than spawning a new one and+ // leaving the original orphaned.+ if (initialProfileName && initialProfileName !== name) {+ await renameProfile.mutateAsync({+ name: initialProfileName,+ newName: name,+ });+ }+ // Omit `llm` → backend snapshots the just-saved agent_settings.llm+ // (api_key and all). Saves us from having to hand-reconstruct the+ // config and risk mangling the secret placeholder handling.+ await saveProfile.mutateAsync({+ name,+ request: { include_secrets: true },+ });+ await activateProfile.mutateAsync(name);+ } catch {+ // Best-effort: the settings save already succeeded. Profile cap+ // (HTTP 409) and transient errors are surfaced on the Profiles page.+ }+ }++ setProfileName("");+ setInitialProfileName("");+ setInitialViewHint(null);+ setShowProfiles(true);+ }, [+ activateProfile,+ initialProfileName,+ profileName,+ renameProfile,+ saveProfile,+ scope,+ ]);++ const openForm = (view: SettingsView | null, name = "") => {+ setProfileName(name);+ setInitialProfileName(name);+ setInitialViewHint(view);+ setShowProfiles(false);+ };++ if (isProfilesView) {+ return (+ <LlmProfilesManager+ onAddProfile={() => openForm(null)}+ onEditProfile={(profile) => openForm(null, profile.name)}+ />+ );+ }++ // Sub-page back affordance (personal scope only — org-defaults has no+ // parent list to return to). Replaces the previous "Profiles" trailing+ // action so the form view follows the second-level settings pattern.+ const backToProfiles =+ scope === "personal" ? (+ <button+ data-testid="llm-back-to-profiles"+ type="button"+ onClick={() => {+ setInitialViewHint(null);+ setShowProfiles(true);+ }}+ className="flex items-center gap-2 self-start text-sm text-gray-300 hover:text-white cursor-pointer"+ >+ <FaChevronLeft size={12} aria-hidden="true" />+ {t(I18nKey.SETTINGS$BACK_TO_LLM_LIST)}+ </button>+ ) : null;+return (- <SdkSectionPage- scope={scope}- sectionKeys={["llm"]}- excludeKeys={LLM_EXCLUDED_KEYS}- header={buildHeader}- buildPayload={buildPayload}- getInitialView={getInitialView}- forceShowAdvancedView- allowAllView={!isSaasMode}- testId="llm-settings-screen"- />+ <div className="flex flex-col gap-4">+ {backToProfiles}+ <SdkSectionPage+ scope={scope}+ sectionKeys={["llm"]}+ excludeKeys={LLM_EXCLUDED_KEYS}+ header={buildHeader}+ buildPayload={buildPayload}+ extraDirty={profileName.trim() !== initialProfileName.trim()}+ onSaveSuccess={handleSaveSuccess}+ getInitialView={getInitialView}+ forceShowAdvancedView+ allowAllView={!isSaasMode}+ testId="llm-settings-screen"+ />+ </div>);}diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsxindex 87b8c11769..00f47a3aa4 100644--- a/frontend/src/routes/root-layout.tsx+++ b/frontend/src/routes/root-layout.tsx@@ -262,7 +262,7 @@ export default function MainApp() {<title>{appTitle}</title><Sidebar />- <div className="flex flex-col w-full h-[calc(100%-50px)] md:h-full gap-3">+ <div className="flex flex-col w-full min-w-0 h-[calc(100%-50px)] md:h-full gap-3">{config.data &&(config.data.maintenance_start_time ||(config.data.faulty_models &&diff --git a/frontend/src/ui/typography.tsx b/frontend/src/ui/typography.tsxindex 6e8dfbcaec..8ed4f22310 100644--- a/frontend/src/ui/typography.tsx+++ b/frontend/src/ui/typography.tsx@@ -21,6 +21,7 @@ const typographyVariants = cva("", {interface TypographyProps extends VariantProps<typeof typographyVariants> {className?: string;testId?: string;+ title?: string;children: React.ReactNode;}@@ -28,6 +29,7 @@ export function Typography({variant,className,testId,+ title,children,}: TypographyProps) {const Tag = variant as keyof React.JSX.IntrinsicElements;@@ -35,6 +37,7 @@ export function Typography({return (<Tagdata-testid={testId}+ title={title}className={cn(typographyVariants({ variant }), className)}>{children}@@ -82,10 +85,16 @@ export function H3({export function Text({className,testId,+ title,children,}: Omit<TypographyProps, "variant">) {return (- <Typography variant="span" className={className} testId={testId}>+ <Typography+ variant="span"+ className={className}+ testId={testId}+ title={title}+ >{children}</Typography>);diff --git a/frontend/src/utils/derive-profile-name.ts b/frontend/src/utils/derive-profile-name.tsnew file mode 100644index 0000000000..b00bcec5a1--- /dev/null+++ b/frontend/src/utils/derive-profile-name.ts@@ -0,0 +1,30 @@+// Backend-enforced pattern: ^[A-Za-z0-9._-]{1,64}$+// Matches settings_router.py — keep them in sync.+const ALLOWED_CHARS = /[^A-Za-z0-9._-]/g;++export const PROFILE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;++/**+ * Build a profile name from an LLM model string.+ *+ * Examples:+ * "openai/gpt-4o" -> "openai_gpt-4o"+ * "anthropic/claude-3-5-sonnet" -> "anthropic_claude-3-5-sonnet"+ * "openai/gpt-4o:custom" -> "openai_gpt-4o_custom"+ *+ * Returns null if the input has no usable characters (e.g. empty or all+ * non-alphanumeric). The caller should then skip the auto-profile step+ * rather than falling back to a generic placeholder name.+ */+export function deriveProfileNameFromModel(model: string): string | null {+ // "/" is the canonical provider separator; mapping it to "_" keeps the+ // human-readable boundary without running afoul of the backend regex.+ const sanitized = model+ .trim()+ .replace(/\//g, "_")+ .replace(ALLOWED_CHARS, "_")+ .replace(/_+/g, "_")+ .replace(/^[._-]+|[._-]+$/g, "")+ .slice(0, 64);+ return sanitized.length > 0 ? sanitized : null;+}diff --git a/frontend/src/utils/extract-error-message.ts b/frontend/src/utils/extract-error-message.tsnew file mode 100644index 0000000000..3064ef4b85--- /dev/null+++ b/frontend/src/utils/extract-error-message.ts@@ -0,0 +1,20 @@+/**+ * Pull a user-facing message off an unknown error, preferring FastAPI's+ * `detail` field, then a generic `message` body field, then `Error.message`,+ * and finally the supplied fallback. Tolerant of non-Axios errors so callers+ * don't need to narrow the type before calling.+ */+export function extractErrorMessage(err: unknown, fallback: string): string {+ if (typeof err === "object" && err !== null) {+ const withResponse = err as {+ response?: { data?: { detail?: unknown; message?: unknown } };+ message?: string;+ };+ const detail = withResponse.response?.data?.detail;+ if (typeof detail === "string") return detail;+ const message = withResponse.response?.data?.message;+ if (typeof message === "string") return message;+ if (withResponse.message) return withResponse.message;+ }+ return fallback;+}diff --git a/frontend/src/utils/utils.ts b/frontend/src/utils/utils.tsindex 48248c2a44..bf9b3a71b3 100644--- a/frontend/src/utils/utils.ts+++ b/frontend/src/utils/utils.ts@@ -216,104 +216,6 @@ export const getPR = (isGitLab: boolean) =>*/export const getPRShort = (isGitLab: boolean) => (isGitLab ? "MR" : "PR");-/**- * Construct the pull request (merge request) URL for different providers- * @param prNumber The pull request number- * @param provider The git provider- * @param repositoryName The repository name in format "owner/repo"- * @returns The pull request URL- *- * @example- * constructPullRequestUrl(123, "github", "owner/repo") // "https://github.com/owner/repo/pull/123"- * constructPullRequestUrl(456, "gitlab", "owner/repo") // "https://gitlab.com/owner/repo/-/merge_requests/456"- * constructPullRequestUrl(789, "bitbucket", "owner/repo") // "https://bitbucket.org/owner/repo/pull-requests/789"- * constructPullRequestUrl(789, "bitbucket", "PROJECT/repo", "server.com") // "https://server.com/projects/PROJECT/repos/repo/pull-requests/789"- */-export const constructPullRequestUrl = (- prNumber: number,- provider: Provider,- repositoryName: string,- host?: string | null,-): string => {- const baseUrl = ensureHttpsPrefix(host);-- switch (provider) {- case "github":- return `${baseUrl}/${repositoryName}/pull/${prNumber}`;- case "forgejo":- return `${baseUrl}/${repositoryName}/pull/${prNumber}`;- case "gitlab":- return `${baseUrl}/${repositoryName}/-/merge_requests/${prNumber}`;- case "bitbucket":- return `${baseUrl}/${repositoryName}/pull-requests/${prNumber}`;- case "bitbucket_data_center": {- const [project, repo] = repositoryName.split("/");- return `${baseUrl}/projects/${project}/repos/${repo}/pull-requests/${prNumber}`;- }- case "azure_devops": {- // Azure DevOps format: org/project/repo- const parts = repositoryName.split("/");- if (parts.length === 3) {- const [org, project, repo] = parts;- return `${baseUrl}/${org}/${project}/_git/${repo}/pullrequest/${prNumber}`;- }- return "";- }- default:- return "";- }-};--/**- * Construct the microagent URL for different providers- * @param gitProvider The git provider- * @param repositoryName The repository name in format "owner/repo"- * @param microagentPath The path to the microagent in the repository- * @returns The URL to the microagent file in the Git provider- *- * @example- * constructMicroagentUrl("github", "owner/repo", ".openhands/microagents/tell-me-a-joke.md")- * // "https://github.com/owner/repo/blob/main/.openhands/microagents/tell-me-a-joke.md"- * constructMicroagentUrl("gitlab", "owner/repo", "microagents/git-helper.md")- * // "https://gitlab.com/owner/repo/-/blob/main/microagents/git-helper.md"- * constructMicroagentUrl("bitbucket", "owner/repo", ".openhands/microagents/docker-helper.md")- * // "https://bitbucket.org/owner/repo/src/main/.openhands/microagents/docker-helper.md"- */-export const constructMicroagentUrl = (- gitProvider: Provider,- repositoryName: string,- microagentPath: string,- host?: string | null,-): string => {- const baseUrl = ensureHttpsPrefix(host);-- switch (gitProvider) {- case "github":- return `${baseUrl}/${repositoryName}/blob/main/${microagentPath}`;- case "forgejo":- return `${baseUrl}/${repositoryName}/src/branch/main/${microagentPath}`;- case "gitlab":- return `${baseUrl}/${repositoryName}/-/blob/main/${microagentPath}`;- case "bitbucket":- return `${baseUrl}/${repositoryName}/src/main/${microagentPath}`;- case "bitbucket_data_center": {- const [project, repo] = repositoryName.split("/");- return `${baseUrl}/projects/${project}/repos/${repo}/browse/${microagentPath}?at=refs/heads/main`;- }- case "azure_devops": {- // Azure DevOps format: org/project/repo- const parts = repositoryName.split("/");- if (parts.length === 3) {- const [org, project, repo] = parts;- return `${baseUrl}/${org}/${project}/_git/${repo}?path=/${microagentPath}&version=GBmain`;- }- return "";- }- default:- return "";- }-};-/*** Extract repository owner, repo name, and file path from repository and microagent data* @param selectedRepository The selected repository object with full_name propertydiff --git a/openhands/app_server/secrets/secrets_router.py b/openhands/app_server/secrets/secrets_router.pyindex f28d560229..5e5da9e182 100644--- a/openhands/app_server/secrets/secrets_router.py+++ b/openhands/app_server/secrets/secrets_router.py@@ -295,7 +295,7 @@ async def update_custom_secret(if existing_secrets:# Check if the secret to update existsif secret_id not in existing_secrets.custom_secrets:- return HTTPException(+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f'Secret with ID {secret_id} not found',)diff --git a/openhands/app_server/settings/file_settings_store.py b/openhands/app_server/settings/file_settings_store.pyindex 2b17ccf10a..c4928362cb 100644--- a/openhands/app_server/settings/file_settings_store.py+++ b/openhands/app_server/settings/file_settings_store.py@@ -18,6 +18,16 @@ class FileSettingsStore(SettingsStore):try:json_str = await call_sync_from_async(self.file_store.read, self.path)kwargs = json.loads(json_str)+ # Seed a Default profile from legacy agent_settings.llm when+ # llm_profiles is absent — pre-llm_profiles settings.json files+ # would otherwise present an empty profiles UI on upgrade.+ if 'llm_profiles' not in kwargs:+ legacy_llm = (kwargs.get('agent_settings') or {}).get('llm')+ if isinstance(legacy_llm, dict) and legacy_llm.get('model'):+ kwargs['llm_profiles'] = {+ 'profiles': {'Default': legacy_llm},+ 'active': 'Default',+ }settings = Settings(**kwargs)# Turn on V1 in OpenHandsdiff --git a/openhands/app_server/settings/llm_profiles.py b/openhands/app_server/settings/llm_profiles.pyindex c01d87f332..189ae4b5e3 100644--- a/openhands/app_server/settings/llm_profiles.py+++ b/openhands/app_server/settings/llm_profiles.py@@ -6,6 +6,7 @@ from pydantic import (BaseModel,ConfigDict,Field,+ SecretStr,SerializationInfo,ValidationError,field_serializer,@@ -16,6 +17,22 @@ from pydantic import (from openhands.app_server.utils.logger import openhands_logger as loggerfrom openhands.sdk.llm import LLM++def has_real_api_key(api_key: Any) -> bool:+ """Return True iff ``api_key`` carries a non-empty value.++ A ``SecretStr('')`` should report as *not set* — otherwise the UI tells+ the user a key is stored when it isn't. Mirrors the check used in+ ``Settings.llm_api_key_is_set``.+ """+ if api_key is None:+ return False+ secret_value = (+ api_key.get_secret_value() if isinstance(api_key, SecretStr) else str(api_key)+ )+ return bool(secret_value and secret_value.strip())++# Soft cap — keeps Settings payload bounded and blocks per-user storage# blow-ups. Tune if product requirements change.MAX_PROFILES_PER_USER: Final[int] = 10@@ -136,7 +153,7 @@ class LLMProfiles(BaseModel):'name': name,'model': llm.model,'base_url': llm.base_url,- 'api_key_set': llm.api_key is not None,+ 'api_key_set': has_real_api_key(llm.api_key),}for name, llm in self.profiles.items()]diff --git a/openhands/app_server/settings/settings_models.py b/openhands/app_server/settings/settings_models.pyindex 1f80e89081..bb7a3dd1ac 100644--- a/openhands/app_server/settings/settings_models.py+++ b/openhands/app_server/settings/settings_models.py@@ -274,10 +274,32 @@ class Settings(BaseModel):Raises :class:`ProfileNotFoundError` if ``name`` isn't a saved profile."""+ # Copy the LLM so post-activation fixups (e.g. resolving ``base_url``+ # against the provider default) don't bleed back into the saved+ # profile. ``model_copy(update={'llm': llm})`` is shallow, so the+ # update value is shared with ``llm_profiles.profiles[name]``.llm = self.llm_profiles.require(name)- self.agent_settings = self.agent_settings.model_copy(update={'llm': llm})+ self.agent_settings = self.agent_settings.model_copy(+ update={'llm': llm.model_copy()}+ )self.llm_profiles.active = name+ def delete_profile(self, name: str) -> bool:+ """Delete a saved profile, promoting a fallback when it was active.++ Returns False if the profile didn't exist; True otherwise. When the+ deleted profile was active and other profiles remain, switches to+ the first remaining one (insertion order — same ordering ``rename``+ relies on) so the user isn't left without an active LLM.+ """+ was_active = self.llm_profiles.active == name+ if not self.llm_profiles.delete(name):+ return False+ if was_active and self.llm_profiles.profiles:+ fallback = next(iter(self.llm_profiles.profiles))+ self.switch_to_profile(fallback)+ return True+@model_validator(mode='before')@classmethoddef _normalize_inputs(cls, data: dict | object) -> dict | object:diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.pyindex 9f796d0c8f..61ebb4907d 100644--- a/openhands/app_server/settings/settings_router.py+++ b/openhands/app_server/settings/settings_router.py@@ -23,6 +23,7 @@ from openhands.app_server.settings.llm_profiles import (ProfileLimitExceededError,ProfileNotFoundError,StrictLLM,+ has_real_api_key,)from openhands.app_server.settings.settings_models import (GETSettingsModel,@@ -428,7 +429,7 @@ async def get_profile(detail=f"Profile '{name}' not found",)- api_key_set = profile.api_key is not None+ api_key_set = has_real_api_key(profile.api_key)config = profile.model_dump(mode='json')config['api_key'] = None # never echo a mask; use api_key_set instead@@ -509,7 +510,7 @@ async def delete_profile("""async with _user_profile_locks[_profile_lock_key(user_id)]:settings = await settings_store.load()- if settings is not None and settings.llm_profiles.delete(name):+ if settings is not None and settings.delete_profile(name):await settings_store.store(settings)return ProfileMutationResponse(name=name, message=f"Profile '{name}' deleted")diff --git a/tests/unit/app_server/test_profiles_api.py b/tests/unit/app_server/test_profiles_api.pyindex 6d18e20cf8..3dee20f3bd 100644--- a/tests/unit/app_server/test_profiles_api.py+++ b/tests/unit/app_server/test_profiles_api.py@@ -440,6 +440,29 @@ async def test_list_profiles_reports_api_key_set_per_row(test_client, settings_sassert rows['no-key']['api_key_set'] is False+async def test_api_key_set_is_false_for_empty_secret(test_client, settings_store):+ """``SecretStr('')`` is *not* a stored key — the UI must not claim one is."""+ settings = _base_settings()+ settings.llm_profiles.save(+ 'blank', LLM(model='openai/gpt-4o', api_key=SecretStr(''))+ )+ settings.llm_profiles.save(+ 'whitespace', LLM(model='openai/gpt-4o', api_key=SecretStr(' '))+ )+ await _seed(settings_store, settings)++ rows = {+ p['name']: p+ for p in test_client.get('/api/v1/settings/profiles').json()['profiles']+ }+ assert rows['blank']['api_key_set'] is False+ assert rows['whitespace']['api_key_set'] is False++ detail = test_client.get('/api/v1/settings/profiles/blank').json()+ assert detail['api_key_set'] is False++@pytest.mark.asyncioasync def test_save_profile_rejects_unknown_llm_field(test_client, settings_store):"""StrictLLM forbids extras → typo in an LLM field returns 422 instead of a silent 201."""@@ -527,10 +550,35 @@ async def test_activate_profile_applies_base_url_fixup(test_client, settings_stoassert response.status_code == 200stored = await settings_store.load()- # Fixup inferred the proxy URL; profile itself remains unchanged.assert stored.agent_settings.llm.base_url is not None+async def test_activate_does_not_mutate_saved_profile_base_url(+ test_client, settings_store+):+ """Activate must not bleed ``_post_merge_llm_fixups`` into the saved+ profile. A shallow ``model_copy(update={'llm': llm})`` would share the+ LLM reference and propagate the fixup to ``llm_profiles[name]``.++ Use a custom base_url (not an openhands/* model) so the LLM SDK does+ not auto-resolve base_url at construction time — that would mask the+ mutation we want to detect.+ """+ settings = _base_settings()+ settings.llm_profiles.save(+ 'custom',+ LLM(model='openai/gpt-4o', base_url='https://custom.example.com'),+ )+ await _seed(settings_store, settings)++ response = test_client.post('/api/v1/settings/profiles/custom/activate')+ assert response.status_code == 200++ stored = await settings_store.load()+ assert stored.llm_profiles.get('custom').base_url == 'https://custom.example.com'++# ── POST /profiles/{name}/rename ─────────────────────────────────diff --git a/tests/unit/storage/data_models/test_settings.py b/tests/unit/storage/data_models/test_settings.pyindex 7004afa324..2b2217c346 100644--- a/tests/unit/storage/data_models/test_settings.py+++ b/tests/unit/storage/data_models/test_settings.py@@ -316,6 +316,47 @@ def test_switch_to_profile_preserves_other_agent_settings():assert 's' in settings.agent_settings.mcp_config.mcpServers+def test_delete_active_profile_promotes_remaining_one():+ settings = Settings()+ settings.llm_profiles.save('a', LLM(model='openai/gpt-4o'))+ settings.llm_profiles.save('b', LLM(model='anthropic/claude-opus-4'))+ settings.switch_to_profile('a')++ assert settings.delete_profile('a') is True++ assert 'a' not in settings.llm_profiles.profiles+ assert settings.llm_profiles.active == 'b'+ assert settings.agent_settings.llm.model == 'anthropic/claude-opus-4'+++def test_delete_inactive_profile_does_not_touch_active():+ settings = Settings()+ settings.llm_profiles.save('a', LLM(model='openai/gpt-4o'))+ settings.llm_profiles.save('b', LLM(model='anthropic/claude-opus-4'))+ settings.switch_to_profile('a')++ assert settings.delete_profile('b') is True++ assert settings.llm_profiles.active == 'a'+ assert settings.agent_settings.llm.model == 'openai/gpt-4o'+++def test_delete_only_profile_clears_active():+ settings = Settings()+ settings.llm_profiles.save('only', LLM(model='openai/gpt-4o'))+ settings.switch_to_profile('only')++ assert settings.delete_profile('only') is True++ assert settings.llm_profiles.profiles == {}+ assert settings.llm_profiles.active is None+++def test_delete_missing_profile_returns_false():+ settings = Settings()+ assert settings.delete_profile('nope') is False++def test_update_ignores_llm_profiles_payload():"""``Settings.update`` refuses to mutate ``llm_profiles``; profile changesmust go through the dedicated endpoints (which enforce name rules, thediff --git a/tests/unit/storage/settings/test_file_settings_store.py b/tests/unit/storage/settings/test_file_settings_store.pyindex cc68f7bfe7..5a859e951b 100644--- a/tests/unit/storage/settings/test_file_settings_store.py+++ b/tests/unit/storage/settings/test_file_settings_store.py@@ -1,3 +1,4 @@+import jsonimport osfrom unittest.mock import MagicMock, patch@@ -96,6 +97,60 @@ async def test_store_and_load_data(file_settings_store):)+async def test_load_seeds_default_profile_from_legacy_llm(file_settings_store):+ legacy_payload = {+ 'agent_settings': {+ 'llm': {+ 'model': 'openai/gpt-4o',+ 'api_key': 'legacy-key',+ 'base_url': 'https://example.com',+ },+ },+ }+ file_settings_store.file_store.read.return_value = json.dumps(legacy_payload)++ loaded = await file_settings_store.load()++ assert loaded is not None+ assert loaded.llm_profiles.active == 'Default'+ default_profile = loaded.llm_profiles.require('Default')+ assert default_profile.model == 'openai/gpt-4o'+ assert default_profile.base_url == 'https://example.com'+ assert default_profile.api_key.get_secret_value() == 'legacy-key'+++async def test_load_does_not_overwrite_existing_profiles(file_settings_store):+ payload = {+ 'agent_settings': {+ 'llm': {'model': 'openai/gpt-4o', 'api_key': 'legacy-key'},+ },+ 'llm_profiles': {+ 'profiles': {'Saved': {'model': 'anthropic/claude-opus-4'}},+ 'active': 'Saved',+ },+ }+ file_settings_store.file_store.read.return_value = json.dumps(payload)++ loaded = await file_settings_store.load()++ assert loaded is not None+ assert set(loaded.llm_profiles.profiles) == {'Saved'}+ assert loaded.llm_profiles.active == 'Saved'+++async def test_load_skips_seeding_when_no_legacy_model(file_settings_store):+ file_settings_store.file_store.read.return_value = json.dumps({})++ loaded = await file_settings_store.load()++ assert loaded is not None+ assert loaded.llm_profiles.profiles == {}+ assert loaded.llm_profiles.active is None++@pytest.mark.asyncioasync def test_get_instance():mock_store = MagicMock(spec=FileStore)