🙌 OpenHands: AI-Driven Development
feat(agent-profiles): Agent Profiles — Settings → Agent as the profile library (local + cloud) (#1571)
simonrosenberg54d718ad4e96
diff --git a/.github/workflows/mock-llm-docker-e2e.yml b/.github/workflows/mock-llm-docker-e2e.ymlindex a2b5acb8d1..13c128b8d8 100644--- a/.github/workflows/mock-llm-docker-e2e.yml+++ b/.github/workflows/mock-llm-docker-e2e.yml@@ -158,8 +158,17 @@ jobs:exit 0fi- SDK_REF=$(gh api "/repos/OpenHands/software-agent-sdk/pulls/${SDK_PR}" --jq '.head.ref')- SDK_SHA=$(gh api "/repos/OpenHands/software-agent-sdk/pulls/${SDK_PR}" --jq '.head.sha')+ # The matched number may belong to an issue rather than a PR — GitHub's+ # "#NNNN" shorthand and "/pull/NNNN" URL text look identical for both in+ # a PR description, but the /pulls/{number} endpoint 404s for an issue+ # number. Degrade gracefully to "no linked PR" (falls back to the+ # released SDK version below) instead of failing the job.+ SDK_PR_JSON=$(gh api "/repos/OpenHands/software-agent-sdk/pulls/${SDK_PR}" 2>/dev/null) || {+ echo "software-agent-sdk#${SDK_PR} is not an open PR (may be an issue) — using the released SDK version."+ exit 0+ }+ SDK_REF=$(jq -r '.head.ref' <<<"$SDK_PR_JSON")+ SDK_SHA=$(jq -r '.head.sha' <<<"$SDK_PR_JSON")echo "Using software-agent-sdk PR #${SDK_PR} branch: ${SDK_REF} (${SDK_SHA})"echo "git_ref=${SDK_SHA}" >> "$GITHUB_OUTPUT"diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex 8df624ac6b..3c218dfc3f 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -654,6 +654,38 @@ describe("AgentServerConversationService", () => {expect(conversation?.llm_model).toBe("Claude Opus 4.7");});+ it("sources acp_server from the agent when the acpserver tag is absent", async () => {+ // Profile launches don't stamp the ``acpserver`` tag client-side, so the+ // provider identity must survive from ``agent.acp_server`` (SDK #3692)+ // through ``normalizeAgent``. Without it the chip degrades to a generic+ // "ACP" and the in-conversation model picker shows no options (#1571).+ mockHttpGet.mockResolvedValue({+ data: [+ {+ id: "conv-acp-server-from-agent",+ created_at: "2024-01-01",+ updated_at: "2024-01-01",+ agent: {+ kind: "ACPAgent",+ acp_server: "claude-code",+ acp_model: "claude-sonnet-4-5",+ llm: { model: "acp-managed" },+ },+ // No ``acpserver`` tag — mirrors an agent_profile_id launch.+ tags: {},+ },+ ],+ });++ const [conversation] =+ await AgentServerConversationService.batchGetAppConversations([+ "conv-acp-server-from-agent",+ ]);++ expect(conversation?.agent_kind).toBe("acp");+ expect(conversation?.acp_server).toBe("claude-code");+ });+it("falls back to acp_model when SDK runtime fields are absent on the wire", async () => {// Older agent-servers don't populate ``current_model_*``. The// adapter must still surface a model on the chip — falling throughdiff --git a/__tests__/components/features/chat/components/chat-input-actions.test.tsx b/__tests__/components/features/chat/components/chat-input-actions.test.tsxindex 7c137c7756..b7fb19bed0 100644--- a/__tests__/components/features/chat/components/chat-input-actions.test.tsx+++ b/__tests__/components/features/chat/components/chat-input-actions.test.tsx@@ -30,9 +30,29 @@ vi.mock("#/components/features/chat/change-agent-button", () => ({ChangeAgentButton: () => <div data-testid="change-agent-button-stub" />,}));-vi.mock("#/components/features/chat/switch-profile-button", () => ({- SwitchProfileButton: () => <div data-testid="switch-profile-button-stub" />,-}));+vi.mock(+ "#/components/features/chat/components/chat-input-profile-picker",+ () => ({+ ChatInputProfilePicker: () => (+ <div data-testid="agent-profile-picker-stub" />+ ),+ ChatInputProfileMenuContent: () => (+ <div data-testid="agent-profile-menu-stub" />+ ),+ }),+);++vi.mock(+ "#/components/features/chat/components/chat-input-llm-profile-picker",+ () => ({+ ChatInputLlmProfilePicker: () => (+ <div data-testid="llm-profile-picker-stub" />+ ),+ ChatInputLlmProfileMenuContent: () => (+ <div data-testid="llm-profile-menu-stub" />+ ),+ }),+);vi.mock("#/hooks/query/use-active-conversation", () => ({useActiveConversation: () => useActiveConversationMock(),@@ -65,22 +85,43 @@ describe("ChatInputActions", () => {useActiveConversationMock.mockReturnValue({ data: undefined });});- it("renders the SwitchProfileButton on a local backend", () => {+ it("renders the AgentProfile picker on the home page (local)", () => {+ useActiveConversationMock.mockReturnValue({ data: undefined });++ renderWithProviders(<ChatInputActions disabled={false} />, {+ navigation: { conversationId: null },+ });++ // Home keeps the start-new/activate AgentProfile picker (#3727).+ expect(screen.getByTestId("agent-profile-picker-stub")).toBeInTheDocument();+ expect(+ screen.queryByTestId("llm-profile-picker-stub"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("chat-input-llm-model"),+ ).not.toBeInTheDocument();+ });++ it("renders the LLM-profile switcher inside a local OpenHands conversation", () => {useActiveConversationMock.mockReturnValue({data: { conversation_id: "test-conversation-id", llm_model: "gpt-4o" },});- renderWithProviders(<ChatInputActions disabled={false} />);+ renderWithProviders(<ChatInputActions disabled={false} />, {+ navigation: { conversationId: "test-conversation-id" },+ });+ // In a conversation the user live-switches the LLM profile, not start-new.+ expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();expect(- screen.getByTestId("switch-profile-button-stub"),- ).toBeInTheDocument();+ screen.queryByTestId("agent-profile-picker-stub"),+ ).not.toBeInTheDocument();expect(screen.queryByTestId("chat-input-llm-model"),).not.toBeInTheDocument();});- it("renders the static model label for local ACP conversations", () => {+ it("renders the model switcher inside a local ACP conversation", () => {useActiveConversationMock.mockReturnValue({data: {conversation_id: "test-conversation-id",@@ -89,22 +130,29 @@ describe("ChatInputActions", () => {},});- renderWithProviders(<ChatInputActions disabled={false} />);+ renderWithProviders(<ChatInputActions disabled={false} />, {+ navigation: { conversationId: "test-conversation-id" },+ });- expect(screen.getByTestId("chat-input-llm-model")).toHaveAttribute(- "title",- "claude-sonnet-4-6",- );+ // ACP in a conversation live-switches the running model via ChatInputModel.+ expect(screen.getByTestId("chat-input-llm-model")).toBeInTheDocument();+ expect(+ screen.queryByTestId("agent-profile-picker-stub"),+ ).not.toBeInTheDocument();expect(- screen.queryByTestId("switch-profile-button-stub"),+ screen.queryByTestId("llm-profile-picker-stub"),).not.toBeInTheDocument();});- it("renders the SwitchProfileButton on a cloud backend", () => {+ it("renders the active conversation model in a cloud ACP conversation", () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });useActiveConversationMock.mockReturnValue({- data: { conversation_id: "test-conversation-id", llm_model: "gpt-4o" },+ data: {+ conversation_id: "test-conversation-id",+ agent_kind: "acp",+ llm_model: "gpt-4o",+ },});renderWithProviders(@@ -113,21 +161,23 @@ describe("ChatInputActions", () => {</ActiveBackendProvider>,);- // Cloud now manages the LLM through profiles, so the composer shows the- // profile switcher (same as local), not the static cloud model label.- expect(- screen.getByTestId("switch-profile-button-stub"),- ).toBeInTheDocument();+ expect(screen.getByTestId("chat-input-llm-model")).toHaveTextContent(+ "gpt-4o",+ );expect(- screen.queryByTestId("chat-input-llm-model"),+ screen.queryByTestId("agent-profile-picker-stub"),).not.toBeInTheDocument();});- it("renders the SwitchProfileButton on cloud even when the conversation has no llm_model", () => {+ it("omits the model label on cloud when the active ACP conversation has no llm_model", () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });useActiveConversationMock.mockReturnValue({- data: { conversation_id: "test-conversation-id", llm_model: null },+ data: {+ conversation_id: "test-conversation-id",+ agent_kind: "acp",+ llm_model: null,+ },});renderWithProviders(@@ -136,23 +186,19 @@ describe("ChatInputActions", () => {</ActiveBackendProvider>,);- expect(- screen.getByTestId("switch-profile-button-stub"),- ).toBeInTheDocument();expect(screen.queryByTestId("chat-input-llm-model"),).not.toBeInTheDocument();});- it("renders the static model label for cloud ACP conversations", () => {+ it("renders the LLM-profile switcher inside a cloud OpenHands conversation", () => {+ // /switch_profile is a real endpoint on both backends (cloud proxies+ // POST /api/v1/app-conversations/{id}/switch_profile) — cloud OpenHands+ // conversations get the same live-switch picker as local (#1571 review).setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });useActiveConversationMock.mockReturnValue({- data: {- conversation_id: "test-conversation-id",- agent_kind: "acp",- llm_model: "claude-sonnet-4-6",- },+ data: { conversation_id: "test-conversation-id", llm_model: "gpt-4o" },});renderWithProviders(@@ -161,14 +207,12 @@ describe("ChatInputActions", () => {</ActiveBackendProvider>,);- // ACP conversations keep the static model label on cloud too — the switch- // gate is now driven solely by isAcpContext, not the backend kind.- expect(screen.getByTestId("chat-input-llm-model")).toHaveAttribute(- "title",- "claude-sonnet-4-6",- );+ expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();expect(- screen.queryByTestId("switch-profile-button-stub"),+ screen.queryByTestId("agent-profile-picker-stub"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("chat-input-llm-model"),).not.toBeInTheDocument();});diff --git a/__tests__/components/features/chat/components/chat-input-llm-profile-picker.test.tsx b/__tests__/components/features/chat/components/chat-input-llm-profile-picker.test.tsxnew file mode 100644index 0000000000..172499fba9--- /dev/null+++ b/__tests__/components/features/chat/components/chat-input-llm-profile-picker.test.tsx@@ -0,0 +1,89 @@+import { fireEvent, screen } from "@testing-library/react";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderWithProviders } from "test-utils";++const useChatInputLlmProfileStateMock = vi.fn();++vi.mock("#/hooks/use-chat-input-llm-profile-state", () => ({+ useChatInputLlmProfileState: () => useChatInputLlmProfileStateMock(),+}));++// eslint-disable-next-line import/first+import { ChatInputLlmProfilePicker } from "#/components/features/chat/components/chat-input-llm-profile-picker";++const PROFILES = [+ {+ name: "Fast",+ model: "openai/gpt-4o-mini",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "Smart",+ model: "anthropic/claude-opus",+ base_url: null,+ api_key_set: true,+ },+];++const selectProfile = vi.fn();++function state(overrides = {}) {+ return {+ profiles: PROFILES,+ currentProfileName: "Fast",+ currentProfileModel: "openai/gpt-4o-mini",+ isLoading: false,+ isSwitching: false,+ selectProfile,+ ...overrides,+ };+}++describe("ChatInputLlmProfilePicker", () => {+ beforeEach(() => {+ selectProfile.mockReset();+ useChatInputLlmProfileStateMock.mockReset();+ useChatInputLlmProfileStateMock.mockReturnValue(state());+ });++ it("renders nothing while loading or when there are no profiles", () => {+ useChatInputLlmProfileStateMock.mockReturnValue(+ state({ profiles: [], isLoading: false }),+ );+ const { container } = renderWithProviders(<ChatInputLlmProfilePicker />);+ expect(container).toBeEmptyDOMElement();+ });++ it("labels the pill with the current profile name", () => {+ renderWithProviders(<ChatInputLlmProfilePicker />);+ expect(screen.getByTestId("chat-input-llm-profile")).toHaveTextContent(+ "Fast",+ );+ });++ it("live-switches to the picked profile", () => {+ renderWithProviders(<ChatInputLlmProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-llm-profile"));+ fireEvent.click(screen.getByTestId("chat-input-llm-profile-option-Smart"));++ expect(selectProfile).toHaveBeenCalledWith("Smart");+ });++ it("does not switch when the current profile is re-selected", () => {+ renderWithProviders(<ChatInputLlmProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-llm-profile"));+ fireEvent.click(screen.getByTestId("chat-input-llm-profile-option-Fast"));++ expect(selectProfile).not.toHaveBeenCalled();+ });++ it("links to the LLM profiles settings page", () => {+ const { container } = renderWithProviders(<ChatInputLlmProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-llm-profile"));++ expect(+ container.ownerDocument.querySelector('a[href="/settings/llm"]'),+ ).not.toBeNull();+ });+});diff --git a/__tests__/components/features/chat/components/chat-input-model.test.tsx b/__tests__/components/features/chat/components/chat-input-model.test.tsxindex 57d1253d49..8e8ac2589f 100644--- a/__tests__/components/features/chat/components/chat-input-model.test.tsx+++ b/__tests__/components/features/chat/components/chat-input-model.test.tsx@@ -100,7 +100,10 @@ describe("ChatInputModel", () => {// list chip), resolved from ``acp_server`` + the raw ``acp_model`` id.expect(model).toHaveAttribute("title", "Claude Sonnet 4.6");fireEvent.click(model);- expect(screen.getByRole("link")).toHaveAttribute("href", "/settings/agent");+ expect(screen.getByRole("link")).toHaveAttribute(+ "href",+ "/settings/agents",+ );});it("does not fall back to the OpenHands settings model for active ACP conversations", () => {@@ -157,7 +160,10 @@ describe("ChatInputModel", () => {const model = screen.getByTestId("chat-input-llm-model");expect(model).toHaveAttribute("title", "gemini-2.5-pro");fireEvent.click(model);- expect(screen.getByRole("link")).toHaveAttribute("href", "/settings/agent");+ expect(screen.getByRole("link")).toHaveAttribute(+ "href",+ "/settings/agents",+ );});it("renders nothing when neither the conversation nor settings provide an llm_model", () => {@@ -221,7 +227,10 @@ describe("ChatInputModel", () => {// acp-providers.ts.expect(model).toHaveAttribute("title", "Claude Opus 4.8 (1M)");fireEvent.click(model);- expect(screen.getByRole("link")).toHaveAttribute("href", "/settings/agent");+ expect(screen.getByRole("link")).toHaveAttribute(+ "href",+ "/settings/agents",+ );});it("renders the provider's available models as selectable rows for an ACP conversation", () => {@@ -326,6 +335,9 @@ describe("ChatInputModel", () => {).toBeInTheDocument();const popover = screen.getByTestId("chat-input-llm-model-popover");expect(popover).toHaveTextContent("Claude Sonnet 4.6");- expect(screen.getByRole("link")).toHaveAttribute("href", "/settings/agent");+ expect(screen.getByRole("link")).toHaveAttribute(+ "href",+ "/settings/agents",+ );});});diff --git a/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx b/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsxnew file mode 100644index 0000000000..38f2b7a1a5--- /dev/null+++ b/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx@@ -0,0 +1,85 @@+import { fireEvent, screen } from "@testing-library/react";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderWithProviders } from "test-utils";++const useAgentProfilesMock = vi.fn();+const activateProfileMutate = vi.fn();++vi.mock("#/hooks/query/use-agent-profiles", () => ({+ useAgentProfiles: () => useAgentProfilesMock(),+}));++vi.mock("#/hooks/mutation/use-activate-agent-profile", () => ({+ useActivateAgentProfile: () => ({+ mutate: activateProfileMutate,+ isPending: false,+ }),+ ACTIVATE_AGENT_PROFILE_MUTATION_KEY: ["activate-agent-profile"],+}));++import { ChatInputProfilePicker } from "#/components/features/chat/components/chat-input-profile-picker";++const PROFILES = [+ { id: "id-default", name: "Default", agent_kind: "openhands" },+ { id: "id-codex", name: "Codex", agent_kind: "acp" },+];++// The picker is home-only (a running conversation shows the LLM-profile / model+// picker instead), so selecting a profile activates it as the launch default.+describe("ChatInputProfilePicker", () => {+ beforeEach(() => {+ useAgentProfilesMock.mockReset();+ activateProfileMutate.mockReset();++ useAgentProfilesMock.mockReturnValue({+ data: { profiles: PROFILES, active_agent_profile_id: "id-default" },+ isLoading: false,+ });+ });++ it("renders nothing when there are no profiles", () => {+ useAgentProfilesMock.mockReturnValue({+ data: { profiles: [], active_agent_profile_id: null },+ isLoading: false,+ });++ const { container } = renderWithProviders(<ChatInputProfilePicker />);+ expect(container).toBeEmptyDOMElement();+ });++ it("labels the button with the active profile", () => {+ renderWithProviders(<ChatInputProfilePicker />);+ expect(screen.getByTestId("chat-input-agent-profile")).toHaveTextContent(+ "Default",+ );+ });++ it("activates the picked profile", () => {+ renderWithProviders(<ChatInputProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-agent-profile"));+ fireEvent.click(+ screen.getByTestId("chat-input-agent-profile-option-Codex"),+ );++ expect(activateProfileMutate).toHaveBeenCalledWith("id-codex");+ });++ it("does not activate when the active profile is re-selected", () => {+ renderWithProviders(<ChatInputProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-agent-profile"));+ fireEvent.click(+ screen.getByTestId("chat-input-agent-profile-option-Default"),+ );++ expect(activateProfileMutate).not.toHaveBeenCalled();+ });++ it("links to the AgentProfile library in settings", () => {+ const { container } = renderWithProviders(<ChatInputProfilePicker />);+ fireEvent.click(screen.getByTestId("chat-input-agent-profile"));++ expect(+ container.ownerDocument.querySelector('a[href="/settings/agents"]'),+ ).not.toBeNull();+ });+});diff --git a/__tests__/components/features/chat/components/resolve-picker-kind.test.ts b/__tests__/components/features/chat/components/resolve-picker-kind.test.tsnew file mode 100644index 0000000000..573eded5e4--- /dev/null+++ b/__tests__/components/features/chat/components/resolve-picker-kind.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from "vitest";+import {+ resolvePickerKind,+ type ResolvePickerKindInput,+} from "#/components/features/chat/components/resolve-picker-kind";++const base: ResolvePickerKindInput = {+ hasConversation: false,+ isCloud: false,+ isAcp: false,+ profilesAvailable: true,+};++describe("resolvePickerKind", () => {+ describe("home (no active conversation)", () => {+ it("shows the agent-profile picker when profiles are available", () => {+ expect(resolvePickerKind({ ...base, hasConversation: false })).toBe(+ "agent-profile",+ );+ // isCloud / isAcp don't matter once profiles exist.+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: false,+ isCloud: true,+ isAcp: true,+ }),+ ).toBe("agent-profile");+ });++ it("falls back to the LLM-profile picker on local when no profiles exist", () => {+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: false,+ isCloud: false,+ profilesAvailable: false,+ }),+ ).toBe("llm-profile");+ });++ it("falls back to the model picker on cloud when no profiles exist", () => {+ // Cloud has no home LLM-profile activate path.+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: false,+ isCloud: true,+ profilesAvailable: false,+ }),+ ).toBe("model");+ });+ });++ describe("inside a conversation", () => {+ it("shows the model picker for an ACP conversation regardless of backend", () => {+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: true,+ isCloud: false,+ isAcp: true,+ }),+ ).toBe("model");+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: true,+ isCloud: true,+ isAcp: true,+ }),+ ).toBe("model");+ });++ it("shows the LLM-profile picker for an OpenHands conversation regardless of backend", () => {+ // /switch_profile is a real endpoint on both backends (cloud proxies+ // POST /api/v1/app-conversations/{id}/switch_profile) — no cloud+ // restriction here.+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: true,+ isCloud: false,+ isAcp: false,+ }),+ ).toBe("llm-profile");+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: true,+ isCloud: true,+ isAcp: false,+ }),+ ).toBe("llm-profile");+ });++ it("ignores profilesAvailable once a conversation is active", () => {+ expect(+ resolvePickerKind({+ ...base,+ hasConversation: true,+ isCloud: false,+ isAcp: false,+ profilesAvailable: false,+ }),+ ).toBe("llm-profile");+ });+ });+});diff --git a/__tests__/components/features/chat/switch-profile-button.test.tsx b/__tests__/components/features/chat/switch-profile-button.test.tsxdeleted file mode 100644index b6e3b027bf..0000000000--- a/__tests__/components/features/chat/switch-profile-button.test.tsx+++ /dev/null@@ -1,246 +0,0 @@-import React from "react";-import { fireEvent, screen } from "@testing-library/react";-import { describe, it, expect, vi, beforeEach } from "vitest";-import { renderWithProviders } from "test-utils";--const useLlmProfilesMock = vi.fn();-const useActiveConversationMock = vi.fn();-const useSettingsMock = vi.fn();-const useSwitchLlmProfileAndLogMock = vi.fn();-const useOptionalConversationIdMock = vi.fn();--vi.mock("#/hooks/query/use-llm-profiles", () => ({- useLlmProfiles: () => useLlmProfilesMock(),-}));--vi.mock("#/hooks/query/use-active-conversation", () => ({- useActiveConversation: () => useActiveConversationMock(),-}));--vi.mock("#/hooks/query/use-settings", () => ({- useSettings: () => useSettingsMock(),-}));--vi.mock("#/hooks/mutation/use-switch-llm-profile-and-log", () => ({- useSwitchLlmProfileAndLog: () => useSwitchLlmProfileAndLogMock(),-}));--vi.mock("#/hooks/use-conversation-id", () => ({- useOptionalConversationId: () => useOptionalConversationIdMock(),-}));--import { SwitchProfileButton } from "#/components/features/chat/switch-profile-button";--const profiles = [- {- name: "haiku",- model: "anthropic/claude-haiku",- base_url: null,- api_key_set: true,- },- { name: "gpt", model: "openai/gpt-4o", base_url: null, api_key_set: true },-];--// Two profiles that resolve to the SAME underlying model but differ by name-// — the #1082 scenario. "broken" is listed first (alphabetical) so a-// model-only match would wrongly pick it over the user's actual choice.-const sameModelProfiles = [- {- name: "broken",- model: "openhands/claude-sonnet-4-6",- base_url: null,- api_key_set: true,- },- {- name: "claude-sonnet-4.6",- model: "openhands/claude-sonnet-4-6",- base_url: null,- api_key_set: true,- },-];--describe("SwitchProfileButton", () => {- const switchAndLog = vi.fn();-- beforeEach(() => {- switchAndLog.mockReset();- useLlmProfilesMock.mockReset();- useActiveConversationMock.mockReset();- useSettingsMock.mockReset();- useSwitchLlmProfileAndLogMock.mockReset();- useOptionalConversationIdMock.mockReset();-- useLlmProfilesMock.mockReturnValue({- data: { profiles, active_profile: "haiku" },- });- useActiveConversationMock.mockReturnValue({ data: undefined });- useSettingsMock.mockReturnValue({ data: undefined });- useSwitchLlmProfileAndLogMock.mockReturnValue({- switchAndLog,- isPending: false,- });- useOptionalConversationIdMock.mockReturnValue({ conversationId: "conv-1" });- });-- it("renders nothing when no profiles are available", () => {- useLlmProfilesMock.mockReturnValue({- data: { profiles: [], active_profile: null },- });-- renderWithProviders(<SwitchProfileButton />);-- expect(- screen.queryByTestId("switch-profile-button"),- ).not.toBeInTheDocument();- });-- it("labels the button with the user-level active profile on the home page (no conversation)", () => {- useOptionalConversationIdMock.mockReturnValue({ conversationId: null });-- renderWithProviders(<SwitchProfileButton />);-- expect(screen.getByTestId("switch-profile-button")).toHaveTextContent(- "haiku",- );- });-- it("calls switchAndLog with null conversationId when clicked from the home page", () => {- useOptionalConversationIdMock.mockReturnValue({ conversationId: null });-- renderWithProviders(<SwitchProfileButton />);- fireEvent.click(screen.getByTestId("switch-profile-button"));- fireEvent.click(screen.getByTestId("switch-profile-option-gpt"));-- expect(switchAndLog).toHaveBeenCalledWith(null, "gpt");- });-- it("calls switchAndLog with the conversation id when clicked from inside a conversation", () => {- renderWithProviders(<SwitchProfileButton />);- fireEvent.click(screen.getByTestId("switch-profile-button"));- fireEvent.click(screen.getByTestId("switch-profile-option-gpt"));-- expect(switchAndLog).toHaveBeenCalledWith("conv-1", "gpt");- });-- it("no-ops when the user clicks the already-active profile", () => {- renderWithProviders(<SwitchProfileButton />);- fireEvent.click(screen.getByTestId("switch-profile-button"));- fireEvent.click(screen.getByTestId("switch-profile-option-haiku"));-- expect(switchAndLog).not.toHaveBeenCalled();- });-- it("disables the button while a switch is in flight", () => {- useSwitchLlmProfileAndLogMock.mockReturnValue({- switchAndLog,- isPending: true,- });-- renderWithProviders(<SwitchProfileButton />);-- expect(screen.getByTestId("switch-profile-button")).toBeDisabled();- });-- it("renders nothing for ACP conversations even when profiles and a display model exist", () => {- // ACPAgent conversations route prompts to a CLI subprocess whose model is- // set via ``acp_model`` in Settings → Agent, not by the LLM-profile- // picker. Letting the user "switch the LLM" here would silently no-op- // against the running subprocess — confusing UX. The button hides; the- // user's path is the ACP model field on the agent settings page.- useActiveConversationMock.mockReturnValue({- data: {- id: "conv-1",- agent_kind: "acp",- llm_model: "claude-sonnet-4-6",- },- });-- renderWithProviders(<SwitchProfileButton />);-- expect(- screen.queryByTestId("switch-profile-button"),- ).not.toBeInTheDocument();- });-- it("hides the picker on the home page when ACP is the default agent", () => {- // Home-screen gating: there's no active conversation, so the- // per-conversation ``agent_kind`` check can't catch this case.- // Fall back to ``settings.agent_settings.agent_kind`` — that's the- // kind the next-created conversation will inherit, and showing- // the LLM picker for it would silently no-op once the user starts- // chatting. Mirrors the ACP nav gating elsewhere in the app.- useActiveConversationMock.mockReturnValue({ data: undefined });- useSettingsMock.mockReturnValue({- data: {- agent_settings: { agent_kind: "acp", acp_server: "claude-code" },- },- });-- renderWithProviders(<SwitchProfileButton />);-- expect(- screen.queryByTestId("switch-profile-button"),- ).not.toBeInTheDocument();- });-- it("labels the button with the conversation's stamped profile when several profiles share a model (#1082)", () => {- useLlmProfilesMock.mockReturnValue({- data: { profiles: sameModelProfiles, active_profile: "broken" },- });- useActiveConversationMock.mockReturnValue({- data: {- id: "conv-1",- agent_kind: "openhands",- llm_model: "openhands/claude-sonnet-4-6",- active_profile: "claude-sonnet-4.6",- },- });-- renderWithProviders(<SwitchProfileButton />);-- const button = screen.getByTestId("switch-profile-button");- expect(button).toHaveTextContent("claude-sonnet-4.6");- expect(button).not.toHaveTextContent("broken");- });-- it("falls back to model-matching when the conversation has no stamped profile", () => {- useLlmProfilesMock.mockReturnValue({- data: { profiles: sameModelProfiles, active_profile: "broken" },- });- useActiveConversationMock.mockReturnValue({- data: {- id: "conv-1",- agent_kind: "openhands",- llm_model: "openhands/claude-sonnet-4-6",- },- });-- renderWithProviders(<SwitchProfileButton />);-- // No stamp (e.g. created by an older client) → first profile whose model- // matches, preserving today's behavior.- expect(screen.getByTestId("switch-profile-button")).toHaveTextContent(- "broken",- );- });-- it("ignores a stamped profile that no longer exists and falls back to model-matching", () => {- useLlmProfilesMock.mockReturnValue({- data: { profiles: sameModelProfiles, active_profile: "broken" },- });- useActiveConversationMock.mockReturnValue({- data: {- id: "conv-1",- agent_kind: "openhands",- llm_model: "openhands/claude-sonnet-4-6",- active_profile: "deleted-profile",- },- });-- renderWithProviders(<SwitchProfileButton />);-- expect(screen.getByTestId("switch-profile-button")).toHaveTextContent(- "broken",- );- });-});diff --git a/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/__tests__/components/features/conversation-panel/conversation-card.test.tsxindex cd4cc361b9..7cbec5b1bb 100644--- a/__tests__/components/features/conversation-panel/conversation-card.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-card.test.tsx@@ -644,6 +644,8 @@ describe("ConversationCard", () => {);const chip = screen.getByTestId("conversation-card-agent-chip");+ // A raw model string not in the registry passes through verbatim+ // (label resolution for known IDs is covered by the next test).expect(chip).toHaveTextContent("raw-model-id");expect(chip).toHaveAttribute("title", "Claude Code · raw-model-id");expect(diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsxnew file mode 100644index 0000000000..9654d37706--- /dev/null+++ b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx@@ -0,0 +1,386 @@+import { render, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi, beforeEach } from "vitest";+import userEvent from "@testing-library/user-event";+import { useEffect } from "react";+import type { AgentSettingsSaveControl } from "#/routes/agent-settings";+import { AgentProfilesLocalView } from "#/components/features/settings/agent-profiles/agent-profiles-local-view";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";+import { displayErrorToast } from "#/utils/custom-toast-handlers";++// The embedded Agent settings form is stubbed to emit a caller-provided+// control, so the tests exercise the view's mapping to AgentProfileSaveInput.+let emitControl: AgentSettingsSaveControl | null = null;++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// The view imports the NAMED `AgentSettingsScreen` export (not the route's+// default, which React Router wraps and would strip the embedded props). Mock+// the named export to match; the factory is hoisted, so define the stub inline.+vi.mock("#/routes/agent-settings", () => {+ const MockAgentSettings = ({+ onSaveControlChange,+ }: {+ onSaveControlChange?: (c: AgentSettingsSaveControl) => void;+ }) => {+ useEffect(() => {+ if (emitControl) onSaveControlChange?.(emitControl);+ }, [onSaveControlChange]);+ return <div data-testid="mock-agent-settings" />;+ };+ return {+ __esModule: true,+ AgentSettingsScreen: MockAgentSettings,+ default: MockAgentSettings,+ };+});++vi.mock(+ "#/components/features/settings/agent-profiles/agent-profiles-manager",+ () => ({+ AgentProfilesManager: ({+ onAddProfile,+ onEditProfile,+ }: {+ onAddProfile?: () => void;+ onEditProfile?: (profile: { name: string }) => void;+ }) => (+ <>+ <button+ type="button"+ data-testid="add-agent-profile"+ onClick={onAddProfile}+ aria-label="add"+ />+ <button+ type="button"+ data-testid="edit-agent-profile"+ onClick={() => onEditProfile?.({ name: "default" })}+ aria-label="edit"+ />+ </>+ ),+ }),+);++const saveMutate = vi.fn().mockResolvedValue({ name: "x", message: "ok" });+vi.mock("#/hooks/mutation/use-save-agent-profile", () => ({+ useSaveAgentProfile: () => ({ mutateAsync: saveMutate }),+}));++const renameMutate = vi.fn().mockResolvedValue({ name: "x", message: "ok" });+vi.mock("#/hooks/mutation/use-rename-agent-profile", () => ({+ useRenameAgentProfile: () => ({ mutateAsync: renameMutate }),+}));++const agentProfilesData = { profiles: [], active_agent_profile_id: null };+vi.mock("#/hooks/query/use-agent-profiles", () => ({+ useAgentProfiles: () => ({ data: agentProfilesData }),+}));++let llmProfilesData: {+ profiles: { name: string; model: string | null }[];+ active_profile: string | null;+};+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => ({ data: llmProfilesData }),+}));++vi.mock("#/contexts/settings-section-header-context", () => ({+ useSettingsSectionHeader: () => ({ setHideSectionHeader: vi.fn() }),+}));++vi.mock("#/utils/custom-toast-handlers");++vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({+ __esModule: true,+ default: { getProfile: vi.fn(), renameProfile: vi.fn() },+}));++async function openCreateAndName(name: string) {+ const user = userEvent.setup();+ await user.click(screen.getByTestId("add-agent-profile"));+ await screen.findByTestId("mock-agent-settings");+ const input = screen.getByTestId("agent-profile-name-input");+ await user.clear(input);+ await user.type(input, name);+ return user;+}++describe("AgentProfilesLocalView save mapping", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ emitControl = null;+ llmProfilesData = {+ profiles: [{ name: "default", model: "gpt-5" }],+ active_profile: "default",+ };+ });++ it("saves an OpenHands profile with the selected llm_profile_ref", async () => {+ emitControl = {+ agentType: "openhands",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ enable_sub_agents: true,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = await openCreateAndName("my-oh");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ expect(saveMutate).toHaveBeenCalledWith({+ name: "my-oh",+ profile: {+ agent_kind: "openhands",+ enable_sub_agents: true,+ llm_profile_ref: "default",+ },+ });+ });++ it("saves an ACP profile without an llm_profile_ref", async () => {+ emitControl = {+ agentType: "acp",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_command: null,+ acp_args: null,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = await openCreateAndName("my-claude");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ expect(saveMutate).toHaveBeenCalledWith({+ name: "my-claude",+ profile: {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_command: null,+ acp_args: null,+ },+ });+ });++ it("edit-save round-trips stored fields the editor doesn't model", async () => {+ // The seeded `default` profile carries fields the minimal editor never+ // shows; the save is a whole-profile overwrite, so they must ride the+ // payload untouched (with server-managed identity stripped).+ const storedProfile = {+ schema_version: 1,+ id: "p-1",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "default",+ agent: "CodeActAgent",+ system_message_suffix: "Be terse.",+ condenser: { kind: "NoOpCondenserSettings" },+ verification: { critic_enabled: true },+ enable_sub_agents: false,+ enable_switch_llm_tool: false,+ tool_concurrency_limit: 4,+ mcp_server_refs: ["github"],+ disabled_skills: ["deploy-checklist"],+ };+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "default",+ profile: storedProfile,+ } as never);+ emitControl = {+ agentType: "openhands",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ enable_sub_agents: true,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = userEvent.setup();+ await user.click(screen.getByTestId("edit-agent-profile"));+ await screen.findByTestId("mock-agent-settings");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ // Profiles are secret-free now (no embedded skills), so exposeSecrets is a+ // server-side no-op; canvas still passes "encrypted" for signature parity.+ expect(AgentProfilesService.getProfile).toHaveBeenCalledWith(+ "default",+ "encrypted",+ );+ const { profile } = saveMutate.mock.calls[0][0];+ expect(profile).toMatchObject({+ agent_kind: "openhands",+ enable_sub_agents: true,+ llm_profile_ref: "default",+ system_message_suffix: "Be terse.",+ condenser: { kind: "NoOpCondenserSettings" },+ verification: { critic_enabled: true },+ enable_switch_llm_tool: false,+ tool_concurrency_limit: 4,+ mcp_server_refs: ["github"],+ disabled_skills: ["deploy-checklist"],+ });+ expect(profile).not.toHaveProperty("id");+ expect(profile).not.toHaveProperty("name");+ expect(profile).not.toHaveProperty("revision");+ });++ it("kind-switch edit-save sends a clean variant payload", async () => {+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "default",+ profile: {+ schema_version: 1,+ id: "p-1",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "default",+ condenser: { kind: "NoOpCondenserSettings" },+ mcp_server_refs: ["github"],+ },+ } as never);+ emitControl = {+ agentType: "acp",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_command: null,+ acp_args: null,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = userEvent.setup();+ await user.click(screen.getByTestId("edit-agent-profile"));+ await screen.findByTestId("mock-agent-settings");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ // No stored openhands fields may leak into the acp payload — the server's+ // extra="forbid" union would 422 on a mongrel profile.+ expect(saveMutate).toHaveBeenCalledWith({+ name: "default",+ profile: {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_command: null,+ acp_args: null,+ },+ });+ });++ it("falls back to the default LLM profile when the stored llm_profile_ref is dangling (#1571 review)", async () => {+ // The stored profile references an LLM profile that's since been deleted;+ // the editor must validate against the live list and self-heal to the+ // active default rather than saving the stale ref straight back.+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "default",+ profile: {+ schema_version: 1,+ id: "p-1",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "deleted-profile",+ enable_sub_agents: false,+ },+ } as never);+ emitControl = {+ agentType: "openhands",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ enable_sub_agents: false,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = userEvent.setup();+ await user.click(screen.getByTestId("edit-agent-profile"));+ await screen.findByTestId("mock-agent-settings");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ const { profile } = saveMutate.mock.calls[0][0];+ expect(profile.llm_profile_ref).toBe("default");+ });++ it("keeps a live llm_profile_ref untouched on load", async () => {+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({+ name: "custom",+ profile: {+ schema_version: 1,+ id: "p-2",+ name: "custom",+ revision: 1,+ agent_kind: "openhands",+ llm_profile_ref: "default",+ enable_sub_agents: false,+ },+ } as never);+ emitControl = {+ agentType: "openhands",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ enable_sub_agents: false,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = userEvent.setup();+ await user.click(screen.getByTestId("edit-agent-profile"));+ await screen.findByTestId("mock-agent-settings");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));+ const { profile } = saveMutate.mock.calls[0][0];+ expect(profile.llm_profile_ref).toBe("default");+ });++ it("blocks an OpenHands save when no LLM profile is available", async () => {+ llmProfilesData = { profiles: [], active_profile: null };+ emitControl = {+ agentType: "openhands",+ isValid: true,+ buildAgentProfileFields: () => ({+ agent_kind: "openhands",+ enable_sub_agents: false,+ }),+ credentials: { isDirty: false, save: vi.fn(), reset: vi.fn() },+ };++ render(<AgentProfilesLocalView />);+ const user = await openCreateAndName("my-oh");+ await user.click(screen.getByTestId("save-agent-profile-btn"));++ await waitFor(() =>+ expect(displayErrorToast).toHaveBeenCalledWith(+ "SETTINGS$AGENT_PROFILE_LLM_REQUIRED",+ ),+ );+ expect(saveMutate).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsxnew file mode 100644index 0000000000..dff99126c6--- /dev/null+++ b/__tests__/components/settings/agent-profiles/agent-profiles-manager.test.tsx@@ -0,0 +1,244 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AgentProfilesManager } from "#/components/features/settings/agent-profiles/agent-profiles-manager";+import AgentProfilesService, {+ type AgentProfileSummary,+} from "#/api/agent-profiles-service/agent-profiles-service.api";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, params?: Record<string, string>) => {+ const translations: Record<string, string> = {+ SETTINGS$AVAILABLE_PROFILES: "Available Profiles",+ SETTINGS$ADD_AGENT_PROFILE: "Add agent profile",+ SETTINGS$PROFILES_LOAD_ERROR: "Failed to load profiles",+ SETTINGS$PROFILES_EMPTY: "No profiles saved yet",+ SETTINGS$PROFILE_ACTIVE: "Active",+ SETTINGS$PROFILE_MENU: "Profile menu",+ SETTINGS$PROFILE_EDIT: "Edit",+ SETTINGS$PROFILE_SET_ACTIVE: "Set as active",+ SETTINGS$PROFILE_DELETE_TITLE: "Delete Profile",+ SETTINGS$AGENT_TYPE_ACP: "ACP",+ SETTINGS$PROFILE_DELETE_CONFIRMATION: params?.name+ ? `Are you sure you want to delete "${params.name}"?`+ : "Are you sure you want to delete this profile?",+ SETTINGS$PROFILE_ACTIVATED: params?.name+ ? `Profile "${params.name}" activated`+ : "Profile activated",+ BUTTON$DELETE: "Delete",+ BUTTON$CANCEL: "Cancel",+ ERROR$GENERIC: "An error occurred",+ };+ return translations[key] || key;+ },+ }),+}));++vi.mock("#/api/agent-profiles-service/agent-profiles-service.api");+vi.mock("#/utils/custom-toast-handlers");+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => ({+ backend: { id: "b1", kind: "local" },+ orgId: null,+ }),+}));++// Gating hook: `true` by default (local / owner-admin); flipped per test to+// exercise the cloud view-only member path.+const canManage = vi.hoisted(() => ({ value: true }));+vi.mock("#/hooks/use-can-manage-org-profiles", () => ({+ useCanManageOrgProfiles: () => canManage.value,+}));++const mockProfiles: AgentProfileSummary[] = [+ {+ id: "id-oh",+ name: "my-openhands",+ agent_kind: "openhands",+ revision: 0,+ llm_profile_ref: "default",+ mcp_server_refs: null,+ },+ {+ id: "id-acp",+ name: "my-claude",+ agent_kind: "acp",+ revision: 0,+ llm_profile_ref: null,+ mcp_server_refs: null,+ },+];++describe("AgentProfilesManager", () => {+ let queryClient: QueryClient;++ const renderManager = (+ props: {+ onAddProfile?: () => void;+ onEditProfile?: (profile: AgentProfileSummary) => void;+ } = {},+ ) =>+ render(+ <QueryClientProvider client={queryClient}>+ <AgentProfilesManager {...props} />+ </QueryClientProvider>,+ );++ beforeEach(() => {+ canManage.value = true;+ queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ });++ afterEach(() => {+ queryClient.clear();+ vi.clearAllMocks();+ });++ it("displays the section title and profiles", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });++ renderManager();++ expect(screen.getByText("Available Profiles")).toBeInTheDocument();+ await screen.findByText("my-openhands");+ expect(screen.getByText("my-claude")).toBeInTheDocument();+ // OpenHands profiles show their referenced LLM profile; ACP shows the kind.+ expect(screen.getByText("default")).toBeInTheDocument();+ expect(screen.getByText("ACP")).toBeInTheDocument();+ });++ it("marks the active profile", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });++ renderManager();++ const badge = await screen.findByTestId("agent-profile-active-badge");+ expect(badge).toHaveTextContent("Active");+ });++ it("shows the Add button and fires onAddProfile", async () => {+ const onAddProfile = vi.fn();+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_agent_profile_id: null,+ });++ renderManager({ onAddProfile });++ const user = userEvent.setup();+ await user.click(screen.getByTestId("add-agent-profile"));+ expect(onAddProfile).toHaveBeenCalledTimes(1);+ });++ it("hides mutate controls for view-only members (canManage false)", async () => {+ canManage.value = false;+ const onAddProfile = vi.fn();+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });++ renderManager({ onAddProfile });++ // The list still renders, but there is no Add button and no row actions.+ await screen.findByText("my-openhands");+ expect(screen.queryByTestId("add-agent-profile")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("agent-profile-menu-trigger"),+ ).not.toBeInTheDocument();+ });++ it("shows the empty state when there are no profiles", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_agent_profile_id: null,+ });++ renderManager();++ await screen.findByText("No profiles saved yet");+ });++ it("shows an error message when loading fails", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockRejectedValue(+ new Error("Network error"),+ );++ renderManager();++ await screen.findByText("Failed to load profiles");+ });++ it("calls onEditProfile from the row menu", async () => {+ const onEditProfile = vi.fn();+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });++ renderManager({ onEditProfile });++ await screen.findByText("my-openhands");+ const user = userEvent.setup();+ const triggers = screen.getAllByTestId("agent-profile-menu-trigger");+ await user.click(triggers[0]);+ await user.click(screen.getByText("Edit"));++ expect(onEditProfile).toHaveBeenCalledWith(mockProfiles[0]);+ });++ it("activates a profile by id from the row menu", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });+ vi.mocked(AgentProfilesService.activateProfile).mockResolvedValue({+ id: "id-acp",+ message: "ok",+ agent_settings_applied: false,+ });++ renderManager();++ await screen.findByText("my-claude");+ const user = userEvent.setup();+ // Second row (my-claude) is not active, so Set active is enabled.+ const triggers = screen.getAllByTestId("agent-profile-menu-trigger");+ await user.click(triggers[1]);+ await user.click(screen.getByText("Set as active"));++ expect(AgentProfilesService.activateProfile).toHaveBeenCalledWith("id-acp");+ });++ it("opens the delete modal from the row menu", async () => {+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({+ profiles: mockProfiles,+ active_agent_profile_id: "id-oh",+ });++ renderManager();++ await screen.findByText("my-claude");+ const user = userEvent.setup();+ const triggers = screen.getAllByTestId("agent-profile-menu-trigger");+ await user.click(triggers[1]);+ await user.click(screen.getByText("Delete"));++ expect(+ screen.getByText('Are you sure you want to delete "my-claude"?'),+ ).toBeInTheDocument();+ });+});diff --git a/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts b/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.tsnew file mode 100644index 0000000000..418744bce3--- /dev/null+++ b/__tests__/components/settings/agent-profiles/merge-agent-profile-save-input.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from "vitest";+import type {+ AgentProfile,+ AgentProfileSaveInput,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import { mergeAgentProfileSaveInput } from "#/components/features/settings/agent-profiles/merge-agent-profile-save-input";++// Mirrors the seeded `default` profile: fields the minimal editor does NOT+// model (condenser, verification, suffix, mcp_server_refs, the disabled_skills+// deny-list) carry non-default values so a wipe-to-defaults would be visible.+// `disabled_skills` rides untyped (the pinned ts-client predates it) — the+// merge must still round-trip it, so the fixture includes it via the cast.+const storedOpenHands = {+ schema_version: 1,+ id: "11111111-1111-1111-1111-111111111111",+ name: "default",+ revision: 3,+ agent_kind: "openhands",+ llm_profile_ref: "old-llm",+ agent: "CodeActAgent",+ system_message_suffix: "Be terse.",+ condenser: { kind: "NoOpCondenserSettings" },+ verification: {+ critic_enabled: true,+ critic_mode: "finish_and_message",+ enable_iterative_refinement: true,+ critic_threshold: 0.8,+ max_refinement_iterations: 5,+ critic_server_url: null,+ critic_model_name: null,+ },+ enable_sub_agents: false,+ enable_switch_llm_tool: false,+ tool_concurrency_limit: 4,+ mcp_server_refs: ["github"],+ disabled_skills: ["deploy-checklist"],+} as unknown as AgentProfile;++const storedAcp = {+ schema_version: 1,+ id: "22222222-2222-2222-2222-222222222222",+ name: "claude",+ revision: 1,+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_session_mode: "bypassPermissions",+ acp_prompt_timeout: 900,+ acp_command: null,+ acp_args: null,+ mcp_server_refs: ["linear"],+} as unknown as AgentProfile;++describe("mergeAgentProfileSaveInput", () => {+ it("preserves unmodeled OpenHands fields under the edited ones", () => {+ const edited: AgentProfileSaveInput = {+ agent_kind: "openhands",+ enable_sub_agents: true,+ llm_profile_ref: "new-llm",+ };++ const merged = mergeAgentProfileSaveInput(storedOpenHands, edited);++ // Edited fields win.+ expect(merged).toMatchObject({+ agent_kind: "openhands",+ enable_sub_agents: true,+ llm_profile_ref: "new-llm",+ });+ // Fields the editor doesn't model survive the whole-profile overwrite.+ expect(merged).toMatchObject({+ condenser: { kind: "NoOpCondenserSettings" },+ verification: { critic_enabled: true, critic_threshold: 0.8 },+ system_message_suffix: "Be terse.",+ mcp_server_refs: ["github"],+ disabled_skills: ["deploy-checklist"],+ enable_switch_llm_tool: false,+ tool_concurrency_limit: 4,+ });+ });++ it("preserves unmodeled ACP fields under the edited ones", () => {+ const edited: AgentProfileSaveInput = {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-sonnet-5",+ acp_command: null,+ acp_args: null,+ };++ const merged = mergeAgentProfileSaveInput(storedAcp, edited);++ expect(merged).toMatchObject({+ agent_kind: "acp",+ acp_model: "claude-sonnet-5",+ acp_session_mode: "bypassPermissions",+ acp_prompt_timeout: 900,+ mcp_server_refs: ["linear"],+ });+ });++ it("strips server-managed identity from the merge", () => {+ const merged = mergeAgentProfileSaveInput(storedOpenHands, {+ agent_kind: "openhands",+ enable_sub_agents: true,+ llm_profile_ref: "new-llm",+ });++ // The path name is authoritative and the server preserves the namesake's+ // id / bumps revision itself; posting stale identity would only mislead.+ expect(merged).not.toHaveProperty("id");+ expect(merged).not.toHaveProperty("name");+ expect(merged).not.toHaveProperty("revision");+ });++ it("sends a clean variant payload on an agent_kind switch", () => {+ const edited: AgentProfileSaveInput = {+ agent_kind: "acp",+ acp_server: "codex",+ acp_model: null,+ acp_command: null,+ acp_args: null,+ };++ // openhands → acp: carrying stored openhands fields over would produce a+ // mongrel payload the server's extra="forbid" union rejects.+ expect(mergeAgentProfileSaveInput(storedOpenHands, edited)).toEqual(edited);+ });++ it("passes the edited fields through on create (no stored profile)", () => {+ const edited: AgentProfileSaveInput = {+ agent_kind: "openhands",+ enable_sub_agents: false,+ llm_profile_ref: "default",+ };++ expect(mergeAgentProfileSaveInput(null, edited)).toEqual(edited);+ });+});diff --git a/__tests__/components/settings/llm-profiles/profile-actions-menu.test.tsx b/__tests__/components/settings/llm-profiles/profile-actions-menu.test.tsxindex 201b64a842..04fb200c66 100644--- a/__tests__/components/settings/llm-profiles/profile-actions-menu.test.tsx+++ b/__tests__/components/settings/llm-profiles/profile-actions-menu.test.tsx@@ -11,6 +11,7 @@ vi.mock("react-i18next", () => ({"BUTTON$RENAME": "Rename","BUTTON$DUPLICATE": "Duplicate","SETTINGS$PROFILE_SET_ACTIVE": "Set as active",+ "SETTINGS$PROFILE_SET_DEFAULT": "Set as default","BUTTON$DELETE": "Delete",};return translations[key] || key;@@ -38,7 +39,7 @@ describe("ProfileActionsMenu", () => {expect(screen.getByTestId("profile-duplicate")).toHaveTextContent("Duplicate",);- expect(screen.getByTestId("profile-set-active")).toHaveTextContent("Set as active");+ expect(screen.getByTestId("profile-set-active")).toHaveTextContent("Set as default");expect(screen.getByTestId("profile-delete")).toHaveTextContent("Delete");});diff --git a/__tests__/components/settings/llm-profiles/profile-row.test.tsx b/__tests__/components/settings/llm-profiles/profile-row.test.tsxindex f8d68292fc..0e503c3036 100644--- a/__tests__/components/settings/llm-profiles/profile-row.test.tsx+++ b/__tests__/components/settings/llm-profiles/profile-row.test.tsx@@ -8,11 +8,11 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({t: (key: string) => {const translations: Record<string, string> = {- SETTINGS$PROFILE_ACTIVE: "Active",+ SETTINGS$PROFILE_DEFAULT: "Default",SETTINGS$PROFILE_MENU: "Profile menu",SETTINGS$PROFILE_EDIT: "Edit",BUTTON$RENAME: "Rename",- SETTINGS$PROFILE_SET_ACTIVE: "Set as active",+ SETTINGS$PROFILE_SET_DEFAULT: "Set as default",BUTTON$DELETE: "Delete",};return translations[key] || key;@@ -67,7 +67,7 @@ describe("ProfileRow", () => {render(<ProfileRow {...defaultProps} isActive />);expect(screen.getByTestId("profile-active-badge")).toBeInTheDocument();- expect(screen.getByText("Active")).toBeInTheDocument();+ expect(screen.getByText("Default")).toBeInTheDocument();});it("does not show Active badge when isActive is false", () => {@@ -98,7 +98,7 @@ describe("ProfileRow", () => {expect(screen.getByText("Edit")).toBeInTheDocument();expect(screen.getByText("Rename")).toBeInTheDocument();- expect(screen.getByText("Set as active")).toBeInTheDocument();+ expect(screen.getByText("Set as default")).toBeInTheDocument();expect(screen.getByText("Delete")).toBeInTheDocument();});@@ -148,7 +148,7 @@ describe("ProfileRow", () => {render(<ProfileRow {...defaultProps} onActivate={handleActivate} />);await user.click(screen.getByTestId("profile-menu-trigger"));- await user.click(screen.getByText("Set as active"));+ await user.click(screen.getByText("Set as default"));expect(handleActivate).toHaveBeenCalledWith(mockProfile.name);});diff --git a/__tests__/hooks/mutation/use-create-conversation.test.tsx b/__tests__/hooks/mutation/use-create-conversation.test.tsxindex f57d5b175e..47db81bb56 100644--- a/__tests__/hooks/mutation/use-create-conversation.test.tsx+++ b/__tests__/hooks/mutation/use-create-conversation.test.tsx@@ -15,19 +15,90 @@ vi.mock("#/hooks/use-tracking", () => ({}),}));+// The default→agent_settings downgrade is local-only (#1571 review); default+// to local so the existing (pre-review) assertions below are unaffected, and+// override per-test to exercise the cloud path.+interface MockActiveBackend {+ backend: { id: string; kind: "local" | "cloud" };+ orgId: string | null;+}+const mockUseActiveBackend = vi.fn<() => MockActiveBackend>(() => ({+ backend: { id: "local-1", kind: "local" },+ orgId: null,+}));+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => mockUseActiveBackend(),+}));+// The hook stamps the active LLM profile onto the conversation (#1082).// Mock it so the captured value is deterministic — the real hook fires a// query the global MSW layer would answer non-deterministically under test// timing.const { useLlmProfilesMock } = vi.hoisted(() => ({- useLlmProfilesMock: vi.fn(() => ({ data: { active_profile: null } })),+ useLlmProfilesMock: vi.fn(() => ({+ data: { active_profile: null as string | null },+ })),}));vi.mock("#/hooks/query/use-llm-profiles", () => ({useLlmProfiles: () => useLlmProfilesMock(),}));+// The hook warms the agent-profiles cache; the launch path itself awaits the+// list via ensureQueryData (so it can't race a cold cache). Mock the hook to a+// no-op and drive launches through the service mock below.+vi.mock("#/hooks/query/use-agent-profiles", () => ({+ useAgentProfiles: () => ({ data: undefined }),+}));++// The launch path resolves the active AgentProfile by awaiting+// `AgentProfilesService.listProfiles` through the query cache (#3727).+// Default: no active profile, so a plain create stays on the legacy path.+const { listAgentProfilesMock } = vi.hoisted(() => ({+ listAgentProfilesMock: vi.fn(),+}));+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({+ __esModule: true,+ default: { listProfiles: listAgentProfilesMock },+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",+}));+listAgentProfilesMock.mockResolvedValue({+ profiles: [],+ active_agent_profile_id: null,+});++// LLM-profile service: real listProfiles calls (the llmProfileExists+// validation — see use-create-conversation.ts) so it can be asserted per-test.+const listLlmProfilesMock = vi.fn();+vi.mock("#/api/profiles-service/profiles-service.api", () => ({+ __esModule: true,+ default: {+ listProfiles: (...args: unknown[]) => listLlmProfilesMock(...args),+ },+}));+listLlmProfilesMock.mockResolvedValue({ profiles: [], active_profile: null });+describe("useCreateConversation", () => {- afterEach(() => removeStoredConversationMetadata("conv-with-plugins"));+ afterEach(() => {+ // Restore the default (no active AgentProfile) so the overrides below+ // don't leak into the other create-call assertions.+ mockUseActiveBackend.mockReturnValue({+ backend: { id: "local-1", kind: "local" as const },+ orgId: null,+ });+ listAgentProfilesMock.mockReset();+ listAgentProfilesMock.mockResolvedValue({+ profiles: [],+ active_agent_profile_id: null,+ });+ listLlmProfilesMock.mockReset();+ listLlmProfilesMock.mockResolvedValue({+ profiles: [],+ active_profile: null,+ });+ useLlmProfilesMock.mockReturnValue({ data: { active_profile: null } });+ removeStoredConversationMetadata("conv-with-plugins");+ removeStoredConversationMetadata("conv-ref-stamp");+ });it("passes suggested tasks to the V1 create conversation API", async () => {const createConversationSpy = vi@@ -105,6 +176,101 @@ describe("useCreateConversation", () => {});});+ it("launches new local conversations from the active AgentProfile (#3727)", async () => {+ listAgentProfilesMock.mockResolvedValue({+ profiles: [],+ active_agent_profile_id: "profile-abc",+ });+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ await result.current.mutateAsync({ query: "hello" });++ await waitFor(() => {+ // sandboxId (#9) is undefined; the active profile id rides as #10.+ const call = createConversationSpy.mock.lastCall;+ expect(call?.[8]).toBeUndefined();+ expect(call?.[9]).toBe("profile-abc");+ });+ });++ it("awaits the profiles fetch so an early send still launches from the active profile", async () => {+ // A send fired before the home profiles query resolves must block on the+ // fetch, not fall through to the agent_settings path (#1571 review F2).+ let resolveList: (value: unknown) => void = () => {};+ listAgentProfilesMock.mockReturnValue(+ new Promise((resolve) => {+ resolveList = resolve;+ }),+ );+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);+ // Spies persist across tests in this file; drop earlier calls so the+ // not-yet-called assertion below sees only this launch.+ createConversationSpy.mockClear();++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ const pending = result.current.mutateAsync({ query: "hello" });+ expect(createConversationSpy).not.toHaveBeenCalled();++ resolveList({ profiles: [], active_agent_profile_id: "profile-late" });+ await pending;++ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBe("profile-late");+ });++ it("falls back to the agent_settings launch when the profiles fetch fails", async () => {+ listAgentProfilesMock.mockRejectedValue(new Error("not supported"));+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ // Resolves without stalling: the launch-path fetch is retry: false.+ await result.current.mutateAsync({ query: "hello" });++ // No profile tail — the create stays on the legacy agent_settings path.+ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBeUndefined();+ });+it("invalidates the conversation list and start-tasks queries on success", async () => {vi.spyOn(AgentServerConversationService,@@ -211,4 +377,189 @@ describe("useCreateConversation", () => {).toEqual([{ source: "github:o/a", ref: null, repo_path: "plugins/a" }]),);});++ it("launches the seeded `default` profile via agent_settings so canvas enrichments survive", async () => {+ // The active profile IS the well-known default → it's the enriched baseline+ // (mirrors agent_settings), not a deliberate profile pick, so the launch+ // stays on the agent_settings path (no profile tail) even though its+ // llm_profile_ref resolves. Keeps <RUNTIME_SERVICES>/canvas_ui/project+ // skills, which the profile-resolution path drops.+ listAgentProfilesMock.mockResolvedValue({+ profiles: [+ {+ id: "profile-default",+ name: "default",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "gpt",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "profile-default",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "gpt" }],+ active_profile: "gpt",+ });+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ await result.current.mutateAsync({ query: "hello" });++ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBeUndefined();+ });++ it("keeps the profile path for an ACP `default` profile (agent_settings can't carry ACP config)", async () => {+ // The default→agent_settings shortcut is OpenHands-only: activation is+ // pointer-only, so global agent_settings is stale (still OpenHands) for an+ // active ACP profile — routing it via agent_settings would launch the wrong+ // agent. An ACP `default` must resolve server-side via agent_profile_id.+ listAgentProfilesMock.mockResolvedValue({+ profiles: [+ {+ id: "profile-acp-default",+ name: "default",+ agent_kind: "acp",+ revision: 1,+ llm_profile_ref: null,+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "profile-acp-default",+ });+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ await result.current.mutateAsync({ query: "hello" });++ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBe("profile-acp-default");+ });++ it("launches the seeded `default` profile from its resolved id on cloud (no agent_settings fallback exists there) (#1571)", async () => {+ // The local-only downgrade exists to preserve canvas-only enrichments that+ // only ride the agent_settings path; cloud has no such payload, so the+ // seeded `default` must always launch via agent_profile_id there — a+ // downgrade there would send agent_profile_id: null and the conversation+ // would never get `launched_agent_profile` stamped.+ mockUseActiveBackend.mockReturnValue({+ backend: { id: "cloud-1", kind: "cloud" },+ orgId: null,+ });+ listAgentProfilesMock.mockResolvedValue({+ profiles: [+ {+ id: "profile-default",+ name: "default",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "gpt",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "profile-default",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "gpt" }],+ active_profile: "gpt",+ });+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-1",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ await result.current.mutateAsync({ query: "hello" });++ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBe("profile-default");+ });++ it("stamps the launched openhands profile's llm_profile_ref into conversation metadata (#1082)", async () => {+ // A named (non-default) profile launches via the profile path and runs its+ // own llm_profile_ref — which differs from the standalone active LLM+ // profile — so the switcher pill must name the ref, not the active profile.+ useLlmProfilesMock.mockReturnValue({+ data: { active_profile: "standalone-active" },+ });+ listAgentProfilesMock.mockResolvedValue({+ profiles: [+ {+ id: "profile-custom",+ name: "My Profile",+ agent_kind: "openhands",+ revision: 2,+ llm_profile_ref: "claude",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "profile-custom",+ });+ listLlmProfilesMock.mockResolvedValue({+ profiles: [{ name: "claude" }],+ active_profile: "standalone-active",+ });+ const createConversationSpy = vi+ .spyOn(AgentServerConversationService, "createConversation")+ .mockResolvedValue({+ id: "task-id",+ app_conversation_id: "conv-ref-stamp",+ agent_server_url: "http://agent-server.local",+ } as never);++ const { result } = renderHook(() => useCreateConversation(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ ),+ });++ await result.current.mutateAsync({ query: "hello" });++ const call = createConversationSpy.mock.lastCall;+ expect(call?.[9]).toBe("profile-custom");+ await waitFor(() =>+ expect(+ getStoredConversationMetadata("conv-ref-stamp")?.active_profile,+ ).toBe("claude"),+ );+ });});diff --git a/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.tsx b/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.tsxindex 5bb2ef713c..b89e56b0ad 100644--- a/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.tsx+++ b/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.tsx@@ -1,98 +1,39 @@import { renderHook } from "@testing-library/react";import { describe, expect, it, vi, beforeEach } from "vitest";-// The wrapper drives the base mutation; mock it so we can deterministically-// trigger the success / error callbacks the wrapper passes in.+// The wrapper is a thin positional adapter over the base mutation; the inline+// message, metadata persist, and error reporting all live in the mutation+// itself (see use-switch-llm-profile.test.tsx) so they survive the switcher+// menu unmounting on select.const switchMutateMock = vi.fn();vi.mock("#/hooks/mutation/use-switch-llm-profile", () => ({useSwitchLlmProfile: () => ({ mutate: switchMutateMock, isPending: false }),}));-vi.mock("#/hooks/chat/record-model-switch-message", () => ({- recordModelSwitchMessage: vi.fn(),-}));--vi.mock("#/hooks/chat/model-command-event-anchor", () => ({- getLastRenderableEventId: () => null,-}));--vi.mock("#/utils/custom-toast-handlers", () => ({- displayErrorToast: vi.fn(),-}));-import { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";-import {- getStoredConversationMetadata,- setStoredConversationMetadata,-} from "#/api/conversation-metadata-store";describe("useSwitchLlmProfileAndLog", () => {beforeEach(() => {vi.clearAllMocks();- window.localStorage.clear();});- it("stamps the switched-to profile onto the conversation metadata, preserving repo/workspace (#1082)", () => {- switchMutateMock.mockImplementation((_vars, opts) => opts?.onSuccess?.());- // Repo metadata persisted at creation must survive the merge.- setStoredConversationMetadata("conv-1", {- selected_repository: "octocat/hello-world",- selected_branch: "main",- git_provider: "github",- });-+ it("maps positional args to the base mutation for the per-conversation path", () => {const { result } = renderHook(() => useSwitchLlmProfileAndLog());result.current.switchAndLog("conv-1", "claude-sonnet-4.6");- expect(getStoredConversationMetadata("conv-1")).toEqual({- selected_repository: "octocat/hello-world",- selected_branch: "main",- git_provider: "github",- selected_workspace: null,- active_profile: "claude-sonnet-4.6",- plugins: null,+ expect(switchMutateMock).toHaveBeenCalledWith({+ conversationId: "conv-1",+ profileName: "claude-sonnet-4.6",});});- it("preserves the conversation's attached plugins across a profile switch", () => {- switchMutateMock.mockImplementation((_vars, opts) => opts?.onSuccess?.());- // A plugin snapshot persisted at creation must survive the full-object- // metadata replace the switch performs.- setStoredConversationMetadata("conv-1", {- selected_repository: null,- selected_branch: null,- git_provider: null,- plugins: [- { source: "github:acme/city-weather", ref: null, repo_path: null },- ],- });-- const { result } = renderHook(() => useSwitchLlmProfileAndLog());- result.current.switchAndLog("conv-1", "claude-sonnet-4.6");-- expect(getStoredConversationMetadata("conv-1")?.plugins).toEqual([- { source: "github:acme/city-weather", ref: null, repo_path: null },- ]);- });-- it("does not stamp metadata for the home-page activate path (conversationId === null)", () => {- switchMutateMock.mockImplementation((_vars, opts) => opts?.onSuccess?.());-+ it("passes a null conversationId through for the home-page activate path", () => {const { result } = renderHook(() => useSwitchLlmProfileAndLog());result.current.switchAndLog(null, "claude-sonnet-4.6");- // No conversation to scope the stamp to → nothing written.- expect(getStoredConversationMetadata("conv-1")).toBeNull();- });-- it("does not stamp metadata when the switch fails", () => {- switchMutateMock.mockImplementation((_vars, opts) =>- opts?.onError?.(new Error("boom")),- );-- const { result } = renderHook(() => useSwitchLlmProfileAndLog());- result.current.switchAndLog("conv-1", "claude-sonnet-4.6");-- expect(getStoredConversationMetadata("conv-1")).toBeNull();+ expect(switchMutateMock).toHaveBeenCalledWith({+ conversationId: null,+ profileName: "claude-sonnet-4.6",+ });});});diff --git a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsxindex 41ce813f9b..fd47773fdb 100644--- a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx+++ b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx@@ -1,5 +1,6 @@import { renderHook, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AxiosError, AxiosHeaders } from "axios";import { describe, expect, it, vi, beforeEach } from "vitest";import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";@@ -8,6 +9,14 @@ import {LLM_PROFILES_QUERY_KEYS,SETTINGS_QUERY_KEYS,} from "#/hooks/query/query-keys";+import { recordModelSwitchMessage } from "#/hooks/chat/record-model-switch-message";+import {+ getStoredConversationMetadata,+ setStoredConversationMetadata,+} from "#/api/conversation-metadata-store";+import { displayErrorToast } from "#/utils/custom-toast-handlers";++vi.mock("#/utils/custom-toast-handlers");vi.mock("#/api/conversation-service/agent-server-conversation-service.api",@@ -18,6 +27,14 @@ vi.mock(}),);+vi.mock("#/hooks/chat/record-model-switch-message", () => ({+ recordModelSwitchMessage: vi.fn(),+}));++vi.mock("#/hooks/chat/model-command-event-anchor", () => ({+ getLastRenderableEventId: () => "evt-9",+}));+const renderSwitchHook = () => {const queryClient = new QueryClient({defaultOptions: {@@ -37,6 +54,7 @@ const renderSwitchHook = () => {describe("useSwitchLlmProfile", () => {beforeEach(() => {vi.clearAllMocks();+ window.localStorage.clear();SettingsService.invalidateCache();});@@ -120,4 +138,147 @@ describe("useSwitchLlmProfile", () => {invalidateCacheSpy.mockRestore();});++ // Errors surface via a tailored onError (not the global mutation toast) so a+ // failed switch keeps the specific "Switched to {name} failed" message+ // (#1571 review).+ it("shows the tailored switch-failed message when the error carries no server detail", async () => {+ // An empty-message Error extracts to "" (see retrieveAxiosErrorMessage),+ // so the tailored fallback is what actually renders.+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(+ new Error(),+ );++ const { result } = renderSwitchHook();+ result.current.mutate({ conversationId: null, profileName: "Smart" });++ await waitFor(() => expect(result.current.isError).toBe(true));+ // The global i18n mock returns the raw key (see vitest.setup.ts).+ expect(displayErrorToast).toHaveBeenCalledWith("MODEL$SWITCH_FAILED");+ });++ it("prefers the server-provided error detail over the tailored fallback", async () => {+ const axiosError = new AxiosError(+ "Request failed",+ "500",+ undefined,+ undefined,+ {+ status: 404,+ statusText: "Not Found",+ headers: new AxiosHeaders(),+ config: { headers: new AxiosHeaders() },+ data: { message: "LLM profile 'gpt-5' not found" },+ },+ );+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(+ axiosError,+ );++ const { result } = renderSwitchHook();+ result.current.mutate({ conversationId: null, profileName: "Smart" });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(displayErrorToast).toHaveBeenCalledWith(+ "LLM profile 'gpt-5' not found",+ );+ });++ // The following behaviors run in the mutation-level onSuccess (not+ // mutate-scoped callbacks) so they survive the switcher menu unmounting on+ // select (#1571).+ it("records the inline switch message anchored to the last renderable event", async () => {+ vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(+ undefined as never,+ );++ const { result } = renderSwitchHook();+ result.current.mutate({ conversationId: "conv-1", profileName: "Smart" });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(recordModelSwitchMessage).toHaveBeenCalledWith(+ "conv-1",+ "Smart",+ "evt-9",+ );+ });++ it("stamps the switched-to profile onto the conversation metadata, preserving repo/workspace (#1082)", async () => {+ vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(+ undefined as never,+ );+ // Repo metadata persisted at creation must survive the merge.+ setStoredConversationMetadata("conv-1", {+ selected_repository: "octocat/hello-world",+ selected_branch: "main",+ git_provider: "github",+ });++ const { result } = renderSwitchHook();+ result.current.mutate({+ conversationId: "conv-1",+ profileName: "claude-sonnet-4.6",+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(getStoredConversationMetadata("conv-1")).toEqual({+ selected_repository: "octocat/hello-world",+ selected_branch: "main",+ git_provider: "github",+ selected_workspace: null,+ active_profile: "claude-sonnet-4.6",+ plugins: null,+ });+ });++ it("preserves the conversation's attached plugins across a profile switch", async () => {+ vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(+ undefined as never,+ );+ setStoredConversationMetadata("conv-1", {+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ plugins: [+ { source: "github:acme/city-weather", ref: null, repo_path: null },+ ],+ });++ const { result } = renderSwitchHook();+ result.current.mutate({+ conversationId: "conv-1",+ profileName: "claude-sonnet-4.6",+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(getStoredConversationMetadata("conv-1")?.plugins).toEqual([+ { source: "github:acme/city-weather", ref: null, repo_path: null },+ ]);+ });++ it("does not stamp metadata for the home-page activate path (conversationId === null)", async () => {+ vi.mocked(AgentServerConversationService.switchProfile).mockResolvedValue(+ undefined as never,+ );++ const { result } = renderSwitchHook();+ result.current.mutate({ conversationId: null, profileName: "Smart" });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(getStoredConversationMetadata("conv-1")).toBeNull();+ expect(recordModelSwitchMessage).not.toHaveBeenCalled();+ });++ it("does not stamp metadata when the switch fails", async () => {+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(+ new Error("boom"),+ );++ const { result } = renderSwitchHook();+ result.current.mutate({ conversationId: "conv-1", profileName: "Smart" });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(getStoredConversationMetadata("conv-1")).toBeNull();+ expect(recordModelSwitchMessage).not.toHaveBeenCalled();+ });});diff --git a/__tests__/hooks/use-can-manage-llm-profiles.test.tsx b/__tests__/hooks/use-can-manage-org-profiles.test.tsxsimilarity index 88%rename from __tests__/hooks/use-can-manage-llm-profiles.test.tsxrename to __tests__/hooks/use-can-manage-org-profiles.test.tsxindex dbf48d4c92..b84894fb94 100644--- a/__tests__/hooks/use-can-manage-llm-profiles.test.tsx+++ b/__tests__/hooks/use-can-manage-org-profiles.test.tsx@@ -2,7 +2,7 @@ import React from "react";import { renderHook, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { beforeEach, describe, expect, it, vi } from "vitest";-import { useCanManageLlmProfiles } from "#/hooks/use-can-manage-llm-profiles";+import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";import * as orgService from "#/api/cloud/organization-service.api";import * as activeBackendContext from "#/contexts/active-backend-context";import type { Backend } from "#/api/backend-registry/types";@@ -41,14 +41,14 @@ function mockBackend(backend: Backend, orgId: string | null) {});}-describe("useCanManageLlmProfiles", () => {+describe("useCanManageOrgProfiles", () => {beforeEach(() => {vi.restoreAllMocks();});it("is always true on local backends (no /me call)", () => {mockBackend(localBackend, null);- const { result } = renderHook(() => useCanManageLlmProfiles(), { wrapper });+ const { result } = renderHook(() => useCanManageOrgProfiles(), { wrapper });expect(result.current).toBe(true);expect(orgService.getCloudOrganizationMe).not.toHaveBeenCalled();});@@ -62,7 +62,7 @@ describe("useCanManageLlmProfiles", () => {role: "member",permissions: ["view_org_settings", "edit_org_settings"],});- const { result } = renderHook(() => useCanManageLlmProfiles(), { wrapper });+ const { result } = renderHook(() => useCanManageOrgProfiles(), { wrapper });await waitFor(() => expect(result.current).toBe(true));});@@ -75,7 +75,7 @@ describe("useCanManageLlmProfiles", () => {role: "owner",permissions: ["view_org_settings"],});- const { result } = renderHook(() => useCanManageLlmProfiles(), { wrapper });+ const { result } = renderHook(() => useCanManageOrgProfiles(), { wrapper });await waitFor(() =>expect(orgService.getCloudOrganizationMe).toHaveBeenCalled(),);@@ -90,7 +90,7 @@ describe("useCanManageLlmProfiles", () => {role: "admin",permissions: null,});- const { result } = renderHook(() => useCanManageLlmProfiles(), { wrapper });+ const { result } = renderHook(() => useCanManageOrgProfiles(), { wrapper });await waitFor(() => expect(result.current).toBe(true));});@@ -102,7 +102,7 @@ describe("useCanManageLlmProfiles", () => {role: "member",permissions: null,});- const { result } = renderHook(() => useCanManageLlmProfiles(), { wrapper });+ const { result } = renderHook(() => useCanManageOrgProfiles(), { wrapper });await waitFor(() =>expect(orgService.getCloudOrganizationMe).toHaveBeenCalled(),);diff --git a/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsxnew file mode 100644index 0000000000..32b5b81685--- /dev/null+++ b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx@@ -0,0 +1,122 @@+import { renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";++const useOptionalConversationIdMock = vi.fn();+const useActiveConversationMock = vi.fn();+const useLlmProfilesMock = vi.fn();+const switchAndLog = vi.fn();++let modelStoreState: { activeProfileByConversation: Record<string, string> } = {+ activeProfileByConversation: {},+};++vi.mock("#/hooks/use-conversation-id", () => ({+ useOptionalConversationId: () => useOptionalConversationIdMock(),+}));+vi.mock("#/hooks/query/use-active-conversation", () => ({+ useActiveConversation: () => useActiveConversationMock(),+}));+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => useLlmProfilesMock(),+}));+vi.mock("#/hooks/mutation/use-switch-llm-profile-and-log", () => ({+ useSwitchLlmProfileAndLog: () => ({ switchAndLog, isPending: false }),+}));+vi.mock("#/stores/model-store", () => ({+ useModelStore: (selector: (s: typeof modelStoreState) => unknown) =>+ selector(modelStoreState),+}));++// eslint-disable-next-line import/first+import { useChatInputLlmProfileState } from "#/hooks/use-chat-input-llm-profile-state";++// The hook reads the switch's pending state via `useIsMutating`, which needs a+// QueryClient in context (the switch mutation itself is mocked out above).+const renderState = () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return renderHook(() => useChatInputLlmProfileState(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ ),+ });+};++const PROFILES = [+ { name: "Fast", model: "gpt-4o-mini", base_url: null, api_key_set: true },+ { name: "Smart", model: "claude-opus", base_url: null, api_key_set: true },+];++describe("useChatInputLlmProfileState", () => {+ beforeEach(() => {+ switchAndLog.mockReset();+ modelStoreState = { activeProfileByConversation: {} };+ useOptionalConversationIdMock.mockReturnValue({ conversationId: "c1" });+ useActiveConversationMock.mockReturnValue({ data: undefined });+ useLlmProfilesMock.mockReturnValue({+ data: { profiles: PROFILES, active_profile: "Fast" },+ isLoading: false,+ });+ });++ it("prefers the profile stamped on the conversation over a model match", () => {+ useActiveConversationMock.mockReturnValue({+ data: { active_profile: "Smart", llm_model: "gpt-4o-mini" },+ });+ const { result } = renderState();+ // model "gpt-4o-mini" would match "Fast", but the stamped profile wins.+ expect(result.current.currentProfileName).toBe("Smart");+ });++ it("falls back to the profile whose model matches the running llm_model", () => {+ useActiveConversationMock.mockReturnValue({+ data: { llm_model: "claude-opus" },+ });+ const { result } = renderState();+ expect(result.current.currentProfileName).toBe("Smart");+ });++ it("falls back to the account active_profile when there is no conversation model", () => {+ useActiveConversationMock.mockReturnValue({ data: { llm_model: null } });+ const { result } = renderState();+ expect(result.current.currentProfileName).toBe("Fast");+ });++ it("prefers the optimistic just-switched profile", () => {+ modelStoreState = { activeProfileByConversation: { c1: "Smart" } };+ useActiveConversationMock.mockReturnValue({+ data: { active_profile: "Fast", llm_model: "gpt-4o-mini" },+ });+ const { result } = renderState();+ expect(result.current.currentProfileName).toBe("Smart");+ });++ it("ignores a stamped profile that is no longer in the list", () => {+ useActiveConversationMock.mockReturnValue({+ data: { active_profile: "Deleted", llm_model: "claude-opus" },+ });+ const { result } = renderState();+ // Deleted is not in PROFILES → fall through to the model match.+ expect(result.current.currentProfileName).toBe("Smart");+ });++ it("live-switches a different profile against the conversation id", () => {+ useActiveConversationMock.mockReturnValue({+ data: { active_profile: "Fast", llm_model: "gpt-4o-mini" },+ });+ const { result } = renderState();+ result.current.selectProfile("Smart");+ expect(switchAndLog).toHaveBeenCalledWith("c1", "Smart");+ });++ it("does not switch when the current profile is re-selected", () => {+ useActiveConversationMock.mockReturnValue({+ data: { active_profile: "Fast", llm_model: "gpt-4o-mini" },+ });+ const { result } = renderState();+ result.current.selectProfile("Fast");+ expect(switchAndLog).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/hooks/use-chat-input-model-state.test.tsx b/__tests__/hooks/use-chat-input-model-state.test.tsxindex 1f7bfb40d9..7ac2a852d8 100644--- a/__tests__/hooks/use-chat-input-model-state.test.tsx+++ b/__tests__/hooks/use-chat-input-model-state.test.tsx@@ -115,7 +115,7 @@ describe("useChatInputModelState", () => {acpContext({isActiveAcpConversation: true,isAcpContext: true,- destinationPath: "/settings/agent",+ destinationPath: "/settings/agents",destinationLabel: "Agent",}),);@@ -133,7 +133,7 @@ describe("useChatInputModelState", () => {expect(result.current.showAcpPicker).toBe(true);// Live switch targets the navigation conversation id.expect(result.current.switchConversationId).toBe("c1");- expect(result.current.destinationPath).toBe("/settings/agent");+ expect(result.current.destinationPath).toBe("/settings/agents");});it("home ACP: resolves the configured acp_model and exposes the picker, but no live-switch target", () => {@@ -152,7 +152,7 @@ describe("useChatInputModelState", () => {acpContext({isHomeAcp: true,isAcpContext: true,- destinationPath: "/settings/agent",+ destinationPath: "/settings/agents",destinationLabel: "Agent",}),);diff --git a/__tests__/hooks/use-llm-configured.test.tsx b/__tests__/hooks/use-llm-configured.test.tsxnew file mode 100644index 0000000000..1489de7a7b--- /dev/null+++ b/__tests__/hooks/use-llm-configured.test.tsx@@ -0,0 +1,144 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { useLlmConfigured } from "#/hooks/use-llm-configured";++const useSettingsMock = vi.fn();+const useConfigMock = vi.fn();+const useLlmProfilesMock = vi.fn();+const useActiveBackendMock = vi.fn();+const useActiveAgentProfileMock = vi.fn();++vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => useSettingsMock(),+}));+vi.mock("#/hooks/query/use-config", () => ({+ useConfig: () => useConfigMock(),+}));+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => useLlmProfilesMock(),+}));+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => useActiveBackendMock(),+}));+vi.mock("#/hooks/use-active-agent-profile", () => ({+ useActiveAgentProfile: () => useActiveAgentProfileMock(),+}));++function wrapper({ children }: { children: ReactNode }) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}++describe("useLlmConfigured (local, agent-profile-driven)", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useConfigMock.mockReturnValue({ data: { feature_flags: {} } });+ useActiveBackendMock.mockReturnValue({+ backend: { kind: "local", id: "b1" },+ orgId: null,+ });+ useSettingsMock.mockReturnValue({+ data: {+ agent_settings: { agent_kind: "openhands" },+ llm_api_key_set: false,+ },+ });+ });++ const llmProfiles = (+ active: string,+ entries: { name: string; api_key_set: boolean }[],+ ) => ({+ data: {+ active_profile: active,+ profiles: entries.map((e) => ({+ name: e.name,+ model: "m",+ api_key_set: e.api_key_set,+ })),+ },+ });++ it("is configured when the LLM profile the AGENT profile references has a key", () => {+ useLlmProfilesMock.mockReturnValue(+ llmProfiles("default", [+ { name: "default", api_key_set: false },+ { name: "sonnet", api_key_set: true },+ ]),+ );+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: {+ agent_kind: "openhands",+ llm_profile_ref: "sonnet",+ name: "MyOH",+ },+ });++ const { result } = renderHook(() => useLlmConfigured(), { wrapper });+ expect(result.current.isConfigured).toBe(true);+ });++ it("is NOT configured when the referenced profile has no key, even if the active LLM profile has one", () => {+ // Discriminating case: the standalone active LLM profile ("default") HAS a+ // key, but the active agent profile references "sonnet", which does not.+ // Conversations launch from the agent profile, so the ref is what matters.+ useLlmProfilesMock.mockReturnValue(+ llmProfiles("default", [+ { name: "default", api_key_set: true },+ { name: "sonnet", api_key_set: false },+ ]),+ );+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: {+ agent_kind: "openhands",+ llm_profile_ref: "sonnet",+ name: "MyOH",+ },+ });++ const { result } = renderHook(() => useLlmConfigured(), { wrapper });+ expect(result.current.isConfigured).toBe(false);+ });++ it("falls back to the active LLM profile when the ref is stale (matches the launch fallback)", () => {+ // The agent profile references "ghost", which no longer exists in the list+ // (deleted profile / seed ref pointing at a named profile that was never+ // created). The launch path drops a stale-ref profile launch to an+ // agent_settings launch on the active LLM ("default", which HAS a key), so+ // this hook must report configured too — otherwise the composer is+ // spuriously disabled even though launch succeeds (VascoSch92 review #1571).+ useLlmProfilesMock.mockReturnValue(+ llmProfiles("default", [{ name: "default", api_key_set: true }]),+ );+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: {+ agent_kind: "openhands",+ llm_profile_ref: "ghost",+ name: "MyOH",+ },+ });++ const { result } = renderHook(() => useLlmConfigured(), { wrapper });+ expect(result.current.isConfigured).toBe(true);+ });++ it("is configured for an ACP agent profile regardless of LLM keys", () => {+ useLlmProfilesMock.mockReturnValue(+ llmProfiles("default", [{ name: "default", api_key_set: false }]),+ );+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: {+ agent_kind: "acp",+ llm_profile_ref: null,+ name: "MyClaude",+ },+ });++ const { result } = renderHook(() => useLlmConfigured(), { wrapper });+ expect(result.current.isConfigured).toBe(true);+ });+});diff --git a/__tests__/hooks/use-settings-nav-items.test.tsx b/__tests__/hooks/use-settings-nav-items.test.tsxindex 0b4ce21395..063e3e0d56 100644--- a/__tests__/hooks/use-settings-nav-items.test.tsx+++ b/__tests__/hooks/use-settings-nav-items.test.tsx@@ -12,6 +12,12 @@ const useActiveBackendMock = vi.fn<backend: { kind: "local" },orgId: null,}));+// The active AgentProfile now drives the ACP-disable derivation; default to+// "no active profile" so tests that set only `useSettings` exercise the+// settings fallback path.+const useActiveAgentProfileMock = vi.fn<+ () => { activeProfile: { agent_kind: string; name: string } | null }+>(() => ({ activeProfile: null }));vi.mock("#/hooks/query/use-config", () => ({useConfig: () => useConfigMock(),@@ -25,6 +31,10 @@ vi.mock("#/contexts/active-backend-context", () => ({useActiveBackend: () => useActiveBackendMock(),}));+vi.mock("#/hooks/use-active-agent-profile", () => ({+ useActiveAgentProfile: () => useActiveAgentProfileMock(),+}));+const createConfig = (feature_flags: Partial<WebClientConfig["feature_flags"]> = {},): WebClientConfig => ({@@ -58,6 +68,7 @@ describe("useSettingsNavItems", () => {backend: { kind: "local" },orgId: null,});+ useActiveAgentProfileMock.mockReturnValue({ activeProfile: null });});it("returns the LLM settings item unchanged on local backends", () => {@@ -68,9 +79,7 @@ describe("useSettingsNavItems", () => {(item) => item.type === "item" && item.item.to === "/settings/llm",);- const baseLlm = OSS_NAV_ITEMS.find(- (item) => item.to === "/settings/llm",- )!;+ const baseLlm = OSS_NAV_ITEMS.find((item) => item.to === "/settings/llm")!;expect(llmItem).toEqual({type: "item",item: baseLlm,@@ -86,11 +95,54 @@ describe("useSettingsNavItems", () => {const { result } = renderHook(() => useSettingsNavItems());+ // Agent profiles are available on cloud too (OpenHands #15060), so every+ // OSS item is present; only the `/settings` LLM-Profiles rename stays+ // local-only, so on cloud every item is passed through unchanged.expect(result.current).toEqual(OSS_NAV_ITEMS.map((item) => ({ type: "item", item })),);});+ it("shows a single Agent item (the profile library) on both local and cloud", () => {+ useConfigMock.mockReturnValue({ data: createConfig() });++ for (const kind of ["local", "cloud"] as const) {+ useActiveBackendMock.mockReturnValue({+ backend: { kind },+ orgId: kind === "cloud" ? "org-123" : null,+ });+ const paths = renderHook(() => useSettingsNavItems())+ .result.current.filter((item) => item.type === "item")+ .map((item) => (item.type === "item" ? item.item.to : null));+ // "Agent" IS the profile library; the old standalone /settings/agent+ // global-agent form + separate /settings/agents "Agent profiles" item+ // were collapsed into one.+ expect(paths).toContain("/settings/agents");+ expect(paths).not.toContain("/settings/agent");+ expect(paths.filter((p) => p === "/settings/agents")).toHaveLength(1);+ }+ });++ it("derives the ACP-disable from the active agent profile, not global settings", () => {+ useConfigMock.mockReturnValue({ data: createConfig() });+ // Global settings still say OpenHands, but the active profile is ACP —+ // the active profile wins (activate is pointer-only, #1571).+ useSettingsMock.mockReturnValue({ data: openHandsSettings });+ useActiveAgentProfileMock.mockReturnValue({+ activeProfile: { agent_kind: "acp", name: "MyClaude" },+ });++ const { result } = renderHook(() => useSettingsNavItems());+ const llm = result.current.find(+ (r) => r.type === "item" && r.item.to === "/settings/llm",+ );+ expect(llm?.type).toBe("item");+ if (llm?.type === "item") {+ expect(llm.disabled).toBe(true);+ expect(llm.disabledAgentName).toBe("MyClaude");+ }+ });+it("filters hidden routes from the OSS settings items", () => {useConfigMock.mockReturnValue({data: createConfig({ hide_llm_settings: true }),@@ -129,8 +181,7 @@ describe("useSettingsNavItems", () => {result.current.filter((item) => item.type === "item").map(- (item) =>- [item.type === "item" ? item.item.to : "", item] as const,+ (item) => [item.type === "item" ? item.item.to : "", item] as const,),);diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 162a99c66b..507e725000 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -3,7 +3,7 @@ import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { MemoryRouter } from "react-router";import { beforeEach, describe, expect, it, vi } from "vitest";-import AgentSettingsScreen from "#/routes/agent-settings";+import { AgentSettingsScreen } from "#/routes/agent-settings";import SettingsService from "#/api/settings-service/settings-service.api";import { SecretsService } from "#/api/secrets-service";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";diff --git a/__tests__/routes/build-agent-profile-fields.test.ts b/__tests__/routes/build-agent-profile-fields.test.tsnew file mode 100644index 0000000000..3d20ddee4b--- /dev/null+++ b/__tests__/routes/build-agent-profile-fields.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from "vitest";+import { buildAgentProfileFields } from "#/routes/agent-settings";+import type { SettingsFieldSchema } from "#/types/settings";++const baseAcp = {+ isAcp: true,+ selectedPreset: "claude-code",+ isDefaultProviderCommand: true,+ commandTokens: ["npx", "-y", "@zed-industries/claude-code-acp"],+ acpModel: "claude-opus-4-8",+ subAgentsEnabled: false,+ toolConcurrencyField: undefined,+ toolConcurrency: "",+};++const concurrencyField: SettingsFieldSchema = {+ key: "tool_concurrency_limit",+ label: "Tool concurrency limit",+ section: "agent",+ section_label: "Agent",+ value_type: "integer",+ choices: [],+ depends_on: [],+ prominence: "minor",+ secret: false,+ required: false,+};++describe("buildAgentProfileFields — ACP", () => {+ it("stores no explicit command for a built-in provider on its default command", () => {+ const fields = buildAgentProfileFields(baseAcp);+ expect(fields).toEqual({+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_model: "claude-opus-4-8",+ acp_command: null,+ acp_args: null,+ });+ });++ it("stores the verbatim shell command when it diverges from the default", () => {+ const fields = buildAgentProfileFields({+ ...baseAcp,+ isDefaultProviderCommand: false,+ commandTokens: ["npx", "-y", "@zed-industries/[email protected]"],+ });+ expect(fields.agent_kind).toBe("acp");+ if (fields.agent_kind === "acp") {+ expect(fields.acp_command).toBe(+ "npx -y @zed-industries/[email protected]",+ );+ }+ });++ it("stores the command for the custom preset even if it happens to match a default", () => {+ const fields = buildAgentProfileFields({+ ...baseAcp,+ selectedPreset: "custom",+ // A custom preset is never treated as a built-in default.+ isDefaultProviderCommand: true,+ commandTokens: ["my-acp", "--flag"],+ });+ if (fields.agent_kind === "acp") {+ expect(fields.acp_server).toBe("custom");+ expect(fields.acp_command).toBe("my-acp --flag");+ }+ });++ it("normalizes a blank model to null", () => {+ const fields = buildAgentProfileFields({ ...baseAcp, acpModel: " " });+ if (fields.agent_kind === "acp") {+ expect(fields.acp_model).toBeNull();+ }+ });+});++describe("buildAgentProfileFields — OpenHands", () => {+ const baseOh = {+ isAcp: false,+ selectedPreset: "custom",+ isDefaultProviderCommand: false,+ commandTokens: [],+ acpModel: "",+ subAgentsEnabled: true,+ toolConcurrencyField: undefined,+ toolConcurrency: "",+ };++ it("passes through enable_sub_agents and omits concurrency when the field is absent", () => {+ expect(buildAgentProfileFields(baseOh)).toEqual({+ agent_kind: "openhands",+ enable_sub_agents: true,+ });+ });++ it("coerces a valid tool_concurrency_limit to a number", () => {+ const fields = buildAgentProfileFields({+ ...baseOh,+ toolConcurrencyField: concurrencyField,+ toolConcurrency: "3",+ });+ if (fields.agent_kind === "openhands") {+ expect(fields.tool_concurrency_limit).toBe(3);+ }+ });++ it("falls back to the schema default (1) when the input is empty, so a clear actually clears (#1571 review)", () => {+ // A blank field coerces to `null`; the field itself is a non-nullable+ // backend int, so an explicit default — not an omitted key — is what+ // actually resets a stored value on an edit-save (the whole-profile merge+ // would otherwise silently keep the old value for an omitted key).+ const fields = buildAgentProfileFields({+ ...baseOh,+ toolConcurrencyField: concurrencyField,+ toolConcurrency: "",+ });+ if (fields.agent_kind === "openhands") {+ expect(fields.tool_concurrency_limit).toBe(1);+ }+ });++ it("falls back to the schema's own default value when the field declares one", () => {+ const fields = buildAgentProfileFields({+ ...baseOh,+ toolConcurrencyField: { ...concurrencyField, default: 2 },+ toolConcurrency: "",+ });+ if (fields.agent_kind === "openhands") {+ expect(fields.tool_concurrency_limit).toBe(2);+ }+ });++ it("throws on a non-numeric concurrency value (schema-driven validation)", () => {+ expect(() =>+ buildAgentProfileFields({+ ...baseOh,+ toolConcurrencyField: concurrencyField,+ toolConcurrency: "abc",+ }),+ ).toThrow();+ });+});diff --git a/__tests__/routes/llm-settings.test.tsx b/__tests__/routes/llm-settings.test.tsxindex 2b4aff98bd..f8cfded4f0 100644--- a/__tests__/routes/llm-settings.test.tsx+++ b/__tests__/routes/llm-settings.test.tsx@@ -16,8 +16,8 @@ import LLMSubscriptionService from "#/api/llm-subscription-service";vi.mock("#/hooks/query/use-llm-profiles");// The profile manager gates mutate controls on this hook; default to a user// who can manage so the manager renders its full (editable) surface.-vi.mock("#/hooks/use-can-manage-llm-profiles", () => ({- useCanManageLlmProfiles: () => true,+vi.mock("#/hooks/use-can-manage-org-profiles", () => ({+ useCanManageOrgProfiles: () => true,}));function buildSettings(overrides: Partial<Settings> = {}): Settings {diff --git a/__tests__/routes/settings.test.tsx b/__tests__/routes/settings.test.tsxindex 3463ba2330..ea3bb9165b 100644--- a/__tests__/routes/settings.test.tsx+++ b/__tests__/routes/settings.test.tsx@@ -21,6 +21,15 @@ vi.mock("#/hooks/use-settings-nav-items", () => ({).map((item) => ({ type: "item", item })),}));+// The ACP route guard now reads the active agent profile first, falling back to+// settings. These tests drive the guard via `SettingsService`, so make the+// agent-profiles lookup unavailable to force that deterministic fallback.+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({+ default: {+ listProfiles: vi.fn().mockRejectedValue(new Error("no agent profiles")),+ },+}));+describe("settings route", () => {beforeEach(() => {vi.restoreAllMocks();@@ -35,19 +44,19 @@ describe("settings route", () => {queryClient.clear();});- it("prefers /settings/agent when LLM settings are hidden", () => {- // /settings/agent is the unconditional first fallback — always+ it("prefers /settings/agents when LLM settings are hidden", () => {+ // /settings/agents is the unconditional first fallback — always// available and the single place to switch agent kinds.expect(getFirstAvailablePath({hide_llm_settings: true,hide_users_page: true,}),- ).toBe("/settings/agent");+ ).toBe("/settings/agents");});- it("prefers /settings/agent when LLM settings are visible", () => {- // /settings/agent wins unconditionally, so OpenHands users land+ it("prefers /settings/agents when LLM settings are visible", () => {+ // /settings/agents wins unconditionally, so OpenHands users land// there too and reach LLM via the left nav instead of bouncing// through /settings/llm (which is disabled for ACP users).expect(@@ -55,7 +64,7 @@ describe("settings route", () => {hide_llm_settings: false,hide_users_page: true,}),- ).toBe("/settings/agent");+ ).toBe("/settings/agents");});it("redirects hidden OSS settings pages to the first available route", async () => {@@ -80,7 +89,7 @@ describe("settings route", () => {} as never)) as Response;expect(response.status).toBe(302);- expect(response.headers.get("Location")).toBe("/settings/agent");+ expect(response.headers.get("Location")).toBe("/settings/agents");});it("does not redirect unrelated removed nested paths through the settings loader", async () => {@@ -135,7 +144,7 @@ describe("settings route", () => {expect(screen.getByTestId("app-settings-screen")).toBeInTheDocument();});- it("redirects to /settings/agent when ACP is active and the path is disabled-by-ACP", async () => {+ it("redirects to /settings/agents when ACP is active and the path is disabled-by-ACP", async () => {vi.spyOn(OptionService, "getConfig").mockResolvedValue({posthog_client_key: null,feature_flags: {@@ -165,7 +174,7 @@ describe("settings route", () => {} as never)) as Response;expect(response.status).toBe(302);- expect(response.headers.get("Location")).toBe("/settings/agent");+ expect(response.headers.get("Location")).toBe("/settings/agents");});it("does not redirect when the active agent is OpenHands", async () => {diff --git a/__tests__/utils/acp-route-guard.test.ts b/__tests__/utils/acp-route-guard.test.tsnew file mode 100644index 0000000000..62b0338526--- /dev/null+++ b/__tests__/utils/acp-route-guard.test.ts@@ -0,0 +1,56 @@+import { describe, it, expect, vi, afterEach } from "vitest";+import { redirectIfAcpActive } from "#/utils/acp-route-guard";+import { getQueryClient } from "#/query-client-config";++// `queryClient` (used by the guard) is a Proxy around the lazily-created+// singleton — spy on the real underlying client instance so vi.spyOn can find+// an actual own property to wrap.+const queryClient = getQueryClient();++describe("redirectIfAcpActive", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("uses the shared no-retry policy for the agent-profiles fetch (#1571 review)", async () => {+ // An older backend without /api/agent-profiles must fail this fast rather+ // than sitting through the default exponential backoff on every settings+ // navigation — the retry policy is shared with useAgentProfiles and the+ // launch path in useCreateConversation so it can't drift between them.+ const fetchQuerySpy = vi+ .spyOn(queryClient, "fetchQuery")+ .mockResolvedValueOnce({+ profiles: [+ {+ id: "p1",+ name: "default",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "gpt",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "p1",+ } as never);++ await redirectIfAcpActive();++ expect(fetchQuerySpy).toHaveBeenCalledTimes(1);+ expect(fetchQuerySpy.mock.calls[0]?.[0]).toMatchObject({ retry: false });+ });++ it("falls through to the settings fallback (default retry policy) when the profile list can't resolve isAcp", async () => {+ const fetchQuerySpy = vi+ .spyOn(queryClient, "fetchQuery")+ .mockResolvedValueOnce({ profiles: [], active_agent_profile_id: null })+ .mockResolvedValueOnce({ agent_settings: { agent_kind: "openhands" } });++ const result = await redirectIfAcpActive();++ expect(result).toBeNull();+ expect(fetchQuerySpy).toHaveBeenCalledTimes(2);+ // The settings fallback isn't part of the shared agent-profiles retry+ // policy — it's a different (always-available) surface.+ expect(fetchQuerySpy.mock.calls[1]?.[0]).not.toHaveProperty("retry");+ });+});diff --git a/src/api/agent-profiles-service/agent-profiles-service.api.ts b/src/api/agent-profiles-service/agent-profiles-service.api.tsnew file mode 100644index 0000000000..530d96f772--- /dev/null+++ b/src/api/agent-profiles-service/agent-profiles-service.api.ts@@ -0,0 +1,130 @@+/**+ * AgentProfilesService wraps the SDK's AgentProfilesClient, creating a client+ * per-call so it always picks up the active backend's host/apiKey (same pattern+ * as ProfilesService / SettingsService).+ *+ * Backs the Settings → Agent profiles library + reused agent editor. The+ * `AgentProfilesClient` ships in ts-client (pinned 1.28.0 here); the+ * `/api/agent-profiles` endpoints it targets shipped in agent-server v1.29.0+ * (local) and in the enterprise cloud app-server (OpenHands #15060, epic+ * #3730). Cloud exposes the SAME contract but authenticates with a bearer+ * token + `X-Org-Id`, so cloud calls route through `callCloudProxy` (see+ * `cloud/agent-profiles-service.api.ts`) instead of the direct client.+ */+import {+ AgentProfilesClient,+ type GetAgentProfileOptions,+} from "@openhands/typescript-client/clients";+import type {+ AgentProfile,+ AgentProfileSummary,+ AgentProfileSaveInput,+ AgentProfileListResponse,+ AgentProfileDetailResponse,+ AgentProfileMutationResponse,+ ActivateAgentProfileResponse,+ ExposeSecretsMode,+} from "@openhands/typescript-client";+import { getAgentServerClientOptions } from "../agent-server-client-options";+import { getActiveBackend } from "../backend-registry/active-store";+import {+ listCloudAgentProfiles,+ getCloudAgentProfile,+ saveCloudAgentProfile,+ deleteCloudAgentProfile,+ renameCloudAgentProfile,+ activateCloudAgentProfile,+} from "../cloud/agent-profiles-service.api";++function isCloud(): boolean {+ return getActiveBackend().backend.kind === "cloud";+}++/**+ * The seeded, well-known baseline agent profile. The backend lazily seeds it to+ * mirror the user's global config (#3719), and onboarding configures it from the+ * user's choice. It stands in for global `agent_settings`, so the home-launch+ * path treats it as the enriched baseline rather than a deliberate profile+ * selection (see `useCreateConversation`).+ */+export const WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME = "default";++// Re-export SDK types for consumers.+export type {+ AgentProfile,+ AgentProfileSummary,+ AgentProfileSaveInput,+ AgentProfileListResponse,+ AgentProfileDetailResponse,+ AgentProfileMutationResponse,+ ActivateAgentProfileResponse,+};++class AgentProfilesService {+ static async listProfiles(): Promise<AgentProfileListResponse> {+ if (isCloud()) return listCloudAgentProfiles();+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).listAgentProfiles();+ }++ static async getProfile(+ name: string,+ exposeSecrets?: ExposeSecretsMode,+ ): Promise<AgentProfileDetailResponse> {+ // Agent profiles are secret-free at rest now (embedded skills and their+ // `mcp_tools` were removed in #4017 — a profile carries only refs + the+ // `disabled_skills` deny-list of names), so `exposeSecrets` is vestigial and+ // cloud ignores it; kept for local signature parity with ProfilesService.+ if (isCloud()) return getCloudAgentProfile(name);+ const options: GetAgentProfileOptions = exposeSecrets+ ? { exposeSecrets }+ : {};+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).getAgentProfile(name, options);+ }++ /** Create or overwrite a profile by name (upsert). */+ static async saveProfile(+ name: string,+ profile: AgentProfileSaveInput,+ ): Promise<AgentProfileMutationResponse> {+ if (isCloud()) return saveCloudAgentProfile(name, profile);+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).saveAgentProfile(name, profile);+ }++ static async deleteProfile(+ name: string,+ ): Promise<AgentProfileMutationResponse> {+ if (isCloud()) return deleteCloudAgentProfile(name);+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).deleteAgentProfile(name);+ }++ static async renameProfile(+ name: string,+ newName: string,+ ): Promise<AgentProfileMutationResponse> {+ if (isCloud()) return renameCloudAgentProfile(name, newName);+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).renameAgentProfile(name, newName);+ }++ /** Activate by the profile's stable UUID `id` (pointer-only; never writes+ * agent_settings). */+ static async activateProfile(+ profileId: string,+ ): Promise<ActivateAgentProfileResponse> {+ if (isCloud()) return activateCloudAgentProfile(profileId);+ return new AgentProfilesClient(+ getAgentServerClientOptions(),+ ).activateAgentProfile(profileId);+ }+}++export default AgentProfilesService;diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.tsindex daae033906..7248b9058d 100644--- a/src/api/agent-server-adapter.test.ts+++ b/src/api/agent-server-adapter.test.ts@@ -44,8 +44,10 @@ describe("buildStartConversationRequest", () => {secretsEncrypted: true,});- expect(payload.agent_settings.agent_kind).toBe("openhands");- expect(payload.agent_settings.mcp_config).toEqual(agentSettings.mcp_config);+ expect(payload.agent_settings!.agent_kind).toBe("openhands");+ expect(payload.agent_settings!.mcp_config).toEqual(+ agentSettings.mcp_config,+ );expect(payload.secrets_encrypted).toBe(true);});@@ -74,8 +76,10 @@ describe("buildStartConversationRequest", () => {secretsEncrypted: true,});- expect(payload.agent_settings.agent_kind).toBe("acp");- expect(payload.agent_settings.mcp_config).toEqual(agentSettings.mcp_config);+ expect(payload.agent_settings!.agent_kind).toBe("acp");+ expect(payload.agent_settings!.mcp_config).toEqual(+ agentSettings.mcp_config,+ );expect(payload.secrets_encrypted).toBe(true);});@@ -101,7 +105,79 @@ describe("buildStartConversationRequest", () => {secretsEncrypted: true,});- expect(payload.agent_settings.agent_kind).toBe("acp");+ expect(payload.agent_settings!.agent_kind).toBe("acp");+ expect(payload.secrets_encrypted).toBeUndefined();+ });+});++describe("buildStartConversationRequest — agentProfileId path", () => {+ it("sends agent_profile_id and omits agent_settings (mutually exclusive)", () => {+ const settings = makeSettings({+ agent_kind: "openhands",+ llm: { model: "litellm_proxy/openai/gpt-5.5", api_key: "sk-test" },+ });++ const payload = buildStartConversationRequest({+ settings,+ agentProfileId: "profile-xyz",+ });++ expect(payload.agent_profile_id).toBe("profile-xyz");+ expect(payload.agent_settings).toBeUndefined();+ });++ it("suppresses the ACP server tag when launching from a profile", () => {+ const agentSettings = {+ agent_kind: "acp",+ acp_server: "codex",+ acp_command: ["codex-acp"],+ acp_model: "gpt-5.5/medium",+ };++ // Without a profile the ACP server tag is stamped from settings...+ expect(+ buildStartConversationRequest({ settings: makeSettings(agentSettings) })+ .tags,+ ).toBeDefined();++ // ...but a profile launch resolves the server server-side, so the tag+ // (which may not match the launched profile) is omitted.+ const payload = buildStartConversationRequest({+ settings: makeSettings(agentSettings),+ agentProfileId: "profile-xyz",+ });+ expect(payload.tags).toBeUndefined();+ });++ it("suppresses secrets_encrypted when launching from a profile", () => {+ const agentSettings = {+ agent_kind: "openhands",+ llm: {+ model: "litellm_proxy/openai/gpt-5.5",+ api_key: "gAAAAAencrypted-llm-api-key",+ },+ mcp_config: {+ mcpServers: {+ linear: {+ url: "https://mcp.linear.app/mcp",+ transport: "http",+ headers: { Authorization: encryptedValue },+ },+ },+ },+ };+ const settings = makeSettings(agentSettings);++ // Same inputs without a profile would set secrets_encrypted (covered+ // above); the profile path defers secret resolution to the server.+ const payload = buildStartConversationRequest({+ settings,+ encryptedAgentSettings: agentSettings,+ encryptedConversationSettings: settings.conversation_settings!,+ secretsEncrypted: true,+ agentProfileId: "profile-xyz",+ });+expect(payload.secrets_encrypted).toBeUndefined();});});diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex 4d17bc61df..203046b02e 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -57,6 +57,13 @@ export interface DirectConversationInfo {*/kind?: string | null;acp_model?: string | null;+ /**+ * ACP CLI identity (``claude-code`` / ``codex`` / ``gemini-cli``) from the+ * SDK's ``ACPAgent.acp_server`` (#3692). Preferred fallback when the+ * ``acpserver`` tag is absent — e.g. a profile launch doesn't stamp the tag+ * client-side and the server may not repopulate it. Read by {@link toAppConversation}.+ */+ acp_server?: string | null;llm?: {model?: string | null;} | null;@@ -300,8 +307,13 @@ export function toAppConversation(// Only surface ``acp_server`` for ACP conversations even if the wire// payload accidentally carries an ``acpserver`` tag on an OpenHands// conversation — the chip is identity info for the ACP CLI subprocess,- // and showing it on a non-ACP conversation would be a lie.- const acpServer = isAcp ? (info.tags?.[ACP_SERVER_TAG_KEY] ?? null) : null;+ // and showing it on a non-ACP conversation would be a lie. Fall back to the+ // agent's own ``acp_server`` (#3692) when the tag is missing — a profile+ // launch doesn't stamp the tag, so tag-only reads would drop the ACP model+ // picker and degrade the chip to a generic "ACP" (#1571).+ const acpServer = isAcp+ ? (info.tags?.[ACP_SERVER_TAG_KEY] ?? info.agent?.acp_server ?? null)+ : null;return {id: info.id,created_by_user_id: null,@@ -856,7 +868,10 @@ interface LookupSecret {}type StartConversationPayload = Record<string, unknown> & {- agent_settings: AgentSettingsPayload;+ // Omitted when launching via ``agent_profile_id`` — the two are mutually+ // exclusive agent sources; the server resolves the profile server-side.+ agent_settings?: AgentSettingsPayload;+ agent_profile_id?: string;workspace: LocalWorkspacePayload;confirmation_policy: SettingsRecord;security_analyzer?: SettingsRecord;@@ -884,6 +899,9 @@ export interface StartConversationOptions {encryptedConversationSettings?: Record<string, SettingsValue>;secretsEncrypted?: boolean;customSecrets?: Array<{ name: string; description?: string }>;+ // When set, the conversation launches from this AgentProfile (resolved+ // server-side) instead of an inline ``agent_settings`` dump (#3727).+ agentProfileId?: string;}export function buildStartConversationRequest(@@ -914,7 +932,23 @@ export function buildStartConversationRequest();const payload: StartConversationPayload = {- agent_settings: agentSettings,+ // ``agent_profile_id`` and ``agent_settings`` are mutually exclusive agent+ // sources; the profile path lets the server resolve the profile (#3727).+ //+ // Enrichment boundary: on the profile path the server rebuilds the agent+ // purely from the stored profile fields, so the client-owned enrichments+ // this adapter folds into ``agent_settings`` do NOT apply. The exec toolset+ // (terminal/file_editor/task_tracker) and public-skill loading are the+ // server/SDK's responsibility to restore on the profile path — tracked in+ // software-agent-sdk#3967 (profile resolution must attach the default+ // toolset + public skills, else a profile-launched OpenHands agent has only+ // Finish/Think). The two genuinely canvas-only enrichments — the+ // ``canvas_ui`` tool and the dev ``RUNTIME_SERVICES`` system-message-suffix+ // (``buildAgentContext``) — have no server-side representation and are+ // intentionally not carried on the profile path.+ ...(options.agentProfileId+ ? { agent_profile_id: options.agentProfileId }+ : { agent_settings: agentSettings }),workspace: conversationSettings.workspace,confirmation_policy:getConversationConfirmationPolicy(conversationSettings),@@ -927,7 +961,9 @@ export function buildStartConversationRequest(worktree: options.worktree ?? true,};- if (acpServerTag) {+ // A profile launch resolves the ACP server server-side, so don't stamp the+ // tag from current settings (it may not match the launched profile).+ if (!options.agentProfileId && acpServerTag) {payload.tags = { [ACP_SERVER_TAG_KEY]: acpServerTag };}@@ -938,6 +974,7 @@ export function buildStartConversationRequest(// encrypted settings round-trip mcp_config secrets as Fernet tokens,// and ACP forwards mcp_config directly to the subprocess.if (+ !options.agentProfileId &&options.secretsEncrypted &&(!acpMode || hasEncryptedMcpSecrets(agentSettings.mcp_config))) {@@ -1047,6 +1084,7 @@ export async function buildStartConversationRequestWithEncryptedSettings(optionsconversationId?: string;workingDir?: string;worktree?: boolean;+ agentProfileId?: string;}): Promise<Record<string, unknown>> {const { SecretsService } = await import("./secrets-service");@@ -1058,7 +1096,11 @@ export async function buildStartConversationRequestWithEncryptedSettings(optionsconst { agentSettings, conversationSettings, secretsEncrypted } =settingsResult;- await assertSubscriptionAuthReady(agentSettings);+ // A profile launch resolves the LLM server-side, so the current-settings+ // subscription check doesn't apply (and can't see the profile's LLM).+ if (!options.agentProfileId) {+ await assertSubscriptionAuthReady(agentSettings);+ }return buildStartConversationRequest({...options,diff --git a/src/api/cloud/agent-profiles-service.api.ts b/src/api/cloud/agent-profiles-service.api.tsnew file mode 100644index 0000000000..010876afb6--- /dev/null+++ b/src/api/cloud/agent-profiles-service.api.ts@@ -0,0 +1,98 @@+import type {+ AgentProfileSaveInput,+ AgentProfileListResponse,+ AgentProfileDetailResponse,+ AgentProfileMutationResponse,+ ActivateAgentProfileResponse,+} from "@openhands/typescript-client";+import { getActiveBackend } from "../backend-registry/active-store";+import type { Backend } from "../backend-registry/types";+import { callCloudProxy } from "./proxy";++/**+ * Cloud transport for the Agent Profiles surface. The cloud enterprise+ * app-server exposes the SAME `/api/agent-profiles` contract as the local+ * agent-server (paths + response shapes mirror `agent_profiles_router.py`),+ * but cloud calls authenticate with the backend's bearer token + `X-Org-Id`+ * and must go through {@link callCloudProxy} — not the direct+ * `AgentProfilesClient` (which speaks `X-Session-API-Key` to a local host).+ *+ * The org is resolved server-side from the auth session (`EFFECTIVE_ORG_ID`),+ * so — unlike org LLM profiles — no `{org_id}` path segment is needed here.+ *+ * Mirrors the pattern in `cloud/settings-service.api.ts`. Consumed by+ * `AgentProfilesService` on the cloud path.+ */++const BASE = "/api/agent-profiles";++function activeCloudBackend(): Backend {+ const active = getActiveBackend().backend;+ if (active.kind !== "cloud") {+ throw new Error("Cloud agent-profile call requires a cloud backend.");+ }+ return active;+}++export async function listCloudAgentProfiles(): Promise<AgentProfileListResponse> {+ return callCloudProxy<AgentProfileListResponse>({+ backend: activeCloudBackend(),+ method: "GET",+ path: BASE,+ });+}++export async function getCloudAgentProfile(+ name: string,+): Promise<AgentProfileDetailResponse> {+ return callCloudProxy<AgentProfileDetailResponse>({+ backend: activeCloudBackend(),+ method: "GET",+ path: `${BASE}/${encodeURIComponent(name)}`,+ });+}++export async function saveCloudAgentProfile(+ name: string,+ profile: AgentProfileSaveInput,+): Promise<AgentProfileMutationResponse> {+ return callCloudProxy<AgentProfileMutationResponse>({+ backend: activeCloudBackend(),+ method: "POST",+ path: `${BASE}/${encodeURIComponent(name)}`,+ body: profile,+ });+}++export async function deleteCloudAgentProfile(+ name: string,+): Promise<AgentProfileMutationResponse> {+ return callCloudProxy<AgentProfileMutationResponse>({+ backend: activeCloudBackend(),+ method: "DELETE",+ path: `${BASE}/${encodeURIComponent(name)}`,+ });+}++export async function renameCloudAgentProfile(+ name: string,+ newName: string,+): Promise<AgentProfileMutationResponse> {+ return callCloudProxy<AgentProfileMutationResponse>({+ backend: activeCloudBackend(),+ method: "POST",+ path: `${BASE}/${encodeURIComponent(name)}/rename`,+ body: { new_name: newName },+ });+}++export async function activateCloudAgentProfile(+ profileId: string,+): Promise<ActivateAgentProfileResponse> {+ return callCloudProxy<ActivateAgentProfileResponse>({+ backend: activeCloudBackend(),+ method: "POST",+ path: `${BASE}/${encodeURIComponent(profileId)}/activate`,+ body: {},+ });+}diff --git a/src/api/cloud/organization-service.api.ts b/src/api/cloud/organization-service.api.tsindex 9d4fa54033..64d6686758 100644--- a/src/api/cloud/organization-service.api.ts+++ b/src/api/cloud/organization-service.api.ts@@ -93,7 +93,7 @@ export async function getCurrentCloudApiKey(* `null` if the upstream omits it). `permissions` is the server-defined* permission set for that role (e.g. `edit_org_settings`); it is `null` on* older app-servers that don't return it, so callers fall back to the role.- * See `useCanManageLlmProfiles`.+ * See `useCanManageOrgProfiles`.*/export async function getCloudOrganizationMe(orgId: string,diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex fdd8ce71c7..1b4ccafde1 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -135,14 +135,18 @@ function normalizeAgent(value: unknown): DirectConversationInfo["agent"] {? { model: stringOrNull(value.llm.model) }: null;// ``kind`` is the SDK's pydantic discriminator (``"Agent"`` vs ``"ACPAgent"``);- // ``toAppConversation`` reads it to derive ``agent_kind``. ``acp_model`` is- // the Canvas-configured model on the ACPAgent — preserved so the conversation- // adapter and the conversation chip can fall back to it when the SDK runtime- // model fields aren't populated. Preserving these here makes the wire path- // agree with the unit-test path that builds ``DirectConversationInfo``- // directly (e.g. ``__tests__/api/agent-server-adapter.test.ts``).+ // ``toAppConversation`` reads it to derive ``agent_kind``. ``acp_server`` is+ // the ACP provider identity (``ACPAgent.acp_server``, SDK #3692) — required so+ // the adapter can source the chip + in-conversation model list from the agent+ // when the ``acpserver`` tag is absent (a profile launch doesn't stamp it,+ // #1571). ``acp_model`` is the Canvas-configured model — preserved so the chip+ // can fall back to it when the SDK runtime model fields aren't populated.+ // Preserving these makes the wire path agree with the unit-test path that+ // builds ``DirectConversationInfo`` directly+ // (e.g. ``__tests__/api/agent-server-adapter.test.ts``).return {kind: stringOrNull(value.kind),+ acp_server: stringOrNull(value.acp_server),acp_model: stringOrNull(value.acp_model),llm,};@@ -352,6 +356,11 @@ class AgentServerConversationService {parentConversationId?: string,agentType?: "default" | "plan",sandboxId?: string,+ // Launch from a saved AgentProfile (resolved server-side) instead of the+ // current encrypted agent_settings (#3727). Supported on both local and the+ // cloud app-server (OpenHands #15060): local threads it through the+ // encrypted-settings builder; cloud sends it as a flat request field.+ agentProfileId?: string,): Promise<AppConversationStartTask> {if (getActiveBackend().backend.kind === "cloud") {// Cloud path mirrors OpenHands' frontend: build a flat@@ -359,6 +368,8 @@ class AgentServerConversationService {// (returns a WORKING task), and let the conversation route's// useTaskPolling drive it to READY. NO encrypted-settings// round-trip — the cloud backend holds secrets server-side.+ // When launching from a profile, send `agent_profile_id`; the backend+ // resolves it to agent_settings server-side.const request: AppConversationStartRequest = {initial_message: initialUserMsg? {@@ -374,6 +385,7 @@ class AgentServerConversationService {parent_conversation_id: parentConversationId ?? null,agent_type: agentType,sandbox_id: sandboxId ?? null,+ agent_profile_id: agentProfileId ?? null,};return createCloudAppConversation(request);}@@ -401,6 +413,7 @@ class AgentServerConversationService {conversationId,workingDir,worktree: resolvedWorkspaceMode === "new_worktree",+ agentProfileId,});const data = await new ConversationClient(diff --git a/src/api/conversation-service/agent-server-conversation-service.types.ts b/src/api/conversation-service/agent-server-conversation-service.types.tsindex 724507d6c1..787725551b 100644--- a/src/api/conversation-service/agent-server-conversation-service.types.ts+++ b/src/api/conversation-service/agent-server-conversation-service.types.ts@@ -82,6 +82,11 @@ export interface AppConversationStartRequest {agent_type?: "default" | "plan";sandbox_id?: string | null;plugins?: PluginSpec[] | null; // Plugins to load when starting the conversation+ // One-off launch from a saved AgentProfile, resolved server-side (#3727).+ // Accepted by the cloud app-server (OpenHands #15060) on+ // POST /api/v1/app-conversations; the local path uses the encrypted+ // agent_settings builder instead, which threads its own agentProfileId.+ agent_profile_id?: string | null;}export type AppConversationStartTaskStatus =diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsxindex 17d88c7ff9..8afbd03403 100644--- a/src/components/features/chat/chat-interface.tsx+++ b/src/components/features/chat/chat-interface.tsx@@ -573,7 +573,7 @@ export function ChatInterface() {}onReauth={isAcpAuthErrorCode(errorCode)- ? () => navigate("/settings/agent")+ ? () => navigate("/settings/agents"): undefined}/>diff --git a/src/components/features/chat/components/chat-input-actions.tsx b/src/components/features/chat/components/chat-input-actions.tsxindex 78f0f774e9..a8ee86dea4 100644--- a/src/components/features/chat/components/chat-input-actions.tsx+++ b/src/components/features/chat/components/chat-input-actions.tsx@@ -5,7 +5,15 @@ import { Cpu } from "lucide-react";import { AgentStatus } from "#/components/features/controls/agent-status";import { ChangeAgentButton } from "../change-agent-button";import { ChatInputModel, ChatInputModelMenuContent } from "./chat-input-model";-import { SwitchProfileButton } from "../switch-profile-button";+import {+ ChatInputProfilePicker,+ ChatInputProfileMenuContent,+} from "./chat-input-profile-picker";+import {+ ChatInputLlmProfilePicker,+ ChatInputLlmProfileMenuContent,+} from "./chat-input-llm-profile-picker";+import { resolvePickerKind } from "./resolve-picker-kind";import { ChatAddFileButton } from "../chat-add-file-button";import { ChatSendButton } from "../chat-send-button";import CarretRightFillIcon from "#/icons/carret-right-fill.svg?react";@@ -17,6 +25,7 @@ import { useOptionalConversationId } from "#/hooks/use-conversation-id";import { usePauseConversation } from "#/hooks/mutation/use-pause-conversation";import { useResumeConversation } from "#/hooks/mutation/use-resume-conversation";import { useActiveBackend } from "#/contexts/active-backend-context";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";import { useChatInputModelState } from "#/hooks/use-chat-input-model-state";import { useConversationStore } from "#/stores/conversation-store";import { useAgentState } from "#/hooks/use-agent-state";@@ -59,6 +68,16 @@ export function ChatInputActions({const { backend } = useActiveBackend();const isCloud = backend.kind === "cloud";const modelState = useChatInputModelState();+ // The home page defaults to the AgentProfile picker (#3727) on both local and+ // cloud (cloud gained the /api/agent-profiles surface in OpenHands #15060). A+ // backend without that surface returns none — fall back so the composer still+ // shows a model affordance instead of nothing (#1571). Only fetched on home.+ const homeAgentProfiles = useAgentProfiles({+ enabled: !conversationId,+ });+ const agentProfilesUnavailableOnHome =+ homeAgentProfiles.isFetched &&+ (homeAgentProfiles.data?.profiles?.length ?? 0) === 0;// Code/Plan mode switching is a cloud OpenHands feature — it doesn't apply// to ACP conversations (which have no "plan" mode), so hide it when ACP.const showChangeAgentButton = isCloud && !modelState.isAcpContext;@@ -224,6 +243,25 @@ export function ChatInputActions({setIsOverflowOpen(false);};+ // Which chat-input model/profile picker to show (pure matrix, unit-tested in+ // `resolve-picker-kind.test.ts`).+ const pickerKind = resolvePickerKind({+ hasConversation: !!conversationId,+ isCloud,+ isAcp: modelState.isAcpContext,+ profilesAvailable: !agentProfilesUnavailableOnHome,+ });++ // Shared styling for the settings link inside the overflow submenu content.+ const overflowSettingsLinkClassName = cn(+ "group",+ formControlTransitionClassName,+ );+ const overflowSettingsIconClassName = cn(+ "text-[var(--oh-muted)] group-hover:text-[var(--oh-foreground)]",+ formControlTransitionClassName,+ );+React.useLayoutEffect(() => {if (!isOverflowOpen || !overflowTriggerRef.current) {return;@@ -367,19 +405,29 @@ export function ChatInputActions({testId="overflow-model-submenu"className="min-w-[220px] max-w-[320px] max-h-[60vh] overflow-y-auto gap-0">- <ChatInputModelMenuContent- model={modelState}- onClose={closeOverflowMenus}- dividerInset="menu"- settingsLinkClassName={cn(- "group",- formControlTransitionClassName,- )}- settingsIconClassName={cn(- "text-[var(--oh-muted)] group-hover:text-[var(--oh-foreground)]",- formControlTransitionClassName,- )}- />+ {pickerKind === "model" ? (+ <ChatInputModelMenuContent+ model={modelState}+ onClose={closeOverflowMenus}+ dividerInset="menu"+ settingsLinkClassName={overflowSettingsLinkClassName}+ settingsIconClassName={overflowSettingsIconClassName}+ />+ ) : pickerKind === "agent-profile" ? (+ <ChatInputProfileMenuContent+ onClose={closeOverflowMenus}+ dividerInset="menu"+ settingsLinkClassName={overflowSettingsLinkClassName}+ settingsIconClassName={overflowSettingsIconClassName}+ />+ ) : (+ <ChatInputLlmProfileMenuContent+ onClose={closeOverflowMenus}+ dividerInset="menu"+ settingsLinkClassName={overflowSettingsLinkClassName}+ settingsIconClassName={overflowSettingsIconClassName}+ />+ )}</ContextMenu></div></div>@@ -406,10 +454,14 @@ export function ChatInputActions({</div>)}<div ref={modelRef} className={cn(!showModelInline && "hidden")}>- {modelState.isAcpContext ? (+ {/* Picker depends on backend + whether we're in a conversation;+ see the `pickerKind` cases above. */}+ {pickerKind === "model" ? (<ChatInputModel />+ ) : pickerKind === "agent-profile" ? (+ <ChatInputProfilePicker />) : (- <SwitchProfileButton />+ <ChatInputLlmProfilePicker />)}</div>diff --git a/src/components/features/chat/components/chat-input-llm-profile-picker.tsx b/src/components/features/chat/components/chat-input-llm-profile-picker.tsxnew file mode 100644index 0000000000..b2fa243f42--- /dev/null+++ b/src/components/features/chat/components/chat-input-llm-profile-picker.tsx@@ -0,0 +1,191 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { useChatInputLlmProfileState } from "#/hooks/use-chat-input-llm-profile-state";+import { ComboboxCaretInline } from "#/ui/combobox-caret";+import SettingsGearIcon from "#/icons/settings-gear.svg?react";+import CheckIcon from "#/icons/checkmark.svg?react";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { NavigationLink } from "#/components/shared/navigation-link";+import { ContextMenu } from "#/ui/context-menu";+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";+import { Divider } from "#/ui/divider";+import { Typography } from "#/ui/typography";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";+import { chatInputPillButtonClassName } from "#/utils/form-control-classes";++const PROFILE_LABEL_MAX_CHARS = 18;++function truncateLabel(label: string): string {+ return label.length <= PROFILE_LABEL_MAX_CHARS+ ? label+ : `${label.slice(0, PROFILE_LABEL_MAX_CHARS)}…`;+}++interface ChatInputLlmProfileMenuContentProps {+ onClose: () => void;+ dividerInset?: "menu";+ settingsLinkClassName?: string;+ settingsIconClassName?: string;+}++/**+ * The in-conversation OpenHands LLM-profile switcher list. Selecting a profile+ * live-swaps the running conversation's LLM via `/switch_profile` (the ACP+ * analog is {@link ChatInputModelMenuContent}). Shared by the inline pill and+ * the chat-input overflow submenu.+ */+export function ChatInputLlmProfileMenuContent({+ onClose,+ dividerInset,+ settingsLinkClassName,+ settingsIconClassName,+}: ChatInputLlmProfileMenuContentProps) {+ const { t } = useTranslation("openhands");+ const { profiles, currentProfileName, selectProfile } =+ useChatInputLlmProfileState();++ const handleSelect = (profileName: string) => {+ selectProfile(profileName);+ onClose();+ };++ return (+ <>+ {profiles.length > 0 && (+ <>+ {/* role="presentation" keeps this a valid <li> child of the+ ContextMenu <ul> without exposing the label as a menu item. */}+ <li role="presentation" className="px-2 pt-1 pb-0.5">+ <Typography.Text className="text-[11px] font-medium text-[var(--oh-text-dim)] uppercase tracking-wide leading-4">+ {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}+ </Typography.Text>+ </li>+ {profiles.map((profile) => {+ const isCurrent = profile.name === currentProfileName;+ return (+ <ContextMenuListItem+ key={profile.name}+ testId={`chat-input-llm-profile-option-${profile.name}`}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ if (isCurrent) {+ onClose();+ return;+ }+ handleSelect(profile.name);+ }}+ className={cn(+ "flex flex-col items-stretch gap-0.5",+ isCurrent && "bg-[var(--oh-interactive-hover)]",+ )}+ >+ <span className="flex items-center gap-2">+ <span+ className="flex-1 truncate text-sm leading-5"+ title={profile.model ?? profile.name}+ >+ {profile.name}+ </span>+ {isCurrent && (+ <CheckIcon+ width={14}+ height={14}+ className="shrink-0"+ aria-hidden+ />+ )}+ </span>+ {profile.model && (+ <span className="block truncate text-xs leading-4 text-[var(--oh-muted)]">+ {profile.model}+ </span>+ )}+ </ContextMenuListItem>+ );+ })}+ </>+ )}+ {profiles.length > 0 && <Divider inset={dividerInset} />}+ <li className="text-sm">+ <NavigationLink+ to="/settings/llm"+ onClick={onClose}+ className={cn(+ "flex h-[30px] items-center gap-2 rounded p-2 leading-5 text-[var(--oh-foreground)] hover:bg-[var(--oh-interactive-hover)] transition-colors",+ settingsLinkClassName,+ )}+ >+ <SettingsGearIcon+ width={16}+ height={16}+ className={cn("shrink-0", settingsIconClassName)}+ aria-hidden+ />+ <span>{t(I18nKey.SETTINGS$LLM_PROFILES)}</span>+ </NavigationLink>+ </li>+ </>+ );+}++export function ChatInputLlmProfilePicker() {+ const { t } = useTranslation("openhands");+ const { profiles, currentProfileName, isLoading, isSwitching } =+ useChatInputLlmProfileState();+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);+ const triggerRef = React.useRef<HTMLButtonElement>(null);+ const popoverRef = useClickOutsideElement<HTMLUListElement>(+ () => setIsPopoverOpen(false),+ triggerRef,+ );++ // No LLM profiles yet (or the agent-server lacks the surface): stay out of+ // the way, exactly like the ACP/AgentProfile pickers.+ if (isLoading || profiles.length === 0) {+ return null;+ }++ const label = currentProfileName ?? t(I18nKey.LLM$SELECT_MODEL_PLACEHOLDER);++ return (+ <div className="relative min-w-0">+ <button+ ref={triggerRef}+ type="button"+ className={cn(chatInputPillButtonClassName, "max-w-[200px]")}+ title={currentProfileName ?? undefined}+ data-testid="chat-input-llm-profile"+ aria-expanded={isPopoverOpen}+ aria-haspopup="dialog"+ // Disabled mid-switch so re-opening can't fire a second /switch_profile.+ disabled={isSwitching}+ aria-busy={isSwitching}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsPopoverOpen((open) => !open);+ }}+ >+ <span className="truncate">{truncateLabel(label)}</span>+ <ComboboxCaretInline isOpen={isPopoverOpen} />+ </button>++ {isPopoverOpen && (+ <ContextMenu+ ref={popoverRef}+ testId="chat-input-llm-profile-popover"+ position="top"+ alignment="left"+ spacing="none"+ className="z-[60] mb-2 min-w-[200px] max-w-[320px] max-h-[60vh] overflow-y-auto"+ >+ <ChatInputLlmProfileMenuContent+ onClose={() => setIsPopoverOpen(false)}+ />+ </ContextMenu>+ )}+ </div>+ );+}diff --git a/src/components/features/chat/components/chat-input-profile-picker.tsx b/src/components/features/chat/components/chat-input-profile-picker.tsxnew file mode 100644index 0000000000..24c86ec1a9--- /dev/null+++ b/src/components/features/chat/components/chat-input-profile-picker.tsx@@ -0,0 +1,181 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { useChatInputProfileState } from "#/hooks/use-chat-input-profile-state";+import { ComboboxCaretInline } from "#/ui/combobox-caret";+import SettingsGearIcon from "#/icons/settings-gear.svg?react";+import CheckIcon from "#/icons/checkmark.svg?react";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { NavigationLink } from "#/components/shared/navigation-link";+import { ContextMenu } from "#/ui/context-menu";+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";+import { Divider } from "#/ui/divider";+import { Typography } from "#/ui/typography";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";+import { chatInputPillButtonClassName } from "#/utils/form-control-classes";++const PROFILE_LABEL_MAX_CHARS = 18;++function truncateLabel(label: string): string {+ return label.length <= PROFILE_LABEL_MAX_CHARS+ ? label+ : `${label.slice(0, PROFILE_LABEL_MAX_CHARS)}…`;+}++interface ChatInputProfileMenuContentProps {+ onClose: () => void;+ dividerInset?: "menu";+ settingsLinkClassName?: string;+ settingsIconClassName?: string;+}++export function ChatInputProfileMenuContent({+ onClose,+ dividerInset,+ settingsLinkClassName,+ settingsIconClassName,+}: ChatInputProfileMenuContentProps) {+ const { t } = useTranslation("openhands");+ const { profiles, currentProfileId, selectProfile } =+ useChatInputProfileState();++ const handleSelect = (profile: (typeof profiles)[number]) => {+ selectProfile(profile);+ onClose();+ };++ return (+ <>+ {profiles.length > 0 && (+ <>+ {/* role="presentation" keeps this a valid <li> child of the+ ContextMenu <ul> without exposing the label as a menu item. */}+ <li role="presentation" className="px-2 pt-1 pb-0.5">+ <Typography.Text className="text-[11px] font-medium text-[var(--oh-text-dim)] uppercase tracking-wide leading-4">+ {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}+ </Typography.Text>+ </li>+ {profiles.map((profile) => {+ const isCurrent =+ profile.id != null && profile.id === currentProfileId;+ return (+ <ContextMenuListItem+ key={profile.id ?? profile.name}+ testId={`chat-input-agent-profile-option-${profile.name}`}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ if (isCurrent) {+ onClose();+ return;+ }+ handleSelect(profile);+ }}+ className={cn(+ "flex items-center gap-2",+ isCurrent && "bg-[var(--oh-interactive-hover)]",+ )}+ >+ <span+ className="flex-1 truncate text-sm leading-5"+ title={profile.name}+ >+ {profile.name}+ </span>+ {isCurrent && (+ <CheckIcon+ width={14}+ height={14}+ className="shrink-0"+ aria-hidden+ />+ )}+ </ContextMenuListItem>+ );+ })}+ </>+ )}+ {profiles.length > 0 && <Divider inset={dividerInset} />}+ <li className="text-sm">+ <NavigationLink+ to="/settings/agents"+ onClick={onClose}+ className={cn(+ "flex h-[30px] items-center gap-2 rounded p-2 leading-5 text-[var(--oh-foreground)] hover:bg-[var(--oh-interactive-hover)] transition-colors",+ settingsLinkClassName,+ )}+ >+ <SettingsGearIcon+ width={16}+ height={16}+ className={cn("shrink-0", settingsIconClassName)}+ aria-hidden+ />+ <span>{t(I18nKey.CHAT$MANAGE_AGENT_PROFILES)}</span>+ </NavigationLink>+ </li>+ </>+ );+}++export function ChatInputProfilePicker() {+ const { t } = useTranslation("openhands");+ const { profiles, currentProfileName, isLoading, isSwitching } =+ useChatInputProfileState();+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);+ const triggerRef = React.useRef<HTMLButtonElement>(null);+ const popoverRef = useClickOutsideElement<HTMLUListElement>(+ () => setIsPopoverOpen(false),+ triggerRef,+ );++ // Nothing to launch from yet (empty store before the backend seeds, or an+ // agent-server without the /api/agent-profiles surface): stay out of the way.+ if (isLoading || profiles.length === 0) {+ return null;+ }++ const label = currentProfileName ?? t(I18nKey.CHAT$AGENT_PROFILE_PLACEHOLDER);++ return (+ <div className="relative min-w-0">+ <button+ ref={triggerRef}+ type="button"+ className={cn(chatInputPillButtonClassName, "max-w-[200px]")}+ title={currentProfileName ?? undefined}+ data-testid="chat-input-agent-profile"+ aria-expanded={isPopoverOpen}+ aria-haspopup="dialog"+ // Disabled while a profile switch (new-conversation create / activate) is+ // in flight, so re-opening the menu can't fire a second create. The menu+ // closes on select, so this is the only double-submit path.+ disabled={isSwitching}+ aria-busy={isSwitching}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsPopoverOpen((open) => !open);+ }}+ >+ <span className="truncate">{truncateLabel(label)}</span>+ <ComboboxCaretInline isOpen={isPopoverOpen} />+ </button>++ {isPopoverOpen && (+ <ContextMenu+ ref={popoverRef}+ testId="chat-input-agent-profile-popover"+ position="top"+ alignment="left"+ spacing="none"+ className="z-[60] mb-2 min-w-[200px] max-w-[320px] max-h-[60vh] overflow-y-auto"+ >+ <ChatInputProfileMenuContent+ onClose={() => setIsPopoverOpen(false)}+ />+ </ContextMenu>+ )}+ </div>+ );+}diff --git a/src/components/features/chat/components/resolve-picker-kind.ts b/src/components/features/chat/components/resolve-picker-kind.tsnew file mode 100644index 0000000000..3fb75ab733--- /dev/null+++ b/src/components/features/chat/components/resolve-picker-kind.ts@@ -0,0 +1,42 @@+export type PickerKind = "model" | "agent-profile" | "llm-profile";++export interface ResolvePickerKindInput {+ /** A conversation is active (i.e. we're inside a conversation, not on home). */+ hasConversation: boolean;+ /** The active backend is cloud (vs. a local agent-server). */+ isCloud: boolean;+ /** The current context runs an ACP agent (active conv or home ACP settings). */+ isAcp: boolean;+ /** At least one AgentProfile exists to launch the next conversation from. */+ profilesAvailable: boolean;+}++/**+ * Decide which chat-input model/profile picker to show. Pure so the matrix is+ * unit-tested directly (see `resolve-picker-kind.test.ts`).+ *+ * - Home (local or cloud): the AgentProfile picker, which starts a new+ * conversation / activates the default (#3727, cloud via #15060). When no+ * profiles exist yet, fall back — cloud → model, local → LLM-profile (cloud+ * has no home LLM-profile activate path).+ * - In an ACP conversation (local or cloud): the model picker — ACP owns its+ * LLM via the subprocess/session, so the picker just live-switches the+ * session model (set_session_model / cloud's switch_acp_model proxy).+ * - In an OpenHands conversation (local or cloud): the LLM-profile picker,+ * which live-switches the running conversation's LLM profile via+ * /switch_profile — a real endpoint on both backends (cloud proxies+ * POST /api/v1/app-conversations/{id}/switch_profile, unchanged since+ * OpenHands#14288). There is no cloud-specific restriction here.+ */+export function resolvePickerKind({+ hasConversation,+ isCloud,+ isAcp,+ profilesAvailable,+}: ResolvePickerKindInput): PickerKind {+ if (!hasConversation) {+ if (profilesAvailable) return "agent-profile";+ return isCloud ? "model" : "llm-profile";+ }+ return isAcp ? "model" : "llm-profile";+}diff --git a/src/components/features/chat/switch-profile-button.tsx b/src/components/features/chat/switch-profile-button.tsxdeleted file mode 100644index 0301629635..0000000000--- a/src/components/features/chat/switch-profile-button.tsx+++ /dev/null@@ -1,121 +0,0 @@-import React from "react";-import { useTranslation } from "react-i18next";-import { I18nKey } from "#/i18n/declaration";-import { ComboboxCaretInline } from "#/ui/combobox-caret";-import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";-import { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";-import { useActiveConversation } from "#/hooks/query/use-active-conversation";-import { useSettings } from "#/hooks/query/use-settings";-import { useOptionalConversationId } from "#/hooks/use-conversation-id";-import { useModelStore } from "#/stores/model-store";-import { cn } from "#/utils/utils";-import { chatInputPillButtonClassName } from "#/utils/form-control-classes";-import { SwitchProfileContextMenu } from "./switch-profile-context-menu";--export function SwitchProfileButton() {- const { t } = useTranslation("openhands");- const [contextMenuOpen, setContextMenuOpen] = React.useState(false);- // Null on the home page; `useSwitchLlmProfileAndLog` is fine with that- // because /api/profiles/<name>/activate is a global endpoint.- const { conversationId } = useOptionalConversationId();- const { data } = useLlmProfiles();- const { data: conversation } = useActiveConversation();- const { data: settings } = useSettings();- const { switchAndLog, isPending } = useSwitchLlmProfileAndLog();- // Optimistic value written by recordSwitch on a successful switch — gives- // instant in-conversation feedback before the conversation refetch lands- // with the new `llm_model`.- const optimisticActiveProfile = useModelStore((s) =>- conversationId ? s.activeProfileByConversation[conversationId] : undefined,- );-- const profiles = data?.profiles ?? [];- const conversationModel = conversation?.llm_model ?? null;- // ACPAgent conversations route prompts to a CLI subprocess whose model is- // controlled by ``acp_model`` (set in Settings → Agent), not by the LLM- // profile picker. Surfacing the switcher here would let the user "change- // the model" while the running subprocess silently keeps its own — a- // confusing no-op. Hide the button even when ``llm_model`` carries an ACP- // display model for chips/headers.- //- // On the home screen ``conversation`` is undefined; fall back to- // ``settings.agent_settings.agent_kind`` so the picker also hides when- // ACP is the *default* the next-created conversation would inherit.- // Otherwise an ACP user lands on a home page with an LLM-switch- // control that contradicts the ACP nav gating everywhere else.- const isAcpActive =- conversation?.agent_kind === "acp" ||- (!conversation && settings?.agent_settings?.agent_kind === "acp");-- // Resolution priority for the active profile name:- // 1. Optimistic (just-clicked) — instant feedback before the refetch.- // 2. Profile stamped on the conversation at creation / last switch —- // exact identity, survives reload, and is unambiguous when several- // profiles share one underlying model (#1082). Validated against the- // live list so a since-deleted/renamed profile falls through.- // 3. Profile whose model matches the running llm_model — legacy fallback.- // 4. User-level active_profile — home page / before the conversation has- // sent any messages.- const stampedProfile = conversation?.active_profile ?? null;- const conversationProfile =- stampedProfile && profiles.some((p) => p.name === stampedProfile)- ? stampedProfile- : null;- const activeProfileName =- optimisticActiveProfile ??- conversationProfile ??- (conversationModel- ? (profiles.find((p) => p.model === conversationModel)?.name ?? null)- : (data?.active_profile ?? null));- const activeProfileModel =- profiles.find((p) => p.name === activeProfileName)?.model ??- conversationModel ??- null;-- if (profiles.length === 0 || isAcpActive) {- return null;- }-- const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {- event.preventDefault();- event.stopPropagation();- setContextMenuOpen((open) => !open);- };-- const handleSelect = (profileName: string) => {- if (profileName === activeProfileName) return;- switchAndLog(conversationId, profileName);- };-- return (- <div className="relative">- <button- type="button"- onClick={handleClick}- disabled={isPending}- data-testid="switch-profile-button"- title={activeProfileModel ?? undefined}- aria-haspopup="menu"- aria-expanded={contextMenuOpen}- className={cn(- chatInputPillButtonClassName,- "max-w-[200px]",- "disabled:opacity-50 disabled:cursor-not-allowed",- )}- >- <span className="truncate">- {activeProfileName ?? t(I18nKey.LLM$SELECT_MODEL_PLACEHOLDER)}- </span>- <ComboboxCaretInline isOpen={contextMenuOpen} />- </button>- {contextMenuOpen && (- <SwitchProfileContextMenu- profiles={profiles}- activeProfileName={activeProfileName}- onSelect={handleSelect}- onClose={() => setContextMenuOpen(false)}- />- )}- </div>- );-}diff --git a/src/components/features/chat/switch-profile-context-menu.tsx b/src/components/features/chat/switch-profile-context-menu.tsxdeleted file mode 100644index 46d6fd576d..0000000000--- a/src/components/features/chat/switch-profile-context-menu.tsx+++ /dev/null@@ -1,145 +0,0 @@-import React from "react";-import { useTranslation } from "react-i18next";-import { I18nKey } from "#/i18n/declaration";-import { ContextMenu } from "#/ui/context-menu";-import { Divider } from "#/ui/divider";-import { Typography } from "#/ui/typography";-import { NavigationLink } from "#/components/shared/navigation-link";-import { ContextMenuListItem } from "../context-menu/context-menu-list-item";-import { useClickOutsideElement } from "#/hooks/use-click-outside-element";-import CircuitIcon from "#/icons/u-circuit.svg?react";-import SettingsIcon from "#/icons/settings.svg?react";-import CheckIcon from "#/icons/checkmark.svg?react";-import { cn } from "#/utils/utils";-import type { ProfileInfo } from "#/api/profiles-service/profiles-service.api";-import {- dropdownMenuRowGapClassName,- dropdownMenuRowIconWrapperClassName,- switchProfileMenuListScrollClassName,-} from "#/utils/dropdown-classes";--const rowBaseClassName = cn(- "w-full flex flex-col gap-0.5 p-2 rounded",- "text-start hover:bg-[var(--oh-interactive-hover)] cursor-pointer text-nowrap",-);-const profileRowClassName = cn(rowBaseClassName, "h-auto items-stretch");-const linkRowClassName = cn(- "group w-full flex items-center p-2 rounded",- dropdownMenuRowGapClassName,- "text-start hover:bg-[var(--oh-interactive-hover)] cursor-pointer text-nowrap",-);--interface SwitchProfileContextMenuProps {- profiles: ProfileInfo[];- activeProfileName: string | null;- onSelect: (profileName: string) => void;- onClose: () => void;-}--export function SwitchProfileContextMenu({- profiles,- activeProfileName,- onSelect,- onClose,-}: SwitchProfileContextMenuProps) {- const { t } = useTranslation("openhands");- const ref = useClickOutsideElement<HTMLUListElement>(onClose);-- React.useEffect(() => {- const onKey = (e: KeyboardEvent) => {- if (e.key === "Escape") onClose();- };- document.addEventListener("keydown", onKey);- return () => document.removeEventListener("keydown", onKey);- }, [onClose]);-- const handleSelect = (- event: React.MouseEvent<HTMLButtonElement>,- name: string,- ) => {- event.preventDefault();- event.stopPropagation();- onSelect(name);- onClose();- };-- return (- <ContextMenu- ref={ref}- testId="switch-profile-context-menu"- position="top"- alignment="left"- className="z-[60] left-0 mb-2 bottom-full min-w-[280px] pt-0"- >- <div className="px-2 pb-0.5">- <Typography.Text className="text-[11px] font-medium text-[var(--oh-text-dim)] uppercase tracking-wide leading-4">- {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}- </Typography.Text>- </div>- <div- data-testid="switch-profile-options-list"- className={switchProfileMenuListScrollClassName}- >- {profiles.map((profile) => {- const isActive = profile.name === activeProfileName;- return (- <ContextMenuListItem- key={profile.name}- testId={`switch-profile-option-${profile.name}`}- onClick={(event) => handleSelect(event, profile.name)}- className={cn(- profileRowClassName,- isActive && "bg-[var(--oh-interactive-hover)]",- )}- >- <span- className={cn(- "flex items-center min-w-0",- dropdownMenuRowGapClassName,- )}- title={profile.model ?? undefined}- >- <span- className={dropdownMenuRowIconWrapperClassName}- aria-hidden- >- <CircuitIcon width={16} height={16} />- </span>- <span className="flex-1 truncate text-sm leading-5">- {profile.name}- </span>- {isActive && (- <CheckIcon- width={14}- height={14}- className="shrink-0"- aria-hidden- />- )}- </span>- {profile.model && (- <span className="block truncate text-xs leading-4 text-[var(--oh-muted)] pl-6">- {profile.model}- </span>- )}- </ContextMenuListItem>- );- })}- </div>- <Divider />- <NavigationLink- to="/settings"- onClick={onClose}- data-testid="switch-profile-open-settings"- className={linkRowClassName}- >- <span className={dropdownMenuRowIconWrapperClassName} aria-hidden>- <SettingsIcon width={16} height={16} />- </span>- <span className="text-sm leading-5">- {t(I18nKey.MODEL$OPEN_SETTINGS)}- </span>- </NavigationLink>- </ContextMenu>- );-}diff --git a/src/components/features/command-menu/command-menu-items.tsx b/src/components/features/command-menu/command-menu-items.tsxindex a68a23b131..52dcf49969 100644--- a/src/components/features/command-menu/command-menu-items.tsx+++ b/src/components/features/command-menu/command-menu-items.tsx@@ -23,7 +23,7 @@ export const COMMAND_MENU_ROUTE = {automations: "/automations",mcp: "/mcp",settings: "/settings",- agentSettings: "/settings/agent",+ agentSettings: "/settings/agents",llmSettings: "/settings/llm",condenserSettings: "/settings/condenser",verificationSettings: "/settings/verification",diff --git a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsxindex 0b77477b64..fdbef5cda7 100644--- a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx+++ b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx@@ -8,7 +8,11 @@ import { I18nKey } from "#/i18n/declaration";import { useAcpAuthStatus } from "#/hooks/query/use-acp-auth-status";import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";import { useActiveBackend } from "#/contexts/active-backend-context";-import { getAcpProviderDisplayName } from "#/constants/acp-providers";+import {+ getAcpProviderDisplayName,+ getAcpPreferredDefaultModel,+} from "#/constants/acp-providers";+import { useApplyOnboardingAgentProfile } from "#/hooks/mutation/use-apply-onboarding-agent-profile";import { type OnboardingAgentId } from "./choose-agent-step";interface SetupAcpSecretsStepProps {@@ -78,6 +82,7 @@ export function SetupAcpSecretsStep({isSaving,} = useAcpCredentialForm(providerKey);+ const applyAgentProfile = useApplyOnboardingAgentProfile();const providerName = getAcpProviderDisplayName(providerKey) ?? providerKey;const isAuthenticated = authStatus === "authenticated";@@ -112,6 +117,18 @@ export function SetupAcpSecretsStep({const handleNext = async () => {if (await save()) {+ // Land the user's ACP choice on the active AGENT profile so the next+ // conversation launches that provider (no LLM profile/key needed — the+ // subprocess owns its LLM). Best-effort; never blocks advancing. This+ // step never renders for "openhands" (the modal shows SetupLlmStep+ // there), so the guard just narrows the type for `acp_server`.+ if (providerKey !== "openhands") {+ await applyAgentProfile({+ agent_kind: "acp",+ acp_server: providerKey,+ acp_model: getAcpPreferredDefaultModel(providerKey) ?? undefined,+ });+ }onNext();}};diff --git a/src/components/features/onboarding/steps/setup-llm-step.tsx b/src/components/features/onboarding/steps/setup-llm-step.tsxindex 52b2778087..86d2e02ca5 100644--- a/src/components/features/onboarding/steps/setup-llm-step.tsx+++ b/src/components/features/onboarding/steps/setup-llm-step.tsx@@ -7,6 +7,7 @@ import type { SdkSectionSaveControl } from "#/components/features/settings/sdk-simport { useActiveBackend } from "#/contexts/active-backend-context";import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";+import { useApplyOnboardingAgentProfile } from "#/hooks/mutation/use-apply-onboarding-agent-profile";import { deriveProfileNameFromModel } from "#/utils/derive-profile-name";interface SetupLlmStepProps {@@ -46,6 +47,7 @@ export function SetupLlmStep({ onBack, onNext }: SetupLlmStepProps) {const isLocalBackend = backend.kind === "local";const saveProfile = useSaveLlmProfile();const activateProfile = useActivateLlmProfile();+ const applyAgentProfile = useApplyOnboardingAgentProfile();const [saveControl, setSaveControl] =React.useState<SdkSectionSaveControl | null>(null);const [isFinalizing, setIsFinalizing] = React.useState(false);@@ -53,12 +55,17 @@ export function SetupLlmStep({ onBack, onNext }: SetupLlmStepProps) {// On local backends the LLM profiles list is the user-facing source of// truth; without this step the form save only updates agent_settings and// the new config never shows up in the profiles list ("ghost profile").- const persistAsProfile = React.useCallback(async () => {- if (!isLocalBackend || !saveControl) return;+ // Returns the saved LLM profile name so the caller can point the active+ // AGENT profile at it (conversations launch from the agent profile, not the+ // active LLM profile).+ const persistAsProfile = React.useCallback(async (): Promise<+ string | null+ > => {+ if (!isLocalBackend || !saveControl) return null;const values = saveControl.values;const model =typeof values["llm.model"] === "string" ? values["llm.model"] : "";- if (!model) return;+ if (!model) return null;const apiKey =typeof values["llm.api_key"] === "string" ? values["llm.api_key"] : "";const baseUrl =@@ -77,22 +84,42 @@ export function SetupLlmStep({ onBack, onNext }: SetupLlmStepProps) {request: { llm: llmConfig, include_secrets: true },});await activateProfile.mutateAsync(name);+ return name;} catch (error) {// Best-effort: the agent_settings save already succeeded, so the// user is not blocked from completing onboarding.console.error("Failed to persist onboarding LLM as profile:", error);+ return null;}}, [isLocalBackend, saveControl, saveProfile, activateProfile]);const handleSaveSuccess = React.useCallback(async () => {setIsFinalizing(true);try {- await persistAsProfile();+ const llmProfileName = await persistAsProfile();+ // Point the active AGENT profile at the LLM the user just configured so+ // the next conversation actually uses it (and the "LLM not set up"+ // banner clears). Without this the active agent profile keeps its+ // seeded llm_profile_ref, which has no key.+ //+ // Cloud intentionally skips this: `persistAsProfile` only creates/activates+ // a *local* LLM profile (it early-returns null off local backends), and on+ // cloud the agent-profile ↔ LLM wiring is resolved server-side from the+ // settings this step's form save already persisted — there is no+ // client-writable cloud agent-profile ref to repoint here. The ACP step+ // still calls applyAgentProfile because ACP agents carry no LLM ref and+ // persist their kind/model locally regardless of backend.+ if (llmProfileName) {+ await applyAgentProfile({+ agent_kind: "openhands",+ llm_profile_ref: llmProfileName,+ });+ }} finally {setIsFinalizing(false);onNext();}- }, [persistAsProfile, onNext]);+ }, [persistAsProfile, applyAgentProfile, onNext]);const handleNext = () => {if (saveControl?.isDirty) {diff --git a/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx b/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsxnew file mode 100644index 0000000000..5dd2f09889--- /dev/null+++ b/src/components/features/settings/agent-profiles/agent-profile-actions-menu.tsx@@ -0,0 +1,179 @@+import {+ useEffect,+ useLayoutEffect,+ useRef,+ useCallback,+ useState,+} from "react";+import ReactDOM from "react-dom";+import { useTranslation } from "react-i18next";+import { cn } from "#/utils/utils";+import { dropdownMenuListClassName } from "#/utils/dropdown-classes";+import { I18nKey } from "#/i18n/declaration";+import EditIcon from "#/icons/u-edit.svg?react";+import CheckCircleIcon from "#/icons/u-check-circle.svg?react";+import DeleteIcon from "#/icons/u-delete.svg?react";+import { MenuItem } from "#/components/features/settings/llm-profiles/profile-actions-menu-item";++interface AgentProfileActionsMenuProps {+ onEdit: () => void;+ onSetActive: () => void;+ onDelete: () => void;+ isActive: boolean;+ isActivating: boolean;+ onClose: () => void;+ /**+ * Element the menu anchors against. When provided, the menu renders into a+ * body portal with fixed positioning so it isn't clipped by scroll+ * containers (matches the LLM-profiles menu behavior).+ */+ anchorRef?: React.RefObject<HTMLElement | null>;+}++export function AgentProfileActionsMenu({+ onEdit,+ onSetActive,+ onDelete,+ isActive,+ isActivating,+ onClose,+ anchorRef,+}: AgentProfileActionsMenuProps) {+ const { t } = useTranslation("openhands");+ const menuRef = useRef<HTMLDivElement>(null);+ const menuItemsRef = useRef<(HTMLButtonElement | null)[]>([]);++ const anchorElement = anchorRef?.current ?? null;+ const [portalStyle, setPortalStyle] = useState<React.CSSProperties>();++ useLayoutEffect(() => {+ if (!anchorElement) return undefined;++ const updatePosition = () => {+ const rect = anchorElement.getBoundingClientRect();+ if (!rect) return;+ const gap = 8;+ setPortalStyle({+ position: "fixed",+ zIndex: 9999,+ top: rect.bottom + gap,+ right: window.innerWidth - rect.right,+ width: "max-content",+ });+ };++ updatePosition();+ window.addEventListener("resize", updatePosition);+ window.addEventListener("scroll", updatePosition, true);+ return () => {+ window.removeEventListener("resize", updatePosition);+ window.removeEventListener("scroll", updatePosition, true);+ };+ }, [anchorElement]);++ useEffect(() => {+ menuItemsRef.current[0]?.focus();+ }, []);++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ const target = event.target as Node;+ if (menuRef.current && !menuRef.current.contains(target)) {+ onClose();+ }+ };+ const handleEscape = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ document.addEventListener("mousedown", handleClickOutside);+ document.addEventListener("keydown", handleEscape);+ return () => {+ document.removeEventListener("mousedown", handleClickOutside);+ document.removeEventListener("keydown", handleEscape);+ };+ }, [onClose]);++ const handleAction = (action: () => void) => {+ action();+ onClose();+ };++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent, currentIndex: number) => {+ if (e.key === "Tab") {+ onClose();+ return;+ }+ const itemCount = menuItemsRef.current.filter(Boolean).length;+ if (e.key === "ArrowDown") {+ e.preventDefault();+ const nextIndex = (currentIndex + 1) % itemCount;+ menuItemsRef.current[nextIndex]?.focus();+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ const prevIndex = (currentIndex - 1 + itemCount) % itemCount;+ menuItemsRef.current[prevIndex]?.focus();+ }+ },+ [onClose],+ );++ const setActiveDisabled = isActive || isActivating;+ const isPortaled = Boolean(anchorElement);++ const menu = (+ <div+ ref={menuRef}+ className={cn(+ "absolute right-0 top-full z-10 mt-2 w-[160px] rounded-md border border-[var(--oh-border-subtle)] bg-tertiary px-1 py-1 shadow-lg",+ dropdownMenuListClassName,+ isPortaled &&+ "!static !top-auto !bottom-auto !left-auto !right-auto !mt-0",+ )}+ role="menu"+ aria-orientation="vertical"+ data-testid="agent-profile-actions-menu"+ >+ <MenuItem+ index={0}+ icon={<EditIcon width={16} height={16} />}+ label={t(I18nKey.SETTINGS$PROFILE_EDIT)}+ onClick={() => handleAction(onEdit)}+ onKeyDown={handleKeyDown}+ menuItemsRef={menuItemsRef}+ testId="agent-profile-edit"+ />+ <MenuItem+ index={1}+ icon={<CheckCircleIcon width={16} height={16} />}+ label={t(I18nKey.SETTINGS$PROFILE_SET_ACTIVE)}+ onClick={() => handleAction(onSetActive)}+ onKeyDown={handleKeyDown}+ menuItemsRef={menuItemsRef}+ disabled={setActiveDisabled}+ testId="agent-profile-set-active"+ />+ <MenuItem+ index={2}+ icon={<DeleteIcon width={16} height={16} />}+ label={t(I18nKey.BUTTON$DELETE)}+ onClick={() => handleAction(onDelete)}+ onKeyDown={handleKeyDown}+ menuItemsRef={menuItemsRef}+ testId="agent-profile-delete"+ />+ </div>+ );++ if (isPortaled) {+ if (typeof document === "undefined" || !portalStyle) {+ return null;+ }+ return ReactDOM.createPortal(+ <div style={portalStyle}>{menu}</div>,+ document.body,+ );+ }++ return menu;+}diff --git a/src/components/features/settings/agent-profiles/agent-profile-row.tsx b/src/components/features/settings/agent-profiles/agent-profile-row.tsxnew file mode 100644index 0000000000..f0fc15388a--- /dev/null+++ b/src/components/features/settings/agent-profiles/agent-profile-row.tsx@@ -0,0 +1,97 @@+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { AgentProfileActionsMenu } from "./agent-profile-actions-menu";+import { type AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { I18nKey } from "#/i18n/declaration";+import { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";+import { BrandBadge } from "#/components/shared/badge";+import { cn } from "#/utils/utils";+import {+ settingsListIconActionButtonClassName,+ settingsListRowClassName,+} from "#/utils/settings-list-classes";++interface AgentProfileRowProps {+ profile: AgentProfileSummary;+ isActive: boolean;+ /** When false, the row is read-only and the actions menu is hidden. */+ canManage: boolean;+ onActivate: (profile: AgentProfileSummary) => void;+ onEdit: (profile: AgentProfileSummary) => void;+ onDelete: (profile: AgentProfileSummary) => void;+ isActivating: boolean;+}++export function AgentProfileRow({+ profile,+ isActive,+ canManage,+ onActivate,+ onEdit,+ onDelete,+ isActivating,+}: AgentProfileRowProps) {+ const { t } = useTranslation("openhands");+ const [menuOpen, setMenuOpen] = useState(false);+ const triggerRef = useRef<HTMLButtonElement>(null);++ // Secondary label: the referenced LLM profile (OpenHands) or the "ACP" kind.+ const secondary =+ profile.agent_kind === "openhands"+ ? profile.llm_profile_ref+ : t(I18nKey.SETTINGS$AGENT_TYPE_ACP);++ return (+ <div+ data-testid="agent-profile-row"+ className={cn(settingsListRowClassName, "justify-between gap-3")}+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <span+ className="min-w-0 max-w-full truncate text-sm font-medium text-white"+ title={profile.name}+ >+ {profile.name}+ </span>+ {secondary ? (+ <span+ className="min-w-0 max-w-full truncate text-sm text-[var(--oh-muted)]"+ title={secondary}+ >+ {secondary}+ </span>+ ) : null}+ {isActive && (+ <BrandBadge+ className="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs"+ data-testid="agent-profile-active-badge"+ >+ {t(I18nKey.SETTINGS$PROFILE_ACTIVE)}+ </BrandBadge>+ )}+ </div>+ {canManage && (+ <div className="relative shrink-0">+ <EllipsisButton+ ref={triggerRef}+ onClick={() => setMenuOpen((open) => !open)}+ ariaLabel={t(I18nKey.SETTINGS$PROFILE_MENU)}+ testId="agent-profile-menu-trigger"+ className={settingsListIconActionButtonClassName}+ />+ {menuOpen && (+ <AgentProfileActionsMenu+ anchorRef={triggerRef}+ onEdit={() => onEdit(profile)}+ onSetActive={() => onActivate(profile)}+ onDelete={() => onDelete(profile)}+ isActive={isActive}+ isActivating={isActivating}+ onClose={() => setMenuOpen(false)}+ />+ )}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/features/settings/agent-profiles/agent-profiles-body.tsx b/src/components/features/settings/agent-profiles/agent-profiles-body.tsxnew file mode 100644index 0000000000..146936a6bd--- /dev/null+++ b/src/components/features/settings/agent-profiles/agent-profiles-body.tsx@@ -0,0 +1,94 @@+import { useTranslation } from "react-i18next";+import { LoadingSpinner } from "#/components/shared/loading-spinner";+import { AgentProfileRow } from "./agent-profile-row";+import { type AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { I18nKey } from "#/i18n/declaration";+import { cn } from "#/utils/utils";+import {+ settingsListContainerClassName,+ settingsListDividerClassName,+} from "#/utils/settings-list-classes";+import { extensionModuleEmptyStateClassName } from "#/utils/extension-module-card-classes";++interface AgentProfilesBodyProps {+ isLoading: boolean;+ loadError: Error | null;+ profiles: AgentProfileSummary[];+ activeId: string | null;+ /** When false, rows are read-only and the actions menu is hidden. */+ canManage: boolean;+ onActivate: (profile: AgentProfileSummary) => void;+ onEdit: (profile: AgentProfileSummary) => void;+ onDelete: (profile: AgentProfileSummary) => void;+ isActivating: boolean;+}++export function AgentProfilesBody({+ isLoading,+ loadError,+ profiles,+ activeId,+ canManage,+ onActivate,+ onEdit,+ onDelete,+ isActivating,+}: AgentProfilesBodyProps) {+ const { t } = useTranslation("openhands");++ if (isLoading) {+ return (+ <div className="flex justify-center p-4">+ <LoadingSpinner size="large" />+ </div>+ );+ }++ if (loadError) {+ return (+ <div+ data-testid="agent-profiles-load-error"+ className={extensionModuleEmptyStateClassName}+ >+ <p className="text-sm text-red-400">+ {t(I18nKey.SETTINGS$PROFILES_LOAD_ERROR)}+ </p>+ </div>+ );+ }++ if (profiles.length === 0) {+ return (+ <div+ data-testid="agent-profiles-empty"+ className={extensionModuleEmptyStateClassName}+ >+ <p className="text-sm text-[var(--oh-muted)]">+ {t(I18nKey.SETTINGS$PROFILES_EMPTY)}+ </p>+ </div>+ );+ }++ return (+ <div+ className={cn(+ settingsListContainerClassName,+ settingsListDividerClassName,+ )}+ >+ {profiles.map((profile) => (+ <AgentProfileRow+ key={profile.name}+ profile={profile}+ isActive={!!profile.id && profile.id === activeId}+ canManage={canManage}+ onActivate={onActivate}+ onEdit={onEdit}+ onDelete={onDelete}+ isActivating={isActivating}+ />+ ))}+ </div>+ );+}diff --git a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsxnew file mode 100644index 0000000000..f8b4738ce9--- /dev/null+++ b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx@@ -0,0 +1,356 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { AgentProfilesManager } from "./agent-profiles-manager";+import { mergeAgentProfileSaveInput } from "./merge-agent-profile-save-input";+import { ProfileNameInput } from "#/components/features/settings/llm-profiles/profile-name-input";+import { BrandButton } from "#/components/features/settings/brand-button";+import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";+import {+ AgentSettingsScreen,+ type AgentSettingsSaveControl,+} from "#/routes/agent-settings";+import AgentProfilesService, {+ type AgentProfile,+ type AgentProfileSummary,+ type AgentProfileSaveInput,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useSaveAgentProfile } from "#/hooks/mutation/use-save-agent-profile";+import { useRenameAgentProfile } from "#/hooks/mutation/use-rename-agent-profile";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";+import { I18nKey } from "#/i18n/declaration";+import { isProfileNameValid } from "#/utils/derive-profile-name";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { SettingsValue } from "#/types/settings";+import { BackNavButton } from "#/components/shared/buttons/back-nav-button";+import { Typography } from "#/ui/typography";+import { useSettingsSectionHeader } from "#/contexts/settings-section-header-context";+import { parseCommand } from "#/utils/acp-command";++type ViewMode = "list" | "create" | "edit";++/**+ * Build the `agent_settings`-shaped seed the embedded {@link AgentSettingsScreen}+ * consumes for an existing profile. The stored ACP command is a shell string;+ * the form's init logic expects a token array, so split it here.+ */+function toAgentSettingsOverride(+ profile: AgentProfile,+): Record<string, SettingsValue> {+ if (profile.agent_kind === "acp") {+ return {+ agent_kind: "acp",+ acp_server: profile.acp_server,+ acp_command: profile.acp_command ? parseCommand(profile.acp_command) : [],+ acp_args: profile.acp_args ?? [],+ acp_model: profile.acp_model ?? "",+ };+ }+ return {+ agent_kind: "openhands",+ enable_sub_agents: profile.enable_sub_agents,+ tool_concurrency_limit: profile.tool_concurrency_limit,+ };+}++/**+ * AgentProfilesLocalView mirrors {@link LlmSettingsLocalView}: a list of the+ * user's Agent profiles, with a create/edit view that reuses the existing Agent+ * settings form (embedded) plus a profile name and — for OpenHands profiles —+ * an LLM-profile picker. Available on local backends only.+ */+export function AgentProfilesLocalView() {+ const { t } = useTranslation("openhands");+ const { setHideSectionHeader } = useSettingsSectionHeader();+ const saveProfile = useSaveAgentProfile();+ const renameProfile = useRenameAgentProfile();+ const { data: profilesData } = useAgentProfiles();+ const { data: llmProfilesData, isLoading: isLlmProfilesLoading } =+ useLlmProfiles();++ const [viewMode, setViewMode] = useState<ViewMode>("list");+ const [profileName, setProfileName] = useState("");+ const [editingProfile, setEditingProfile] = useState<AgentProfile | null>(+ null,+ );+ const [override, setOverride] = useState<Record<+ string,+ SettingsValue+ > | null>(null);+ const [llmProfileRef, setLlmProfileRef] = useState("");+ const [saveControl, setSaveControl] =+ useState<AgentSettingsSaveControl | null>(null);+ const [isSaving, setIsSaving] = useState(false);++ useEffect(() => {+ setHideSectionHeader(viewMode !== "list");+ return () => setHideSectionHeader(false);+ }, [viewMode, setHideSectionHeader]);++ const llmProfiles = llmProfilesData?.profiles ?? [];+ const defaultLlmProfileRef =+ llmProfilesData?.active_profile ?? llmProfiles[0]?.name ?? "";++ const existingNames = useMemo(+ () => new Set(profilesData?.profiles.map((p) => p.name) ?? []),+ [profilesData],+ );++ // The shared validator rejects whitespace, so duplicate checks compare raw.+ const isNameValid = useMemo(() => {+ if (!isProfileNameValid(profileName, { isRequired: true })) return false;+ if (viewMode === "create" && existingNames.has(profileName)) return false;+ if (+ viewMode === "edit" &&+ profileName !== editingProfile?.name &&+ existingNames.has(profileName)+ ) {+ return false;+ }+ return true;+ }, [profileName, viewMode, existingNames, editingProfile?.name]);++ const handleAddProfile = useCallback(() => {+ setProfileName("");+ setEditingProfile(null);+ setOverride({ agent_kind: "openhands" });+ setLlmProfileRef(defaultLlmProfileRef);+ setSaveControl(null);+ setViewMode("create");+ }, [defaultLlmProfileRef]);++ const handleEditProfile = useCallback(+ async (summary: AgentProfileSummary) => {+ try {+ // Fetch with encrypted secret exposure so any `skills[].mcp_tools`+ // values arrive as Fernet tokens rather than masks — the save below+ // round-trips the stored profile, and posting back a mask would+ // persist it literally (the local save only decrypts tokens).+ const detail = await AgentProfilesService.getProfile(+ summary.name,+ "encrypted",+ );+ const profile = detail.profile;+ setEditingProfile(profile);+ setOverride(toAgentSettingsOverride(profile));+ if (profile.agent_kind === "openhands") {+ // A profile can reference an LLM profile that's since been deleted+ // (or renamed): the dropdown would render nothing selected while+ // `llmProfileRef` still holds the stale name and saves it straight+ // back. Validate against the live list and fall back to the default+ // so a dangling ref self-heals on load (#1571 review). Skip the+ // check while the list is still loading rather than treating an+ // unloaded cache as "not found".+ const refIsLive =+ isLlmProfilesLoading ||+ llmProfiles.some((p) => p.name === profile.llm_profile_ref);+ setLlmProfileRef(+ refIsLive ? profile.llm_profile_ref : defaultLlmProfileRef,+ );+ } else {+ setLlmProfileRef("");+ }+ setProfileName(profile.name);+ setSaveControl(null);+ setViewMode("edit");+ } catch (error) {+ console.error("Failed to fetch agent profile:", error);+ displayErrorToast(t(I18nKey.ERROR$GENERIC));+ }+ },+ [t, llmProfiles, isLlmProfilesLoading, defaultLlmProfileRef],+ );++ const handleBackToList = useCallback(() => {+ setViewMode("list");+ setEditingProfile(null);+ setProfileName("");+ setOverride(null);+ setSaveControl(null);+ }, []);++ const handleSave = useCallback(async () => {+ if (!saveControl || !isNameValid) return;++ // Build the variant-specific fields from the embedded form (may throw on+ // invalid input, e.g. a bad concurrency value).+ let input: AgentProfileSaveInput;+ try {+ const fields = saveControl.buildAgentProfileFields();+ if (fields.agent_kind === "openhands") {+ if (!llmProfileRef) {+ displayErrorToast(t(I18nKey.SETTINGS$AGENT_PROFILE_LLM_REQUIRED));+ return;+ }+ input = { ...fields, llm_profile_ref: llmProfileRef };+ } else {+ input = fields as AgentProfileSaveInput;+ }+ } catch (error) {+ displayErrorToast(+ error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC),+ );+ return;+ }++ const trimmedName = profileName.trim();+ const originalName = editingProfile?.name;+ const isRename =+ viewMode === "edit" && originalName && originalName !== trimmedName;++ setIsSaving(true);+ try {+ // Persist ACP credentials (global secrets) before the profile spec.+ if (saveControl.credentials.isDirty) {+ const ok = await saveControl.credentials.save({ silent: true });+ if (!ok) return;+ saveControl.credentials.reset();+ }++ // Rename first (preserves the profile's stable id / active pointer);+ // saving to a new name would otherwise mint a fresh profile.+ if (isRename) {+ await renameProfile.mutateAsync({+ name: originalName,+ newName: trimmedName,+ });+ }++ // Save is a whole-profile overwrite: spread the stored profile under+ // the edited fields so the fields this editor doesn't model survive an+ // edit (kind-aware — a kind switch stays a clean variant replacement).+ const profile = mergeAgentProfileSaveInput(+ viewMode === "edit" ? editingProfile : null,+ input,+ );+ await saveProfile.mutateAsync({ name: trimmedName, profile });++ displaySuccessToast(+ viewMode === "create"+ ? t(I18nKey.SETTINGS$PROFILE_CREATED, { name: trimmedName })+ : t(I18nKey.SETTINGS$PROFILE_UPDATED, { name: trimmedName }),+ );+ handleBackToList();+ } catch (error) {+ const message = retrieveAxiosErrorMessage(error as never);+ displayErrorToast(message || t(I18nKey.ERROR$GENERIC));+ } finally {+ setIsSaving(false);+ }+ }, [+ saveControl,+ isNameValid,+ llmProfileRef,+ profileName,+ viewMode,+ editingProfile,+ saveProfile,+ renameProfile,+ t,+ handleBackToList,+ ]);++ if (viewMode === "list") {+ return (+ <AgentProfilesManager+ onAddProfile={handleAddProfile}+ onEditProfile={handleEditProfile}+ />+ );+ }++ const editorTitle =+ viewMode === "edit"+ ? t(I18nKey.SETTINGS$EDIT_AGENT_PROFILE)+ : t(I18nKey.SETTINGS$ADD_AGENT_PROFILE);+ const editorDescription =+ viewMode === "edit" && editingProfile+ ? t(I18nKey.SETTINGS$PROFILE_LOADED, { name: editingProfile.name })+ : t(I18nKey.SETTINGS$PROFILE_SAVE_HINT);+ const isOpenHands = saveControl?.agentType !== "acp";++ return (+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-2">+ <BackNavButton+ testId="back-to-agent-profiles"+ onClick={handleBackToList}+ >+ {t(I18nKey.BUTTON$BACK)}+ </BackNavButton>+ <Typography.H2 testId="agent-profile-editor-title">+ {editorTitle}+ </Typography.H2>+ <p+ data-testid="agent-profile-editor-description"+ className="text-sm leading-5 text-tertiary-light"+ >+ {editorDescription}+ </p>+ </div>++ <ProfileNameInput+ testId="agent-profile-name-input"+ value={profileName}+ onChange={setProfileName}+ isRequired+ />++ {/* Reuse the existing Agent settings form to define the agent. */}+ <AgentSettingsScreen+ key={viewMode === "edit" ? `edit-${editingProfile?.id}` : "new-profile"}+ embedded+ agentSettingsOverride={override}+ onSaveControlChange={setSaveControl}+ />++ {/* OpenHands profiles reference an LLM profile (required). */}+ {isOpenHands &&+ (llmProfiles.length > 0 ? (+ <SettingsDropdownInput+ testId="agent-profile-llm-selector"+ name="agent-profile-llm"+ label={t(I18nKey.SETTINGS$AGENT_PROFILE_LLM_LABEL)}+ items={llmProfiles.map((p) => ({+ key: p.name,+ label: p.model ? `${p.name} (${p.model})` : p.name,+ }))}+ selectedKey={llmProfileRef}+ onSelectionChange={(key) => key && setLlmProfileRef(String(key))}+ />+ ) : (+ <p+ data-testid="agent-profile-no-llm"+ className="text-sm text-red-400"+ >+ {t(I18nKey.SETTINGS$AGENT_PROFILE_NO_LLM)}+ </p>+ ))}++ <div className="flex justify-start gap-3 pt-4">+ <BrandButton+ testId="cancel-agent-profile-btn"+ type="button"+ variant="secondary"+ onClick={handleBackToList}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="save-agent-profile-btn"+ type="button"+ variant="primary"+ onClick={handleSave}+ isDisabled={!isNameValid || isSaving || !saveControl?.isValid}+ aria-busy={isSaving}+ >+ {isSaving ? t(I18nKey.SETTINGS$SAVING) : t(I18nKey.BUTTON$SAVE)}+ </BrandButton>+ </div>+ </div>+ );+}diff --git a/src/components/features/settings/agent-profiles/agent-profiles-manager.tsx b/src/components/features/settings/agent-profiles/agent-profiles-manager.tsxnew file mode 100644index 0000000000..70d211c285--- /dev/null+++ b/src/components/features/settings/agent-profiles/agent-profiles-manager.tsx@@ -0,0 +1,87 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { AgentProfilesBody } from "./agent-profiles-body";+import { DeleteAgentProfileModal } from "./delete-agent-profile-modal";+import { type AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";+import { useActivateAgentProfile } from "#/hooks/mutation/use-activate-agent-profile";+import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";+import { displaySuccessToast } from "#/utils/custom-toast-handlers";+import { I18nKey } from "#/i18n/declaration";++interface AgentProfilesManagerProps {+ onAddProfile?: () => void;+ onEditProfile?: (profile: AgentProfileSummary) => void;+}++export function AgentProfilesManager({+ onAddProfile,+ onEditProfile,+}: AgentProfilesManagerProps) {+ const { t } = useTranslation("openhands");+ const { data, isLoading, error } = useAgentProfiles();+ const activateProfile = useActivateAgentProfile();+ // Cloud members are view-only; only owners/admins (and all local users) may+ // add, edit, delete, or activate agent profiles (org-scoped, same permission+ // as LLM profiles). Mirrors LlmProfilesManager.+ const canManage = useCanManageOrgProfiles();+ const [profileToDelete, setProfileToDelete] =+ useState<AgentProfileSummary | null>(null);++ const profiles = data?.profiles ?? [];+ const activeId = data?.active_agent_profile_id ?? null;++ const handleActivate = async (profile: AgentProfileSummary) => {+ if (!profile.id) return;+ try {+ await activateProfile.mutateAsync(profile.id);+ displaySuccessToast(+ t(I18nKey.SETTINGS$PROFILE_ACTIVATED, { name: profile.name }),+ );+ } catch (error) {+ // The global mutation error toast reports the failure; just log here.+ console.error("Failed to activate agent profile:", error);+ }+ };++ return (+ <>+ <div className="flex flex-col gap-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h2 className="text-base font-medium text-white">+ {t(I18nKey.SETTINGS$AVAILABLE_PROFILES)}+ </h2>+ {onAddProfile && canManage ? (+ <BrandButton+ testId="add-agent-profile"+ type="button"+ variant="secondary"+ className="ml-auto"+ onClick={onAddProfile}+ >+ {t(I18nKey.SETTINGS$ADD_AGENT_PROFILE)}+ </BrandButton>+ ) : null}+ </div>++ <AgentProfilesBody+ isLoading={isLoading}+ loadError={error ?? null}+ profiles={profiles}+ activeId={activeId}+ canManage={canManage}+ onActivate={handleActivate}+ onEdit={(profile) => onEditProfile?.(profile)}+ onDelete={setProfileToDelete}+ isActivating={activateProfile.isPending}+ />+ </div>++ <DeleteAgentProfileModal+ profile={profileToDelete}+ onClose={() => setProfileToDelete(null)}+ />+ </>+ );+}diff --git a/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx b/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsxnew file mode 100644index 0000000000..92e8327f3e--- /dev/null+++ b/src/components/features/settings/agent-profiles/delete-agent-profile-modal.tsx@@ -0,0 +1,95 @@+import { useRef } from "react";+import { useTranslation } from "react-i18next";+import { BrandButton } from "#/components/features/settings/brand-button";+import { LoadingSpinner } from "#/components/shared/loading-spinner";+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";+import { type AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useDeleteAgentProfile } from "#/hooks/mutation/use-delete-agent-profile";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";+import { I18nKey } from "#/i18n/declaration";++interface DeleteAgentProfileModalProps {+ profile: AgentProfileSummary | null;+ onClose: () => void;+}++export function DeleteAgentProfileModal({+ profile,+ onClose,+}: DeleteAgentProfileModalProps) {+ const { t } = useTranslation("openhands");+ const deleteProfile = useDeleteAgentProfile();+ const cancelButtonRef = useRef<HTMLButtonElement>(null);++ if (!profile) return null;++ const handleDelete = async () => {+ try {+ await deleteProfile.mutateAsync(profile.name);+ displaySuccessToast(+ t(I18nKey.SETTINGS$PROFILE_DELETED, { name: profile.name }),+ );+ onClose();+ } catch (error) {+ const message =+ error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC);+ displayErrorToast(message);+ }+ };++ const handleClose = () => {+ if (!deleteProfile.isPending) {+ onClose();+ }+ };++ const footer = (+ <>+ <BrandButton+ ref={cancelButtonRef}+ type="button"+ variant="tertiary"+ onClick={handleClose}+ isDisabled={deleteProfile.isPending}+ >+ {t(I18nKey.BUTTON$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="delete-agent-profile-confirm"+ type="button"+ variant="danger"+ onClick={handleDelete}+ isDisabled={deleteProfile.isPending}+ aria-busy={deleteProfile.isPending}+ >+ {deleteProfile.isPending ? (+ <>+ <LoadingSpinner size="small" />+ <span className="sr-only">{t(I18nKey.BUTTON$DELETE)}</span>+ </>+ ) : (+ t(I18nKey.BUTTON$DELETE)+ )}+ </BrandButton>+ </>+ );++ return (+ <ApiKeyModalBase+ isOpen+ title={t(I18nKey.SETTINGS$PROFILE_DELETE_TITLE)}+ footer={footer}+ onClose={handleClose}+ initialFocusRef={cancelButtonRef}+ >+ <p className="text-sm break-all">+ {t(I18nKey.SETTINGS$PROFILE_DELETE_CONFIRMATION, {+ name: profile.name,+ })}+ </p>+ </ApiKeyModalBase>+ );+}diff --git a/src/components/features/settings/agent-profiles/index.ts b/src/components/features/settings/agent-profiles/index.tsnew file mode 100644index 0000000000..7c3d52fad5--- /dev/null+++ b/src/components/features/settings/agent-profiles/index.ts@@ -0,0 +1,6 @@+export { AgentProfilesLocalView } from "./agent-profiles-local-view";+export { AgentProfilesManager } from "./agent-profiles-manager";+export { AgentProfilesBody } from "./agent-profiles-body";+export { AgentProfileRow } from "./agent-profile-row";+export { AgentProfileActionsMenu } from "./agent-profile-actions-menu";+export { DeleteAgentProfileModal } from "./delete-agent-profile-modal";diff --git a/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts b/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.tsnew file mode 100644index 0000000000..787cb7f75b--- /dev/null+++ b/src/components/features/settings/agent-profiles/merge-agent-profile-save-input.ts@@ -0,0 +1,30 @@+import type {+ AgentProfile,+ AgentProfileSaveInput,+} from "#/api/agent-profiles-service/agent-profiles-service.api";++/**+ * Merge the minimal editor's fields over the stored profile so an edit-save+ * doesn't wipe the fields the editor doesn't model (condenser, verification,+ * system_message_suffix, mcp_server_refs, the disabled_skills deny-list, ACP+ * session mode/timeout, …) — `POST /api/agent-profiles/{name}` is a+ * whole-profile overwrite, and unset fields fall back to server-side defaults.+ *+ * Kind-aware: when the editor switched `agent_kind`, the stored variant's+ * fields must NOT be carried over — the server's `extra="forbid"` profile+ * union rejects a payload mixing openhands and acp fields — so a kind switch+ * stays a clean variant replacement built from the edited fields alone.+ *+ * Identity (`id` / `name` / `revision`) is stripped from the merge: the path+ * name is authoritative on save, and the server preserves the namesake's id+ * and bumps the revision itself (`save_profile_preserving_identity`).+ */+export function mergeAgentProfileSaveInput(+ stored: AgentProfile | null,+ edited: AgentProfileSaveInput,+): AgentProfileSaveInput {+ if (!stored) return edited;+ if (stored.agent_kind !== edited.agent_kind) return edited;+ const { id, name, revision, ...preserved } = stored;+ return { ...preserved, ...edited } as AgentProfileSaveInput;+}diff --git a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsxindex f04f3e6862..c354147a40 100644--- a/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx+++ b/src/components/features/settings/llm-profiles/llm-profiles-manager.tsx@@ -11,7 +11,7 @@ import ProfilesService, {import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";-import { useCanManageLlmProfiles } from "#/hooks/use-can-manage-llm-profiles";+import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";import {displayErrorToast,displaySuccessToast,@@ -33,7 +33,7 @@ export function LlmProfilesManager({const saveProfile = useSaveLlmProfile();// Cloud members are view-only; only owners/admins (and all local users) may// add, edit, rename, duplicate, delete, or activate profiles.- const canManage = useCanManageLlmProfiles();+ const canManage = useCanManageOrgProfiles();const [profileToRename, setProfileToRename] = useState<ProfileInfo | null>(null,);diff --git a/src/components/features/settings/llm-profiles/profile-actions-menu.tsx b/src/components/features/settings/llm-profiles/profile-actions-menu.tsxindex 4ffe4d317d..50874ce7c2 100644--- a/src/components/features/settings/llm-profiles/profile-actions-menu.tsx+++ b/src/components/features/settings/llm-profiles/profile-actions-menu.tsx@@ -176,7 +176,7 @@ export function ProfileActionsMenu({<MenuItemindex={3}icon={<CheckCircleIcon width={16} height={16} />}- label={t(I18nKey.SETTINGS$PROFILE_SET_ACTIVE)}+ label={t(I18nKey.SETTINGS$PROFILE_SET_DEFAULT)}onClick={() => handleAction(onSetActive)}onKeyDown={handleKeyDown}menuItemsRef={menuItemsRef}diff --git a/src/components/features/settings/llm-profiles/profile-row.tsx b/src/components/features/settings/llm-profiles/profile-row.tsxindex d3b29d5974..e5fd69b01c 100644--- a/src/components/features/settings/llm-profiles/profile-row.tsx+++ b/src/components/features/settings/llm-profiles/profile-row.tsx@@ -64,7 +64,10 @@ export function ProfileRow({className="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs"data-testid="profile-active-badge">- {t(I18nKey.SETTINGS$PROFILE_ACTIVE)}+ {/* "Default" (not "Active"): the active LLM profile no longer drives+ conversations — the active AGENT profile does — it's just the+ default `llm_profile_ref` seeded into new agent profiles. */}+ {t(I18nKey.SETTINGS$PROFILE_DEFAULT)}</BrandBadge>)}</div>diff --git a/src/constants/settings-nav.tsx b/src/constants/settings-nav.tsxindex 84ae8a1b67..daf44ac188 100644--- a/src/constants/settings-nav.tsx+++ b/src/constants/settings-nav.tsx@@ -11,7 +11,7 @@ export interface SettingsNavItem {/** Short grey subline under the page title (`settings.tsx`). */subtitle: string;// When true, this item is greyed out (and its route redirects to- // ``/settings/agent``) while the active agent is ACP. The ACP sub-agent+ // ``/settings/agents``) while the active agent is ACP. The ACP sub-agent// manages its own LLM / condenser / MCP, so these OpenHands-side// surfaces have nothing useful to configure. Drives both the navigation// disable in ``use-settings-nav-items.ts`` and the loader redirect in@@ -21,10 +21,14 @@ export interface SettingsNavItem {export const OSS_NAV_ITEMS: SettingsNavItem[] = [{+ // "Agent" is the Agent Profile library: it lists the user's agent profiles+ // and its create/edit view is the reused Agent settings form plus a name.+ // The active profile is the current agent (#1571). Replaces the old split+ // of a global "Agent" form + a separate "Agent profiles" library.icon: <RobotIcon width={16} height={16} />,- to: "/settings/agent",+ to: "/settings/agents",text: "SETTINGS$NAV_AGENT",- subtitle: "SETTINGS$PAGE_AGENT_SUBLINE",+ subtitle: "SETTINGS$PAGE_AGENT_PROFILES_SUBLINE",},{icon: <CircuitIcon width={16} height={16} />,diff --git a/src/hooks/mutation/use-activate-agent-profile.ts b/src/hooks/mutation/use-activate-agent-profile.tsnew file mode 100644index 0000000000..dc24ec96a1--- /dev/null+++ b/src/hooks/mutation/use-activate-agent-profile.ts@@ -0,0 +1,67 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import AgentProfilesService, {+ type AgentProfileListResponse,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ AGENT_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++/**+ * Shared key so any picker instance can observe an in-flight activation via+ * `useIsMutating` (the pill button and the menu that fires it are separate+ * hook instances, so per-observer `isPending` wouldn't line up).+ */+export const ACTIVATE_AGENT_PROFILE_MUTATION_KEY = ["activate-agent-profile"];++/**+ * Activate an agent profile by its stable UUID `id`. Activation is+ * pointer-only (it does NOT write agent_settings), but it changes the launch+ * default the backend resolves for new conversations, so the settings cache is+ * invalidated defensively alongside the profiles list.+ *+ * The active pointer is flipped optimistically so the picker label and the+ * launch default (`useCreateConversation` reads `active_agent_profile_id`)+ * reflect the selection before the refetch lands. Errors roll the pointer back+ * and surface via the global mutation toast (no `meta.disableToast`) so a+ * failure isn't silent when fired from the chat-input picker, whose menu+ * unmounts on select.+ */+export function useActivateAgentProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationKey: ACTIVATE_AGENT_PROFILE_MUTATION_KEY,+ mutationFn: (profileId: string) =>+ AgentProfilesService.activateProfile(profileId),+ onMutate: async (profileId) => {+ await queryClient.cancelQueries({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ const snapshots = queryClient.getQueriesData<AgentProfileListResponse>({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ queryClient.setQueriesData<AgentProfileListResponse>(+ { queryKey: AGENT_PROFILES_QUERY_KEYS.all },+ (prev) =>+ prev ? { ...prev, active_agent_profile_id: profileId } : prev,+ );+ return { snapshots };+ },+ onError: (_err, _profileId, context) => {+ context?.snapshots?.forEach(([key, data]) => {+ queryClient.setQueryData(key, data);+ });+ },+ onSuccess: async () => {+ SettingsService.invalidateCache();+ await queryClient.invalidateQueries({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ await queryClient.invalidateQueries({+ queryKey: SETTINGS_QUERY_KEYS.personal(),+ });+ },+ });+}diff --git a/src/hooks/mutation/use-apply-onboarding-agent-profile.ts b/src/hooks/mutation/use-apply-onboarding-agent-profile.tsnew file mode 100644index 0000000000..51f20cbd41--- /dev/null+++ b/src/hooks/mutation/use-apply-onboarding-agent-profile.ts@@ -0,0 +1,58 @@+import { useCallback } from "react";+import AgentProfilesService, {+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,+ type AgentProfileSaveInput,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useSaveAgentProfile } from "#/hooks/mutation/use-save-agent-profile";+import { useActivateAgentProfile } from "#/hooks/mutation/use-activate-agent-profile";++/**+ * The well-known agent profile onboarding configures. Conversations launch from+ * the active AGENT profile (#1571), so onboarding must land the user's choice on+ * an active profile — not just global agent_settings / a standalone LLM profile,+ * which the active profile wouldn't reference. Reusing the seeded "default" name+ * upserts that one profile (its id is preserved on overwrite) rather than+ * spawning a parallel one.+ */+export const ONBOARDING_AGENT_PROFILE_NAME =+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME;++/**+ * Configure and activate the onboarding agent profile from the user's choices:+ * an OpenHands profile pointing at the LLM profile onboarding just created, or+ * an ACP profile for the chosen provider (which owns its own LLM — no key).+ *+ * Best-effort: a failure (e.g. an older backend without `/api/agent-profiles`)+ * is swallowed so onboarding is never blocked — the global agent_settings the+ * setup steps already wrote remain the fallback.+ */+export function useApplyOnboardingAgentProfile() {+ const saveProfile = useSaveAgentProfile();+ const activateProfile = useActivateAgentProfile();++ return useCallback(+ async (profile: AgentProfileSaveInput) => {+ try {+ // Overwrite (not merge) is intentional: the `default` profile is the+ // baseline that mirrors the current onboarding choice, not a durable+ // store of per-profile customizations (home-launch resolves it via+ // agent_settings — see `useCreateConversation`). Re-onboarding resets it+ // to the fresh choice; users wanting durable custom config create a+ // named profile, which the editor saves via `mergeAgentProfileSaveInput`.+ await saveProfile.mutateAsync({+ name: ONBOARDING_AGENT_PROFILE_NAME,+ profile,+ });+ // activate needs the stable id; the save response only echoes the name.+ const detail = await AgentProfilesService.getProfile(+ ONBOARDING_AGENT_PROFILE_NAME,+ );+ const id = detail.profile.id;+ if (id) await activateProfile.mutateAsync(id);+ } catch (error) {+ console.error("Failed to configure onboarding agent profile:", error);+ }+ },+ [saveProfile, activateProfile],+ );+}diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.tsindex 5467e04618..2112b2f55c 100644--- a/src/hooks/mutation/use-create-conversation.ts+++ b/src/hooks/mutation/use-create-conversation.ts@@ -5,10 +5,22 @@ import { SuggestedTask } from "#/utils/types";import { Provider } from "#/types/settings";import { useTracking } from "#/hooks/use-tracking";import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";+import { useActiveBackend } from "#/contexts/active-backend-context";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import AgentProfilesService, {+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME,+ type AgentProfileListResponse,+} from "#/api/agent-profiles-service/agent-profiles-service.api";import PluginsManagementService, {type InstalledPluginInfo,} from "#/api/plugins-management-service";-import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";+import {+ PLUGINS_QUERY_KEYS,+ LLM_PROFILES_QUERY_KEYS,+ AGENT_PROFILES_QUERY_KEYS,+ AGENT_PROFILES_RETRY_OPTIONS,+} from "#/hooks/query/query-keys";import { pluginReferenceKey } from "#/utils/plugin-display";import {getStoredConversationMetadata,@@ -30,6 +42,10 @@ interface CreateConversationVariables {plugins?: PluginSpec[];workingDir?: string;workspaceMode?: WorkspaceMode;+ // Launch from a specific AgentProfile (local backend). When omitted, the+ // active AgentProfile (if any) is used so home-composed conversations+ // launch from the user's selected profile (#3727).+ agentProfileId?: string;entryPoint?: string; // analytics only; not forwarded to the service}@@ -47,6 +63,14 @@ export const useCreateConversation = () => {// Stamped onto the conversation at creation so the switcher can show the// exact profile even when several profiles share a model (#1082).const { data: llmProfiles } = useLlmProfiles();+ // Warm the agent-profiles cache too — the launch path below awaits the same+ // query via ensureQueryData, so a warm cache makes home-launch instant. The+ // hook's maybe-unresolved data is deliberately NOT read at launch time:+ // activation is pointer-only (it never writes agent_settings), so racing a+ // cold cache into the agent_settings fallback would silently launch the+ // wrong agent.+ const { backend, orgId } = useActiveBackend();+ useAgentProfiles();return useMutation({mutationKey: ["create-conversation"],@@ -62,8 +86,125 @@ export const useCreateConversation = () => {workspaceMode,parentConversationId,agentType,+ agentProfileId,} = variables;+ // The active AgentProfile is the default launch profile for new+ // conversations (#3727), on both local and cloud (cloud gained+ // /api/agent-profiles in OpenHands #15060, #3730). Await the list from+ // the shared query cache: a send fired before the home query resolves+ // must still launch from the active profile, not fall through to the+ // agent_settings path. Degrades safely: if the fetch errors (older+ // backend without the surface), this stays undefined and creation falls+ // back to the encrypted agent_settings launch path.+ let agentProfiles: AgentProfileListResponse | undefined;+ try {+ agentProfiles = await queryClient.ensureQueryData({+ queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backend.id, orgId],+ queryFn: AgentProfilesService.listProfiles,+ // Shared with useAgentProfiles and redirectIfAcpActive so the retry+ // policy for this surface can't drift between call sites (#1571+ // review): a backend without it fails every one of these on every+ // call, so degrade to the fallback immediately rather than sitting+ // through the default exponential-backoff retries each time.+ ...AGENT_PROFILES_RETRY_OPTIONS,+ });+ } catch {+ // Profiles unavailable → legacy agent_settings launch.+ }++ const requestedAgentProfileId =+ agentProfileId ?? agentProfiles?.active_agent_profile_id ?? undefined;++ // Fall back to the legacy agent_settings launch when the resolved agent+ // profile can't resolve its LLM. The agent-server seeds a `default`+ // openhands profile whose `llm_profile_ref` can point at an LLM profile+ // that doesn't exist (fresh store, or one configured with named profiles+ // only); launching from it 404s ("LLM profile '<ref>' not found") and+ // would brick home-launch. agent_settings reflects the active LLM, so the+ // fallback degrades cleanly until the seed mirrors it (SDK #3933).+ // ACP profiles carry no llm_profile_ref, so they're never gated here.+ const resolvedAgentProfile = requestedAgentProfileId+ ? agentProfiles?.profiles?.find(+ (profile) => profile.id === requestedAgentProfileId,+ )+ : undefined;+ // Cloud has no `agent_settings` payload to fall back to — the downgrade+ // below only makes sense on local, where it exists and carries the+ // canvas-only enrichments. Gating it here keeps cloud always launching+ // from the resolved profile id, so the conversation gets+ // `launched_agent_profile` stamped and the profile's config applied+ // (#1571 review).+ const isCloud = backend.kind === "cloud";+ let effectiveAgentProfileId = requestedAgentProfileId;+ if (+ !isCloud &&+ resolvedAgentProfile?.name === WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME &&+ resolvedAgentProfile?.agent_kind === "openhands"+ ) {+ // The seeded OpenHands `default` profile is the enriched baseline, not a+ // deliberate profile pick — it mirrors global agent_settings. Launch it+ // via agent_settings so the canvas-only enrichments the profile-resolution+ // path drops survive for the common home-launch: the <RUNTIME_SERVICES>+ // system-message suffix, the canvas_ui tool, and project-skill loading+ // (buildAgentContext). Named profiles are deliberate custom configs and+ // still use the profile path (accepting that enrichment boundary).+ // Trade-off: per-profile fields set on `default` itself don't apply on+ // home-launch — custom per-profile config belongs in a named profile.+ //+ // Scoped to OpenHands: an ACP `default` must keep the profile path.+ // Activation is pointer-only, so global agent_settings is stale (often+ // still OpenHands) when an ACP profile is active — launching it via+ // agent_settings would start the wrong agent. ACP also carries no+ // <RUNTIME_SERVICES>/canvas_ui enrichment, so there's nothing to preserve.+ //+ // Scoped to local: cloud never writes agent_settings, so it always+ // resolves `default` server-side via agent_profile_id (validated below).+ effectiveAgentProfileId = undefined;+ } else if (+ resolvedAgentProfile?.agent_kind === "openhands" &&+ resolvedAgentProfile.llm_profile_ref+ ) {+ // Await the LLM-profile list rather than reading the maybe-unresolved+ // `useLlmProfiles()` result: a send fired before that query loads (or+ // after it errors) must still validate the ref, not launch blind.+ let llmProfileExists = false;+ try {+ const llm = await queryClient.ensureQueryData({+ queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backend.id, orgId],+ queryFn: ProfilesService.listProfiles,+ // Match the agent-profiles fetch above: on a backend where this+ // errors, fall back to agent_settings immediately rather than+ // stalling the send through the default exponential backoff.+ retry: false,+ });+ llmProfileExists = llm.profiles.some(+ (profile) => profile.name === resolvedAgentProfile.llm_profile_ref,+ );+ } catch {+ // List unavailable → can't validate → fall back to agent_settings.+ }+ if (!llmProfileExists) {+ // Downgrade is silent in the UI; leave a diagnosable trace.+ console.warn(+ `Agent profile "${resolvedAgentProfile.name}" references missing ` ++ `LLM profile "${resolvedAgentProfile.llm_profile_ref}"; ` ++ "launching from agent_settings instead.",+ );+ effectiveAgentProfileId = undefined;+ }+ }++ // Only extend the call with the [sandboxId, agentProfileId] tail when+ // launching from a profile, so a plain create stays byte-identical to+ // the legacy agent_settings path (#3727). sandboxId is unused here.+ // TODO(#1587): createConversation has grown to 10 positional params;+ // refactor it to an options object so this position-skipping tail isn't+ // needed.+ const profileArgs: [undefined, string] | [] = effectiveAgentProfileId+ ? [undefined, effectiveAgentProfileId]+ : [];+const conversation =await AgentServerConversationService.createConversation(query,@@ -80,6 +221,7 @@ export const useCreateConversation = () => {workspaceMode,parentConversationId,agentType,+ ...profileArgs,);// Stamp the active LLM profile onto the (local) conversation so the@@ -127,7 +269,19 @@ export const useCreateConversation = () => {.filter((plugin) => !seen.has(pluginReferenceKey(plugin)));attachedPlugins = [...explicitPlugins, ...enabledInstalled];}- const activeProfile = llmProfiles?.active_profile ?? null;+ // A launch from a named OpenHands profile runs that profile's+ // `llm_profile_ref`, which can differ from the standalone active LLM+ // profile — stamp the ref so the switcher pill names the exact profile+ // the conversation runs (#1082). The agent_settings path (the `default`+ // baseline or a dangling ref, where effectiveAgentProfileId is cleared)+ // runs the active LLM, so it keeps `active_profile`. ACP profiles carry+ // no LLM profile, so they fall through to the active-profile stamp+ // (unused by the ACP model chip).+ const activeProfile =+ effectiveAgentProfileId &&+ resolvedAgentProfile?.agent_kind === "openhands"+ ? resolvedAgentProfile.llm_profile_ref+ : (llmProfiles?.active_profile ?? null);if (localConversationId && (activeProfile || attachedPlugins.length)) {const prev = getStoredConversationMetadata(localConversationId);setStoredConversationMetadata(localConversationId, {diff --git a/src/hooks/mutation/use-delete-agent-profile.ts b/src/hooks/mutation/use-delete-agent-profile.tsnew file mode 100644index 0000000000..cac2a640a0--- /dev/null+++ b/src/hooks/mutation/use-delete-agent-profile.ts@@ -0,0 +1,18 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";+import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";++export function useDeleteAgentProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: (name: string) => AgentProfilesService.deleteProfile(name),+ onSuccess: async () => {+ await queryClient.invalidateQueries({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ },+ // Consumers handle errors with try-catch and manual toasts.+ meta: { disableToast: true },+ });+}diff --git a/src/hooks/mutation/use-rename-agent-profile.ts b/src/hooks/mutation/use-rename-agent-profile.tsnew file mode 100644index 0000000000..dabb7d27d6--- /dev/null+++ b/src/hooks/mutation/use-rename-agent-profile.ts@@ -0,0 +1,24 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";+import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";++interface RenameAgentProfileVariables {+ name: string;+ newName: string;+}++export function useRenameAgentProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({ name, newName }: RenameAgentProfileVariables) =>+ AgentProfilesService.renameProfile(name, newName),+ onSuccess: async () => {+ await queryClient.invalidateQueries({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ },+ // Consumers handle errors with try-catch and manual toasts.+ meta: { disableToast: true },+ });+}diff --git a/src/hooks/mutation/use-save-agent-profile.ts b/src/hooks/mutation/use-save-agent-profile.tsnew file mode 100644index 0000000000..6ed1418ce5--- /dev/null+++ b/src/hooks/mutation/use-save-agent-profile.ts@@ -0,0 +1,27 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import AgentProfilesService, {+ type AgentProfileSaveInput,+} from "#/api/agent-profiles-service/agent-profiles-service.api";+import { AGENT_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";++export function useSaveAgentProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({+ name,+ profile,+ }: {+ name: string;+ profile: AgentProfileSaveInput;+ }) => AgentProfilesService.saveProfile(name, profile),+ onSuccess: async () => {+ // Prefix match invalidates every backend/org-suffixed list key.+ await queryClient.invalidateQueries({+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,+ });+ },+ // Consumers handle errors with try-catch + targeted toasts (409/422).+ meta: { disableToast: true },+ });+}diff --git a/src/hooks/mutation/use-switch-acp-model.ts b/src/hooks/mutation/use-switch-acp-model.tsindex 827f437997..f4b816b03c 100644--- a/src/hooks/mutation/use-switch-acp-model.ts+++ b/src/hooks/mutation/use-switch-acp-model.ts@@ -59,9 +59,9 @@ export const useSwitchAcpModel = () => {});}},- // No meta.disableToast: unlike useSwitchLlmProfile (wrapped by- // useSwitchLlmProfileAndLog, which re-surfaces errors), this hook is called- // directly, so we let the global mutation error toast report a failed- // switch / settings write rather than swallowing it.+ // No meta.disableToast: unlike useSwitchLlmProfile (which tailors a+ // "Switched to {name} failed" message via its own onError), there's no+ // per-action message worth tailoring here, so the global mutation error+ // toast reports a failed switch / settings write rather than swallowing it.});};diff --git a/src/hooks/mutation/use-switch-llm-profile-and-log.ts b/src/hooks/mutation/use-switch-llm-profile-and-log.tsindex c3e44b98b1..b6933264ea 100644--- a/src/hooks/mutation/use-switch-llm-profile-and-log.ts+++ b/src/hooks/mutation/use-switch-llm-profile-and-log.ts@@ -1,69 +1,19 @@import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-anchor";-import { recordModelSwitchMessage } from "#/hooks/chat/record-model-switch-message";import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";-import {- getStoredConversationMetadata,- setStoredConversationMetadata,-} from "#/api/conversation-metadata-store";-import { displayErrorToast } from "#/utils/custom-toast-handlers";-import { I18nKey } from "#/i18n/declaration";/**- * Switch the conversation's LLM profile and render the result inline (same- * UX as `/model <name>`). On success the switch is recorded against the- * last rendered event so the confirmation lines up with where the user- * issued the command.+ * Positional wrapper around {@link useSwitchLlmProfile}. The switch's inline+ * "Switched to" message, #1082 metadata persist, and error reporting all live+ * in the mutation itself, so they survive the switcher menu closing on select.*/export function useSwitchLlmProfileAndLog() {const { mutate, isPending } = useSwitchLlmProfile();- const { t } = useTranslation();const switchAndLog = useCallback((conversationId: string | null, profileName: string) => {- const anchorEventId = getLastRenderableEventId();-- mutate(- { conversationId, profileName },- {- onSuccess: () => {- // The inline "Switched to" message is scoped to a conversation;- // skip it when activating from the home page (no convo yet).- if (conversationId) {- recordModelSwitchMessage(- conversationId,- profileName,- anchorEventId,- );- // Keep the per-conversation profile identity fresh so the- // chat-header switcher shows the right name after a reload- // (the agent-server only round-trips the model string). #1082- const prev = getStoredConversationMetadata(conversationId);- setStoredConversationMetadata(conversationId, {- selected_repository: prev?.selected_repository ?? null,- selected_branch: prev?.selected_branch ?? null,- git_provider: prev?.git_provider ?? null,- selected_workspace: prev?.selected_workspace ?? null,- active_profile: profileName,- // Full-object replace: carry the plugins snapshot forward so- // the in-conversation plugins view survives a profile switch.- plugins: prev?.plugins ?? null,- });- }- },- onError: (err: unknown) => {- const fallback = t(I18nKey.MODEL$SWITCH_FAILED, {- name: profileName,- });- const message =- err instanceof Error && err.message ? err.message : fallback;- displayErrorToast(message);- },- },- );+ mutate({ conversationId, profileName });},- [mutate, t],+ [mutate],);return { switchAndLog, isPending };diff --git a/src/hooks/mutation/use-switch-llm-profile.ts b/src/hooks/mutation/use-switch-llm-profile.tsindex a157dd66a9..b6d64b7cce 100644--- a/src/hooks/mutation/use-switch-llm-profile.ts+++ b/src/hooks/mutation/use-switch-llm-profile.ts@@ -1,10 +1,20 @@import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import SettingsService from "#/api/settings-service/settings-service.api";import {LLM_PROFILES_QUERY_KEYS,SETTINGS_QUERY_KEYS,} from "#/hooks/query/query-keys";+import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-anchor";+import { recordModelSwitchMessage } from "#/hooks/chat/record-model-switch-message";+import {+ getStoredConversationMetadata,+ setStoredConversationMetadata,+} from "#/api/conversation-metadata-store";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { I18nKey } from "#/i18n/declaration";import { invalidateConversationQueries } from "./conversation-mutation-utils";interface SwitchLlmProfileVars {@@ -17,25 +27,68 @@ interface SwitchLlmProfileVars {profileName: string;}+/**+ * Shared key so any picker instance can observe an in-flight switch via+ * `useIsMutating` — the pill button and the menu that fires the switch are+ * separate hook instances, so per-observer `isPending` wouldn't line up.+ */+export const SWITCH_LLM_PROFILE_MUTATION_KEY = ["switch-llm-profile"];+/*** Switches the LLM profile. Per-conversation when called from inside a- * conversation; globally activates the profile when called from the home- * page. Invalidates the conversation query so consumers reading `llm_model`- * pick up the swap, and the profile list so anything reading `active_profile`- * stays in sync.+ * conversation; globally activates the profile when called from the home page.+ *+ * The confirmation message, #1082 metadata persist, and error reporting all+ * live in the mutation-level callbacks (not `mutate(..., callbacks)`) so they+ * still run after the switcher menu closes on select — React Query drops+ * mutate-scoped callbacks when the calling component unmounts.+ *+ * `meta.disableToast` + a tailored `onError` (rather than the global mutation+ * toast) so a failed switch keeps the specific "Switched to {name} failed"+ * message instead of a generic error (#1571 review) — unlike+ * use-switch-acp-model, which has no per-action message worth tailoring.*/export const useSwitchLlmProfile = () => {const queryClient = useQueryClient();+ const { t } = useTranslation();return useMutation({+ mutationKey: SWITCH_LLM_PROFILE_MUTATION_KEY,mutationFn: ({ conversationId, profileName }: SwitchLlmProfileVars) =>AgentServerConversationService.switchProfile(conversationId, profileName),- onSuccess: (_data, { conversationId }) => {+ meta: { disableToast: true },+ // Anchor the inline message where the user issued the switch; captured+ // synchronously here because the menu unmounts before the switch resolves.+ onMutate: ({ conversationId }) => ({+ anchorEventId: conversationId ? getLastRenderableEventId() : null,+ }),+ onError: (error, { profileName }) => {+ const fallback = t(I18nKey.MODEL$SWITCH_FAILED, { name: profileName });+ displayErrorToast(retrieveAxiosErrorMessage(error) || fallback);+ },+ onSuccess: (_data, { conversationId, profileName }, context) => {queryClient.invalidateQueries({queryKey: LLM_PROFILES_QUERY_KEYS.all,});if (conversationId) {invalidateConversationQueries(queryClient, conversationId);+ recordModelSwitchMessage(+ conversationId,+ profileName,+ context?.anchorEventId ?? null,+ );+ // Keep the per-conversation profile identity fresh so the chat-header+ // switcher shows the right name after a reload (the agent-server only+ // round-trips the model string). #1082+ const prev = getStoredConversationMetadata(conversationId);+ setStoredConversationMetadata(conversationId, {+ selected_repository: prev?.selected_repository ?? null,+ selected_branch: prev?.selected_branch ?? null,+ git_provider: prev?.git_provider ?? null,+ selected_workspace: prev?.selected_workspace ?? null,+ active_profile: profileName,+ plugins: prev?.plugins ?? null,+ });} else {// Home-page activate path (same server endpoint as// useActivateLlmProfile): clear the SettingsService cache so the next@@ -47,7 +100,5 @@ export const useSwitchLlmProfile = () => {});}},- // Caller renders an inline message + handles error toast manually.- meta: { disableToast: true },});};diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.tsindex cd602d7326..5bbd11cb0d 100644--- a/src/hooks/query/query-keys.ts+++ b/src/hooks/query/query-keys.ts@@ -20,6 +20,21 @@ export const LLM_PROFILES_QUERY_KEYS = {all: ["llm-profiles"] as const,} as const;+export const AGENT_PROFILES_QUERY_KEYS = {+ all: ["agent-profiles"] as const,+} as const;++/**+ * Shared retry policy for every `/api/agent-profiles` fetch (the launch path+ * in `useCreateConversation`, `redirectIfAcpActive`'s route guard, and+ * `useAgentProfiles`). An older backend without the surface fails every one+ * of these on every call — `retry: false` degrades immediately instead of+ * sitting through the default exponential backoff each time (#1571 review).+ */+export const AGENT_PROFILES_RETRY_OPTIONS = {+ retry: false,+} as const;+export const LLM_SUBSCRIPTION_QUERY_KEYS = {all: ["llm-subscription"] as const,openaiStatus: ["llm-subscription", "openai", "status"] as const,diff --git a/src/hooks/query/use-agent-profiles.ts b/src/hooks/query/use-agent-profiles.tsnew file mode 100644index 0000000000..41c5056a74--- /dev/null+++ b/src/hooks/query/use-agent-profiles.ts@@ -0,0 +1,35 @@+import { useQuery } from "@tanstack/react-query";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";+import {+ CONFIG_CACHE_OPTIONS,+ AGENT_PROFILES_QUERY_KEYS,+ AGENT_PROFILES_RETRY_OPTIONS,+} from "./query-keys";++export { AGENT_PROFILES_QUERY_KEYS };++interface UseAgentProfilesOptions {+ enabled?: boolean;+}++/**+ * List the user's AgentProfiles (Settings → Agent profiles library). On first+ * GET of an empty store the backend lazily seeds one default profile mirroring+ * the user's prior config (#3719), so the list is never empty for an upgrading+ * user. Works on both local and cloud backends — `AgentProfilesService` routes+ * cloud calls through the cloud proxy (OpenHands #15060).+ */+export function useAgentProfiles(options: UseAgentProfilesOptions = {}) {+ const { backend, orgId } = useActiveBackend();++ return useQuery({+ // Backend identity isolates the cache across backend/org switches.+ queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backend.id, orgId],+ queryFn: AgentProfilesService.listProfiles,+ ...CONFIG_CACHE_OPTIONS,+ ...AGENT_PROFILES_RETRY_OPTIONS,+ enabled: options.enabled ?? true,+ meta: { disableToast: true },+ });+}diff --git a/src/hooks/use-acp-model-context.ts b/src/hooks/use-acp-model-context.tsindex ee47c713a6..63e0e91aa2 100644--- a/src/hooks/use-acp-model-context.ts+++ b/src/hooks/use-acp-model-context.ts@@ -2,6 +2,7 @@ import { useTranslation } from "react-i18next";import { useActiveBackend } from "#/contexts/active-backend-context";import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { useSettings } from "#/hooks/query/use-settings";+import { useActiveAgentKind } from "#/hooks/use-active-agent-profile";import { I18nKey } from "#/i18n/declaration";export interface AcpModelContext {@@ -16,7 +17,7 @@ export interface AcpModelContext {/** Either of the above: the model affordance should defer to the ACP picker. */isAcpContext: boolean;/** Where the model/settings link should navigate. */- destinationPath: "/settings/agent" | "/settings";+ destinationPath: "/settings/agents" | "/settings";/** Translated label for that link. */destinationLabel: string;}@@ -32,13 +33,18 @@ export function useAcpModelContext(): AcpModelContext {const { backend } = useActiveBackend();const { data: conversation } = useActiveConversation();const { data: settings } = useSettings();+ const activeAgentKind = useActiveAgentKind();const isActiveAcpConversation = conversation?.agent_kind === "acp";+ // On the home page the "current agent" is the active AgentProfile, not the+ // global agent settings (activate never writes them). Fall back to settings+ // only while the profile list is loading.const isHomeAcp =- !conversation && settings?.agent_settings?.agent_kind === "acp";+ !conversation &&+ (activeAgentKind ?? settings?.agent_settings?.agent_kind) === "acp";const isAcpContext = isActiveAcpConversation || isHomeAcp;- const destinationPath = isAcpContext ? "/settings/agent" : "/settings";+ const destinationPath = isAcpContext ? "/settings/agents" : "/settings";const destinationLabel = t(isAcpContext? I18nKey.SETTINGS$NAV_AGENTdiff --git a/src/hooks/use-active-agent-profile.ts b/src/hooks/use-active-agent-profile.tsnew file mode 100644index 0000000000..fedb91e440--- /dev/null+++ b/src/hooks/use-active-agent-profile.ts@@ -0,0 +1,32 @@+import type { AgentKind } from "@openhands/typescript-client";+import type { AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";++/**+ * The agent profile the user has activated — the authoritative "current agent"+ * now that Settings → Agent IS the profile library (#1571). `activate` is+ * pointer-only and never writes `settings.agent_settings`, so the active+ * profile — not the global agent settings — is the source of truth for what+ * kind of agent (OpenHands vs ACP) is in effect.+ */+export function useActiveAgentProfile(): {+ activeProfile: AgentProfileSummary | null;+ isLoading: boolean;+} {+ const { data, isLoading } = useAgentProfiles();+ const activeId = data?.active_agent_profile_id ?? null;+ const activeProfile =+ data?.profiles.find((p) => p.id != null && p.id === activeId) ?? null;+ return { activeProfile, isLoading };+}++/**+ * The effective agent kind from the active profile. `undefined` while the+ * profile list is loading or when no profile is active — callers should fall+ * back to `settings.agent_settings.agent_kind` in that window to avoid a flash+ * of the wrong (OpenHands-default) UI.+ */+export function useActiveAgentKind(): AgentKind | undefined {+ const { activeProfile } = useActiveAgentProfile();+ return activeProfile?.agent_kind;+}diff --git a/src/hooks/use-can-manage-llm-profiles.ts b/src/hooks/use-can-manage-org-profiles.tssimilarity index 84%rename from src/hooks/use-can-manage-llm-profiles.tsrename to src/hooks/use-can-manage-org-profiles.tsindex 6cc62cf9cc..7768a38199 100644--- a/src/hooks/use-can-manage-llm-profiles.ts+++ b/src/hooks/use-can-manage-org-profiles.ts@@ -4,14 +4,15 @@ import { useActiveBackend } from "#/contexts/active-backend-context";/*** Server-defined permission (mirrors the app-server's- * `authorization.Permission.EDIT_ORG_SETTINGS`) that gates LLM-profile- * mutations for an org.+ * `authorization.Permission.EDIT_ORG_SETTINGS`) that gates org-scoped profile+ * mutations (both LLM profiles and agent profiles).*/const EDIT_ORG_SETTINGS = "edit_org_settings";/**- * Whether the current user may MUTATE LLM profiles on the active backend —- * create, edit, rename, delete, duplicate, or activate/switch.+ * Whether the current user may MUTATE org-scoped profiles — LLM profiles and+ * agent profiles alike — on the active backend: create, edit, rename, delete,+ * duplicate, or activate/switch.** - Local agent-server (OSS): always `true`; the user owns their own profiles.* - Cloud: profiles are org-scoped. The app-server grants every mutating@@ -25,7 +26,7 @@ const EDIT_ORG_SETTINGS = "edit_org_settings";* Returns `false` while the role/permissions are still loading or unknown on* cloud, so mutating controls never flash for a member before they resolve.*/-export function useCanManageLlmProfiles(): boolean {+export function useCanManageOrgProfiles(): boolean {const { backend, orgId } = useActiveBackend();const isCloud = backend.kind === "cloud";diff --git a/src/hooks/use-chat-input-llm-profile-state.ts b/src/hooks/use-chat-input-llm-profile-state.tsnew file mode 100644index 0000000000..f2894f4e1c--- /dev/null+++ b/src/hooks/use-chat-input-llm-profile-state.ts@@ -0,0 +1,91 @@+import { useCallback } from "react";+import { useIsMutating } from "@tanstack/react-query";+import type { ProfileInfo } from "@openhands/typescript-client";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { useActiveConversation } from "#/hooks/query/use-active-conversation";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";+import { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";+import { SWITCH_LLM_PROFILE_MUTATION_KEY } from "#/hooks/mutation/use-switch-llm-profile";+import { useModelStore } from "#/stores/model-store";++export interface ChatInputLlmProfileState {+ profiles: ProfileInfo[];+ /** The LLM profile the running conversation is currently using. */+ currentProfileName: string | null;+ /** That profile's model id (for the tooltip / subtitle). */+ currentProfileModel: string | null;+ isLoading: boolean;+ isSwitching: boolean;+ /**+ * Live-switch the running conversation's LLM profile via `/switch_profile`.+ * This surface is only mounted inside a conversation, so a switch always+ * targets that conversation (no home-page activate path here).+ */+ selectProfile: (profileName: string) => void;+}++/**+ * Backs the in-conversation OpenHands LLM-profile switcher (the ACP analog is+ * {@link useChatInputModelState}). Resolves which profile the conversation is+ * running and live-swaps it, mirroring the former SwitchProfileButton's+ * resolution priority so a switch is reflected instantly.+ */+export function useChatInputLlmProfileState(): ChatInputLlmProfileState {+ const { conversationId } = useOptionalConversationId();+ const { data: conversation } = useActiveConversation();+ const { data, isLoading } = useLlmProfiles();+ const { switchAndLog } = useSwitchLlmProfileAndLog();+ // Read the switch's pending state globally by mutation key: the pill button+ // and the menu that fires the switch are separate hook instances, so a+ // per-observer `isPending` would never light up on the button (#1571).+ const isSwitching =+ useIsMutating({ mutationKey: SWITCH_LLM_PROFILE_MUTATION_KEY }) > 0;+ // Written by useSwitchLlmProfile's onSuccess -> recordModelSwitchMessage ->+ // recordSwitch on a successful switch, so the label/check update before the+ // conversation refetch lands the new llm_model.+ const optimisticActiveProfile = useModelStore((s) =>+ conversationId ? s.activeProfileByConversation[conversationId] : undefined,+ );++ const profiles = data?.profiles ?? [];+ const conversationModel = conversation?.llm_model ?? null;++ // Resolution priority (mirrors the former SwitchProfileButton):+ // 1. Optimistic (just-clicked) — instant feedback before the refetch.+ // 2. Profile stamped on the conversation, validated against the live list+ // so a since-deleted/renamed profile falls through.+ // 3. Profile whose model matches the running llm_model.+ // 4. User-level active_profile (fallback before the first message).+ const stampedProfile = conversation?.active_profile ?? null;+ const conversationProfile =+ stampedProfile && profiles.some((p) => p.name === stampedProfile)+ ? stampedProfile+ : null;+ const currentProfileName =+ optimisticActiveProfile ??+ conversationProfile ??+ (conversationModel+ ? (profiles.find((p) => p.model === conversationModel)?.name ?? null)+ : (data?.active_profile ?? null));+ const currentProfileModel =+ profiles.find((p) => p.name === currentProfileName)?.model ??+ conversationModel ??+ null;++ const selectProfile = useCallback(+ (profileName: string) => {+ if (profileName === currentProfileName) return;+ switchAndLog(conversationId, profileName);+ },+ [conversationId, currentProfileName, switchAndLog],+ );++ return {+ profiles,+ currentProfileName,+ currentProfileModel,+ isLoading,+ isSwitching,+ selectProfile,+ };+}diff --git a/src/hooks/use-chat-input-model-state.ts b/src/hooks/use-chat-input-model-state.tsindex 40dd59333d..c63f42a709 100644--- a/src/hooks/use-chat-input-model-state.ts+++ b/src/hooks/use-chat-input-model-state.ts@@ -17,7 +17,7 @@ export interface ChatInputModelState {availableAcpModels: ACPModelOption[];showAcpPicker: boolean;switchConversationId: string | null;- destinationPath: "/settings/agent" | "/settings";+ destinationPath: "/settings/agents" | "/settings";destinationLabel: string;}diff --git a/src/hooks/use-chat-input-profile-state.ts b/src/hooks/use-chat-input-profile-state.tsnew file mode 100644index 0000000000..a77f49d494--- /dev/null+++ b/src/hooks/use-chat-input-profile-state.ts@@ -0,0 +1,60 @@+import { useCallback } from "react";+import { useIsMutating } from "@tanstack/react-query";+import type { AgentProfileSummary } from "#/api/agent-profiles-service/agent-profiles-service.api";+import { useAgentProfiles } from "#/hooks/query/use-agent-profiles";+import {+ useActivateAgentProfile,+ ACTIVATE_AGENT_PROFILE_MUTATION_KEY,+} from "#/hooks/mutation/use-activate-agent-profile";++export interface ChatInputProfileState {+ profiles: AgentProfileSummary[];+ /** id of the active profile the next conversation will launch from. */+ currentProfileId: string | null;+ currentProfileName: string | null;+ isLoading: boolean;+ isSwitching: boolean;+ /** Activate a profile so the next conversation launches from it. */+ selectProfile: (profile: AgentProfileSummary) => void;+}++/**+ * Backs the home chat-input AgentProfile picker. This picker is only rendered+ * on the home screen — inside a conversation the chat input shows the+ * in-conversation LLM-profile picker (OpenHands) or model picker (ACP) instead+ * (see `chat-input-actions.tsx` `pickerKind`). So selecting a profile here+ * simply activates it as the launch default; `useCreateConversation` reads the+ * active profile when the next conversation starts.+ */+export function useChatInputProfileState(): ChatInputProfileState {+ const { data: agentProfiles, isLoading } = useAgentProfiles();+ const activateProfile = useActivateAgentProfile();+ // Observe the activation globally by mutation key so the picker button (a+ // separate hook instance from the menu that fires it) disables correctly+ // while a switch is in flight (#1571).+ const isSwitching =+ useIsMutating({ mutationKey: ACTIVATE_AGENT_PROFILE_MUTATION_KEY }) > 0;++ const profiles = agentProfiles?.profiles ?? [];+ const currentProfileId = agentProfiles?.active_agent_profile_id ?? null;+ const currentProfileName =+ profiles.find((p) => p.id != null && p.id === currentProfileId)?.name ??+ null;++ const selectProfile = useCallback(+ (profile: AgentProfileSummary) => {+ if (!profile.id || profile.id === currentProfileId) return;+ activateProfile.mutate(profile.id);+ },+ [currentProfileId, activateProfile],+ );++ return {+ profiles,+ currentProfileId,+ currentProfileName,+ isLoading,+ isSwitching,+ selectProfile,+ };+}diff --git a/src/hooks/use-llm-configured.ts b/src/hooks/use-llm-configured.tsindex 183387dcbb..128dbfd2c0 100644--- a/src/hooks/use-llm-configured.ts+++ b/src/hooks/use-llm-configured.ts@@ -3,6 +3,7 @@ import { useSettings } from "#/hooks/query/use-settings";import { useConfig } from "#/hooks/query/use-config";import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";import { useActiveBackend } from "#/contexts/active-backend-context";+import { useActiveAgentProfile } from "#/hooks/use-active-agent-profile";import { isSettingsPageHidden } from "#/utils/settings-utils";import ProfilesService from "#/api/profiles-service/profiles-service.api";import {@@ -54,11 +55,42 @@ export function useLlmConfigured(): LlmConfiguredResult {const { backend, orgId } = useActiveBackend();const isLocal = backend.kind === "local";- const isAcpAgent = settings?.agent_settings?.agent_kind === "acp";+ // The active AgentProfile is the current agent — an ACP profile owns its LLM+ // via the subprocess and never needs an API key. Fall back to the global+ // agent settings only while the profile list loads.+ const {+ activeProfile: activeAgentProfile,+ isLoading: activeAgentProfileLoading,+ } = useActiveAgentProfile();+ const activeAgentKind = activeAgentProfile?.agent_kind;+ const isAcpAgent =+ (activeAgentKind ?? settings?.agent_settings?.agent_kind) === "acp";const hasApiKey = settings?.llm_api_key_set === true;- const activeProfile = profilesData?.profiles.find(- (profile) => profile.name === profilesData.active_profile,- );+ // The LLM that will actually power the next conversation is the profile the+ // active AGENT profile references (`llm_profile_ref`) — conversations launch+ // from the agent profile, not the standalone "active LLM profile".+ const referencedLlmProfileName =+ activeAgentProfile?.agent_kind === "openhands"+ ? activeAgentProfile.llm_profile_ref+ : undefined;+ const referencedProfile = referencedLlmProfileName+ ? profilesData?.profiles.find(+ (profile) => profile.name === referencedLlmProfileName,+ )+ : undefined;+ // Fall back to the active LLM profile when the ref is absent (list loading,+ // or an agent profile without a ref) OR stale (names a profile that no longer+ // exists). This mirrors the launch-time fallback in `useCreateConversation`,+ // which drops a stale-ref profile launch to an `agent_settings` launch on the+ // active LLM. Without this fallback the two contradict each other: launch+ // succeeds via the fallback, but this hook reports `isConfigured: false` and+ // spuriously disables the composer + shows the banner — even inside a running+ // conversation (VascoSch92 review, #1571).+ const activeProfile =+ referencedProfile ??+ profilesData?.profiles.find(+ (profile) => profile.name === profilesData?.active_profile,+ );const hasActiveProfileApiKey = activeProfile?.api_key_set === true;const shouldLoadActiveProfileDetail =isLocal && !!activeProfile && !hasActiveProfileApiKey;@@ -109,6 +141,11 @@ export function useLlmConfigured(): LlmConfiguredResult {// state the banner exists to catch — so we keep deciding from that data.const settingsIndeterminate = settingsLoading || (settingsError && !settings);const configIndeterminate = configLoading || (configError && !config);+ // The active agent profile decides `isAcpAgent` and which LLM profile the+ // next conversation runs; on a cold cache it's still loading, so decide+ // nothing yet — otherwise an ACP agent (which needs no key) briefly reads as+ // an unconfigured OpenHands agent and flashes the "LLM not set up" banner.+ const agentProfileIndeterminate = activeAgentProfileLoading;const profilesIndeterminate =profilesLoading || (profilesError && !profilesData);const activeProfileDetailIndeterminate =@@ -122,6 +159,7 @@ export function useLlmConfigured(): LlmConfiguredResult {settingsIndeterminate ||configIndeterminate ||profilesIndeterminate ||+ agentProfileIndeterminate ||activeProfileDetailIndeterminate,};}diff --git a/src/hooks/use-settings-nav-items.ts b/src/hooks/use-settings-nav-items.tsindex a61773c040..cc36a6cdd0 100644--- a/src/hooks/use-settings-nav-items.ts+++ b/src/hooks/use-settings-nav-items.ts@@ -5,6 +5,7 @@ import { ACP_PROVIDERS } from "#/constants/acp-providers";import { isSettingsPageHidden } from "#/utils/settings-utils";import { I18nKey } from "#/i18n/declaration";import { useActiveBackend } from "#/contexts/active-backend-context";+import { useActiveAgentProfile } from "#/hooks/use-active-agent-profile";export type SettingsNavRenderedItem =| {@@ -22,17 +23,30 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] {const { backend } = useActiveBackend();const featureFlags = config?.feature_flags;+ // The active AgentProfile is the source of truth for the current agent kind+ // (activate is pointer-only and never writes agent_settings). Fall back to+ // the global agent settings only while the profile list is loading, so the+ // ACP-incompatible nav items (LLM/condenser/verification) don't briefly+ // enable before the active profile resolves.const agentSettings = settings?.agent_settings ?? null;- const isAcpAgent = agentSettings?.agent_kind === "acp";+ const { activeProfile } = useActiveAgentProfile();+ const isAcpAgent =+ (activeProfile?.agent_kind ?? agentSettings?.agent_kind) === "acp";const acpServerKey =typeof agentSettings?.acp_server === "string"? agentSettings.acp_server: undefined;+ // Name the active agent in the disabled-item tooltip: prefer the active+ // profile's name, then the ACP provider display name, then a generic label.const acpServerName = isAcpAgent- ? (ACP_PROVIDERS.find(({ key }) => key === acpServerKey)?.display_name ??+ ? (activeProfile?.name ??+ ACP_PROVIDERS.find(({ key }) => key === acpServerKey)?.display_name ??"ACP Agent"): undefined;+ // Agent profiles are available on both local and cloud backends — the cloud+ // enterprise app-server exposes the same `/api/agent-profiles` surface+ // (OpenHands #15060, epic #3730), so the nav item is no longer local-gated.return OSS_NAV_ITEMS.filter((item) => !isSettingsPageHidden(item.to, featureFlags),).map((item) => {diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 7c71d34d94..2a188913f4 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -2243,6 +2243,159 @@"uk": "Агент","ca": "Agent"},+ "SETTINGS$NAV_AGENT_PROFILES": {+ "en": "Agent profiles",+ "ja": "エージェントプロファイル",+ "zh-CN": "代理配置文件",+ "zh-TW": "代理設定檔",+ "ko-KR": "에이전트 프로필",+ "no": "Agentprofiler",+ "it": "Profili agente",+ "pt": "Perfis de agente",+ "es": "Perfiles de agente",+ "ar": "ملفات تعريف الوكيل",+ "fr": "Profils d'agent",+ "tr": "Ajan profilleri",+ "de": "Agentenprofile",+ "uk": "Профілі агента",+ "ca": "Perfils d'agent"+ },+ "SETTINGS$PAGE_AGENT_PROFILES_SUBLINE": {+ "en": "Create and manage reusable agent setups.",+ "ja": "再利用可能なエージェント設定を作成・管理します。",+ "zh-CN": "创建和管理可重用的代理设置。",+ "zh-TW": "建立與管理可重複使用的代理設定。",+ "ko-KR": "재사용 가능한 에이전트 설정을 만들고 관리합니다.",+ "no": "Opprett og administrer gjenbrukbare agentoppsett.",+ "it": "Crea e gestisci configurazioni di agente riutilizzabili.",+ "pt": "Crie e gerencie configurações de agente reutilizáveis.",+ "es": "Crea y gestiona configuraciones de agente reutilizables.",+ "ar": "أنشئ وأدر إعدادات الوكيل القابلة لإعادة الاستخدام.",+ "fr": "Créez et gérez des configurations d'agent réutilisables.",+ "tr": "Yeniden kullanılabilir ajan kurulumları oluşturun ve yönetin.",+ "de": "Erstellen und verwalten Sie wiederverwendbare Agenten-Setups.",+ "uk": "Створюйте та керуйте багаторазовими налаштуваннями агента.",+ "ca": "Crea i gestiona configuracions d'agent reutilitzables."+ },+ "SETTINGS$ADD_AGENT_PROFILE": {+ "en": "Add agent profile",+ "ja": "エージェントプロファイルを追加",+ "zh-CN": "添加代理配置文件",+ "zh-TW": "新增代理設定檔",+ "ko-KR": "에이전트 프로필 추가",+ "no": "Legg til agentprofil",+ "it": "Aggiungi profilo agente",+ "pt": "Adicionar perfil de agente",+ "es": "Agregar perfil de agente",+ "ar": "إضافة ملف تعريف الوكيل",+ "fr": "Ajouter un profil d'agent",+ "tr": "Ajan profili ekle",+ "de": "Agentenprofil hinzufügen",+ "uk": "Додати профіль агента",+ "ca": "Afegeix un perfil d'agent"+ },+ "SETTINGS$EDIT_AGENT_PROFILE": {+ "en": "Edit agent profile",+ "ja": "エージェントプロファイルを編集",+ "zh-CN": "编辑代理配置文件",+ "zh-TW": "編輯代理設定檔",+ "ko-KR": "에이전트 프로필 편집",+ "no": "Rediger agentprofil",+ "it": "Modifica profilo agente",+ "pt": "Editar perfil de agente",+ "es": "Editar perfil de agente",+ "ar": "تعديل ملف تعريف الوكيل",+ "fr": "Modifier le profil d'agent",+ "tr": "Ajan profilini düzenle",+ "de": "Agentenprofil bearbeiten",+ "uk": "Редагувати профіль агента",+ "ca": "Edita el perfil d'agent"+ },+ "SETTINGS$AGENT_PROFILE_LLM_LABEL": {+ "en": "LLM profile",+ "ja": "LLMプロファイル",+ "zh-CN": "LLM配置文件",+ "zh-TW": "LLM設定檔",+ "ko-KR": "LLM 프로필",+ "no": "LLM-profil",+ "it": "Profilo LLM",+ "pt": "Perfil LLM",+ "es": "Perfil LLM",+ "ar": "ملف تعريف LLM",+ "fr": "Profil LLM",+ "tr": "LLM profili",+ "de": "LLM-Profil",+ "uk": "Профіль LLM",+ "ca": "Perfil LLM"+ },+ "SETTINGS$AGENT_PROFILE_LLM_REQUIRED": {+ "en": "Select an LLM profile for this agent.",+ "ja": "このエージェントのLLMプロファイルを選択してください。",+ "zh-CN": "请为此代理选择一个LLM配置文件。",+ "zh-TW": "請為此代理選擇一個LLM設定檔。",+ "ko-KR": "이 에이전트의 LLM 프로필을 선택하세요.",+ "no": "Velg en LLM-profil for denne agenten.",+ "it": "Seleziona un profilo LLM per questo agente.",+ "pt": "Selecione um perfil LLM para este agente.",+ "es": "Selecciona un perfil LLM para este agente.",+ "ar": "اختر ملف تعريف LLM لهذا الوكيل.",+ "fr": "Sélectionnez un profil LLM pour cet agent.",+ "tr": "Bu ajan için bir LLM profili seçin.",+ "de": "Wählen Sie ein LLM-Profil für diesen Agenten.",+ "uk": "Виберіть профіль LLM для цього агента.",+ "ca": "Selecciona un perfil LLM per a aquest agent."+ },+ "SETTINGS$AGENT_PROFILE_NO_LLM": {+ "en": "Create an LLM profile first to define an OpenHands agent.",+ "ja": "OpenHandsエージェントを定義するには、まずLLMプロファイルを作成してください。",+ "zh-CN": "请先创建一个LLM配置文件以定义OpenHands代理。",+ "zh-TW": "請先建立一個LLM設定檔以定義OpenHands代理。",+ "ko-KR": "OpenHands 에이전트를 정의하려면 먼저 LLM 프로필을 만드세요.",+ "no": "Opprett en LLM-profil først for å definere en OpenHands-agent.",+ "it": "Crea prima un profilo LLM per definire un agente OpenHands.",+ "pt": "Crie primeiro um perfil LLM para definir um agente OpenHands.",+ "es": "Crea primero un perfil LLM para definir un agente OpenHands.",+ "ar": "أنشئ ملف تعريف LLM أولاً لتعريف وكيل OpenHands.",+ "fr": "Créez d'abord un profil LLM pour définir un agent OpenHands.",+ "tr": "Bir OpenHands ajanı tanımlamak için önce bir LLM profili oluşturun.",+ "de": "Erstellen Sie zuerst ein LLM-Profil, um einen OpenHands-Agenten zu definieren.",+ "uk": "Спочатку створіть профіль LLM, щоб визначити агента OpenHands.",+ "ca": "Crea primer un perfil LLM per definir un agent OpenHands."+ },+ "CHAT$AGENT_PROFILE_PLACEHOLDER": {+ "en": "Agent profile",+ "ja": "エージェントプロファイル",+ "zh-CN": "代理配置文件",+ "zh-TW": "代理設定檔",+ "ko-KR": "에이전트 프로필",+ "no": "Agentprofil",+ "it": "Profilo agente",+ "pt": "Perfil de agente",+ "es": "Perfil de agente",+ "ar": "ملف تعريف الوكيل",+ "fr": "Profil d'agent",+ "tr": "Ajan profili",+ "de": "Agentenprofil",+ "uk": "Профіль агента",+ "ca": "Perfil d'agent"+ },+ "CHAT$MANAGE_AGENT_PROFILES": {+ "en": "Manage agent profiles",+ "ja": "エージェントプロファイルを管理",+ "zh-CN": "管理代理配置文件",+ "zh-TW": "管理代理設定檔",+ "ko-KR": "에이전트 프로필 관리",+ "no": "Administrer agentprofiler",+ "it": "Gestisci profili agente",+ "pt": "Gerenciar perfis de agente",+ "es": "Gestionar perfiles de agente",+ "ar": "إدارة ملفات تعريف الوكيل",+ "fr": "Gérer les profils d'agent",+ "tr": "Ajan profillerini yönet",+ "de": "Agentenprofile verwalten",+ "uk": "Керувати профілями агента",+ "ca": "Gestiona els perfils d'agent"+ },"SETTINGS$ENABLE_MEMORY_CONDENSATION": {"en": "Enable memory condensation","ja": "メモリ凝縮を有効にする",@@ -30021,6 +30174,40 @@"uk": "Встановити як активний","ca": "Establir com a actiu"},+ "SETTINGS$PROFILE_DEFAULT": {+ "en": "Default",+ "ja": "デフォルト",+ "zh-CN": "默认",+ "zh-TW": "預設",+ "ko-KR": "기본값",+ "no": "Standard",+ "it": "Predefinito",+ "pt": "Padrão",+ "es": "Predeterminado",+ "ar": "افتراضي",+ "fr": "Par défaut",+ "tr": "Varsayılan",+ "de": "Standard",+ "uk": "За замовчуванням",+ "ca": "Predeterminat"+ },+ "SETTINGS$PROFILE_SET_DEFAULT": {+ "en": "Set as default",+ "ja": "デフォルトに設定",+ "zh-CN": "设为默认",+ "zh-TW": "設為預設",+ "ko-KR": "기본값으로 설정",+ "no": "Angi som standard",+ "it": "Imposta come predefinito",+ "pt": "Definir como padrão",+ "es": "Establecer como predeterminado",+ "ar": "تعيين كافتراضي",+ "fr": "Définir par défaut",+ "tr": "Varsayılan olarak ayarla",+ "de": "Als Standard festlegen",+ "uk": "Зробити за замовчуванням",+ "ca": "Estableix com a predeterminat"+ },"SETTINGS$PROFILE_EDIT": {"en": "Edit","ja": "編集",diff --git a/src/routes.ts b/src/routes.tsindex 955e2dc2d4..c078266a21 100644--- a/src/routes.ts+++ b/src/routes.ts@@ -23,6 +23,7 @@ export default [index("routes/settings-index.tsx"),route("llm", "routes/llm-settings.tsx"),route("agent", "routes/agent-settings.tsx"),+ route("agents", "routes/agent-profiles-settings.tsx"),route("condenser", "routes/condenser-settings.tsx"),route("verification", "routes/verification-settings.tsx"),route("app", "routes/app-settings.tsx"),diff --git a/src/routes/agent-profiles-settings.tsx b/src/routes/agent-profiles-settings.tsxnew file mode 100644index 0000000000..38c22ed6dc--- /dev/null+++ b/src/routes/agent-profiles-settings.tsx@@ -0,0 +1,15 @@+import { AgentProfilesLocalView } from "#/components/features/settings/agent-profiles";++export const handle = { hideTitle: false };++/**+ * Settings → Agent profiles. A library of named agent setups, reusing the+ * existing Agent settings form as the editor. Available on both local and+ * cloud backends — the cloud enterprise app-server exposes the same+ * `/api/agent-profiles` surface (OpenHands #15060, epic #3730), and+ * `AgentProfilesService` routes cloud calls through the cloud proxy. The view+ * name is historical ("LocalView"); it is backend-agnostic.+ */+export default function AgentProfilesSettingsRoute() {+ return <AgentProfilesLocalView />;+}diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex fa77f2e209..7453742374 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -1,4 +1,5 @@-import React, { useEffect, useRef, useState } from "react";+import React, { useCallback, useEffect, useRef, useState } from "react";+import { Navigate } from "react-router";import { useTranslation } from "react-i18next";import { AxiosError } from "axios";import { useSettings } from "#/hooks/query/use-settings";@@ -18,7 +19,6 @@ import { cn } from "#/utils/utils";import { SettingsFieldSchema, SettingsValue } from "#/types/settings";import {coerceFieldValue,- getAgentSettingValue,normalizeFieldValue,} from "#/utils/sdk-settings-schema";import {@@ -91,9 +91,153 @@ function isKnownAcpModel();}-function AgentSettingsScreen() {+/**+ * Variant-specific AgentProfile fields derived from the form state. The+ * OpenHands branch omits `llm_profile_ref` — the profile editor supplies it.+ */+export type AgentProfileFieldsDraft =+ | {+ agent_kind: "openhands";+ enable_sub_agents: boolean;+ tool_concurrency_limit?: number;+ }+ | {+ agent_kind: "acp";+ acp_server: string;+ acp_model: string | null;+ acp_command: string | null;+ acp_args: string[] | null;+ };++/** Live form state the pure {@link buildAgentProfileFields} builder reads. */+export interface AgentProfileFieldsInput {+ isAcp: boolean;+ /** Detected ACP preset: a provider key or the ``custom`` sentinel. */+ selectedPreset: string;+ /** True when the command exactly matches the selected provider's default. */+ isDefaultProviderCommand: boolean;+ commandTokens: string[];+ acpModel: string;+ subAgentsEnabled: boolean;+ toolConcurrencyField?: SettingsFieldSchema;+ toolConcurrency: string | boolean;+}++/**+ * Translate the live Agent-settings form state into the variant-specific+ * AgentProfile fields. Pure (no React), so it can be unit-tested directly.+ *+ * ACP: a built-in provider on its default command stores **no** explicit+ * command (``acp_command: null`` — the profile resolver falls back to the+ * provider default); a customized or ``custom`` command is stored verbatim as a+ * shell string. OpenHands: reuses the schema-driven ``tool_concurrency_limit``+ * coercion, which **throws** on invalid input (callers catch at save time). A+ * blank concurrency field always emits an explicit value (the schema default+ * when the coercion is empty) rather than omitting the key — the profile+ * editor's save is a whole-profile overwrite (``mergeAgentProfileSaveInput``+ * spreads the stored profile under these fields), so omitting the key would+ * let a stale stored value silently survive an edit meant to clear it back to+ * the default (#1571 review). The backend field itself is a non-nullable+ * ``int`` with ``ge=1``, so the default — not ``null`` — is the value that+ * actually clears.+ */+export function buildAgentProfileFields(+ input: AgentProfileFieldsInput,+): AgentProfileFieldsDraft {+ const {+ isAcp,+ selectedPreset,+ isDefaultProviderCommand,+ commandTokens,+ acpModel,+ subAgentsEnabled,+ toolConcurrencyField,+ toolConcurrency,+ } = input;+ if (isAcp) {+ const isBuiltinDefault =+ isDefaultProviderCommand && selectedPreset !== ACP_CUSTOM_PRESET_KEY;+ return {+ agent_kind: "acp",+ acp_server: selectedPreset,+ acp_model: acpModel.trim() || null,+ acp_command: isBuiltinDefault+ ? null+ : formatCommand(commandTokens) || null,+ acp_args: null,+ };+ }+ const fields: Extract<AgentProfileFieldsDraft, { agent_kind: "openhands" }> =+ {+ agent_kind: "openhands",+ enable_sub_agents: subAgentsEnabled,+ };+ if (toolConcurrencyField) {+ // Reuse the schema-driven coercion/validation; throws on bad input.+ const coerced = coerceFieldValue(toolConcurrencyField, toolConcurrency);+ // A blank field coerces to `null`. Always emit an explicit value — never+ // omit the key — so a deliberate clear on an edit-save actually resets the+ // stored profile to the schema default, instead of the whole-profile merge+ // silently carrying the old value forward.+ const fallback =+ typeof toolConcurrencyField.default === "number"+ ? toolConcurrencyField.default+ : 1;+ fields.tool_concurrency_limit =+ coerced != null ? Number(coerced) : fallback;+ }+ return fields;+}++/**+ * Handle the embedded form exposes to its parent (the Agent-profile editor) so+ * it can read the current state and persist it as an AgentProfile.+ */+export interface AgentSettingsSaveControl {+ agentType: AgentType;+ /** False when the current form can't be saved (e.g. an empty ACP command). */+ isValid: boolean;+ /**+ * Build the variant-specific AgentProfile fields from the live form state.+ * Throws a user-facing Error on invalid input (e.g. a bad concurrency value).+ */+ buildAgentProfileFields: () => AgentProfileFieldsDraft;+ /** Shared ACP credential form (writes to global secrets). */+ credentials: {+ isDirty: boolean;+ save: (opts?: { silent?: boolean }) => Promise<boolean>;+ reset: () => void;+ };+}++interface AgentSettingsScreenProps {+ /**+ * Embedded mode reuses this form as the Agent-profile editor: it hides the+ * page header + the global Save button, seeds from `agentSettingsOverride`+ * instead of the live global settings, and reports its state through+ * `onSaveControlChange` so the parent can persist it as an AgentProfile.+ */+ embedded?: boolean;+ /**+ * When set (embedded mode), seed the form from this `agent_settings`-shaped+ * object instead of the live global settings — lets the editor open on a+ * stored profile's fields.+ */+ agentSettingsOverride?: Record<string, SettingsValue> | null;+ onSaveControlChange?: (control: AgentSettingsSaveControl) => void;+}++export function AgentSettingsScreen({+ embedded = false,+ agentSettingsOverride = null,+ onSaveControlChange,+}: AgentSettingsScreenProps = {}) {const { t } = useTranslation("openhands");const { data: settings, isLoading } = useSettings();+ // In embedded (profile-editor) mode the parent seeds the form from a stored+ // profile via `agentSettingsOverride`; otherwise use the live global settings.+ const agentSettingsSource: Record<string, SettingsValue> | null =+ agentSettingsOverride ?? settings?.agent_settings ?? null;const { mutate: saveSettings, isPending: isSaving } = useSaveSettings();const { data: schema } = useAgentSettingsSchema(settings?.agent_settings_schema,@@ -108,10 +252,10 @@ function AgentSettingsScreen() {const initialSubAgentsEnabled = React.useMemo(() =>getEnableSubAgentsValue(- settings?.agent_settings?.[ENABLE_SUB_AGENTS_FIELD_KEY],+ agentSettingsSource?.[ENABLE_SUB_AGENTS_FIELD_KEY],subAgentsField,),- [subAgentsField, settings?.agent_settings],+ [subAgentsField, agentSettingsSource],);const [subAgentsEnabled, setSubAgentsEnabled] = useState(initialSubAgentsEnabled,@@ -125,11 +269,9 @@ function AgentSettingsScreen() {);const initialToolConcurrency = React.useMemo(() => {if (!toolConcurrencyField) return "";- const raw = settings- ? getAgentSettingValue(settings, TOOL_CONCURRENCY_FIELD_KEY)- : undefined;+ const raw = agentSettingsSource?.[TOOL_CONCURRENCY_FIELD_KEY];return normalizeFieldValue(toolConcurrencyField, raw);- }, [toolConcurrencyField, settings]);+ }, [toolConcurrencyField, agentSettingsSource]);const [toolConcurrency, setToolConcurrency] = useState<string | boolean>(initialToolConcurrency,);@@ -159,27 +301,30 @@ function AgentSettingsScreen() {const loadedCommandTextRef = useRef<string>("");useEffect(() => {- if (!settings) return;- if (lastInitializedSettingsRef.current === settings) return;+ // Seed from the profile override (embedded) or the live global settings.+ const source = agentSettingsOverride ?? settings?.agent_settings ?? null;+ if (!source && !settings) return;+ const initIdentity = agentSettingsOverride ?? settings;+ if (lastInitializedSettingsRef.current === initIdentity) return;- lastInitializedSettingsRef.current = settings;- const kind = settings.agent_settings?.agent_kind;+ lastInitializedSettingsRef.current = initIdentity;+ const kind = source?.agent_kind;if (kind === "acp") {setAgentType("acp");- const rawAcpServer = settings.agent_settings?.acp_server;+ const rawAcpServer = source?.acp_server;const acpServer =typeof rawAcpServer === "string" ? rawAcpServer : undefined;const provider = getAcpProvider(acpServer);- const storedCommand = toStringArray(settings.agent_settings?.acp_command);+ const storedCommand = toStringArray(source?.acp_command);const effectiveBaseCommand =storedCommand.length > 0? storedCommand: (provider?.default_command ?? []);const tokens = [...effectiveBaseCommand,- ...toStringArray(settings.agent_settings?.acp_args),+ ...toStringArray(source?.acp_args),];const renderedCommandText =tokens.length > 0 ? formatCommand(tokens) : "";@@ -187,7 +332,7 @@ function AgentSettingsScreen() {loadedAcpServerRef.current = acpServer ?? null;loadedCommandTextRef.current = renderedCommandText;- const savedModel = settings.agent_settings?.acp_model;+ const savedModel = source?.acp_model;const normalizedSavedModel =typeof savedModel === "string" ? savedModel.trim() : "";setAcpModel(@@ -206,7 +351,7 @@ function AgentSettingsScreen() {setIsCustomAcpModel(false);}setIsDirty(false);- }, [settings]);+ }, [settings, agentSettingsOverride]);// Sync the sub-agents toggle when settings reloaduseEffect(() => {@@ -218,6 +363,51 @@ function AgentSettingsScreen() {setToolConcurrency(initialToolConcurrency);}, [initialToolConcurrency]);+ // --- Embedded (Agent-profile editor) save control ---+ // Ref-backed so the exposed builder/credential fns read the freshest state at+ // call time without re-emitting the control on every keystroke (mirrors+ // ``sdk-section-page``). The body is (re)assigned during render below.+ const buildFieldsRef = useRef<() => AgentProfileFieldsDraft>(() => ({+ agent_kind: "openhands",+ enable_sub_agents: false,+ }));+ const stableBuildFields = useCallback(() => buildFieldsRef.current(), []);+ const credFormRef = useRef(acpCredentialForm);+ credFormRef.current = acpCredentialForm;+ const stableCredSave = useCallback(+ (opts?: { silent?: boolean }) => credFormRef.current.save(opts),+ [],+ );+ const stableCredReset = useCallback(() => credFormRef.current.reset(), []);++ // Validity/kind are computed here (before the loading early-return) so the+ // emit effect can depend on them; the full ACP derivation lives after it.+ const acpCommandEmpty =+ agentType === "acp" && parseCommand(commandText).length === 0;+ const embeddedCredentialsDirty = acpCredentialForm.isDirty;+ useEffect(() => {+ if (!embedded || !onSaveControlChange) return;+ onSaveControlChange({+ agentType,+ isValid: !acpCommandEmpty,+ buildAgentProfileFields: stableBuildFields,+ credentials: {+ isDirty: embeddedCredentialsDirty,+ save: stableCredSave,+ reset: stableCredReset,+ },+ });+ }, [+ embedded,+ onSaveControlChange,+ agentType,+ acpCommandEmpty,+ embeddedCredentialsDirty,+ stableBuildFields,+ stableCredSave,+ stableCredReset,+ ]);+if (isLoading) return null;const isAcp = agentType === "acp";@@ -239,6 +429,22 @@ function AgentSettingsScreen() {formatCommand(ACP_PROVIDERS[0]?.default_command ?? []) ||COMMAND_PLACEHOLDER_FALLBACK;+ // Assign the embedded control's field builder from the live render state.+ // The mapping itself lives in the pure `buildAgentProfileFields` (unit-+ // tested); this closure just snapshots the current state. Throws only when+ // called (at save time), never during render.+ buildFieldsRef.current = (): AgentProfileFieldsDraft =>+ buildAgentProfileFields({+ isAcp,+ selectedPreset,+ isDefaultProviderCommand,+ commandTokens,+ acpModel,+ subAgentsEnabled,+ toolConcurrencyField,+ toolConcurrency,+ });+// Dirty tracking: for OpenHands path, also check sub-agents toggle and the// parallel-tool-calls input.const isOpenHandsDirty =@@ -370,14 +576,16 @@ function AgentSettingsScreen() {data-testid="agent-settings-screen"className="flex flex-col gap-6 pb-8 max-w-2xl">- <div>- <Typography.H2 className="mb-2">- {t(I18nKey.SETTINGS$NAV_AGENT)}- </Typography.H2>- <Typography.Paragraph className="text-sm text-[#A3A3A3]">- {t(I18nKey.SETTINGS$AGENT_PAGE_DESCRIPTION)}- </Typography.Paragraph>- </div>+ {!embedded && (+ <div>+ <Typography.H2 className="mb-2">+ {t(I18nKey.SETTINGS$NAV_AGENT)}+ </Typography.H2>+ <Typography.Paragraph className="text-sm text-[#A3A3A3]">+ {t(I18nKey.SETTINGS$AGENT_PAGE_DESCRIPTION)}+ </Typography.Paragraph>+ </div>+ )}<SettingsDropdownInputtestId="agent-type-selector"@@ -584,21 +792,38 @@ function AgentSettingsScreen() {</>)}- <div>- <BrandButton- testId="agent-save-button"- type="button"- variant="primary"- isDisabled={isSavingAny || !isAnyDirty || isAcpInvalid}- onClick={handleSave}- >- {isSavingAny- ? t(I18nKey.SETTINGS$SAVING)- : t(I18nKey.SETTINGS$SAVE_CHANGES)}- </BrandButton>- </div>+ {!embedded && (+ <div>+ <BrandButton+ testId="agent-save-button"+ type="button"+ variant="primary"+ isDisabled={isSavingAny || !isAnyDirty || isAcpInvalid}+ onClick={handleSave}+ >+ {isSavingAny+ ? t(I18nKey.SETTINGS$SAVING)+ : t(I18nKey.SETTINGS$SAVE_CHANGES)}+ </BrandButton>+ </div>+ )}</div>);}-export default AgentSettingsScreen;+/**+ * Legacy `/settings/agent` route. Settings → Agent is now the Agent Profile+ * library (`/settings/agents`), whose editor reuses the named+ * `AgentSettingsScreen` export below; this global-agent-form route is retired+ * and redirects there so old links/bookmarks keep working.+ *+ * Note: This is a route file; only the router should import the default export.+ * React Router's Vite plugin wraps a route's default export with+ * `withComponentProps`, which invokes it with route props and drops any props+ * passed by a parent — so embedded consumers (the Agent-profile editor) MUST+ * import the named `AgentSettingsScreen` export instead, or `embedded` /+ * `onSaveControlChange` never arrive. Mirrors `LlmSettingsRoute`.+ */+export default function AgentSettingsRoute() {+ return <Navigate to="/settings/agents" replace />;+}diff --git a/src/routes/settings.tsx b/src/routes/settings.tsxindex 0f787d8961..6d5393d181 100644--- a/src/routes/settings.tsx+++ b/src/routes/settings.tsx@@ -39,7 +39,7 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {// ACP guard: the pages flagged ``disabledByAcp`` (LLM, Condenser, …)// have no useful content while an external ACP subprocess drives- // conversations. Bounce them to ``/settings/agent``. Driven by the+ // conversations. Bounce them to ``/settings/agents``. Driven by the// same ``disabledByAcp`` flag the nav hook uses for greying out, so// the list of redirected paths and the greyed-out paths can never// drift apart. See {@link redirectIfAcpActive} for why the redirectdiff --git a/src/utils/acp-route-guard.ts b/src/utils/acp-route-guard.tsindex b5e9edd5ed..157c39e4b5 100644--- a/src/utils/acp-route-guard.ts+++ b/src/utils/acp-route-guard.ts@@ -2,11 +2,16 @@ import { redirect } from "react-router";import { getActiveBackend } from "#/api/backend-registry/active-store";import { getSettingsQueryFn } from "#/hooks/query/use-settings";-import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";+import {+ SETTINGS_QUERY_KEYS,+ AGENT_PROFILES_QUERY_KEYS,+ AGENT_PROFILES_RETRY_OPTIONS,+} from "#/hooks/query/query-keys";+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";import { queryClient } from "#/query-client-config";/**- * Issue a ``redirect`` to ``/settings/agent`` when the personal settings+ * Issue a ``redirect`` to ``/settings/agents`` when the personal settings* say the active agent is ACP.** The ACP sub-agent owns its own LLM and condenser, so the canvas-side@@ -34,17 +39,49 @@ import { queryClient } from "#/query-client-config";export async function redirectIfAcpActive() {try {const active = getActiveBackend();- const personalSettings = await queryClient.fetchQuery({- queryKey: [- ...SETTINGS_QUERY_KEYS.byScope("personal"),- active.backend.id,- active.orgId,- ],- queryFn: () => getSettingsQueryFn("personal"),- staleTime: 0,- });- if (personalSettings?.agent_settings?.agent_kind === "acp") {- return redirect("/settings/agent");+ // The active AgentProfile is the current agent (activate is pointer-only+ // and never writes agent_settings), so it's the authoritative ACP signal.+ // Fall back to the global agent settings when the profile list is+ // unavailable (older backend, fetch error) so behavior degrades gracefully.+ let isAcp: boolean | undefined;+ try {+ const profiles = await queryClient.fetchQuery({+ queryKey: [+ ...AGENT_PROFILES_QUERY_KEYS.all,+ active.backend.id,+ active.orgId,+ ],+ queryFn: AgentProfilesService.listProfiles,+ staleTime: 0,+ // A backend without the surface fails this on every settings+ // navigation — degrade to the agent_settings fallback below+ // immediately rather than sitting through the default backoff.+ ...AGENT_PROFILES_RETRY_OPTIONS,+ });+ const activeId = profiles?.active_agent_profile_id ?? null;+ const activeProfile = profiles?.profiles.find(+ (profile) => profile.id != null && profile.id === activeId,+ );+ if (activeProfile) isAcp = activeProfile.agent_kind === "acp";+ } catch {+ // Agent profiles unavailable — fall back to settings below.+ }++ if (isAcp === undefined) {+ const personalSettings = await queryClient.fetchQuery({+ queryKey: [+ ...SETTINGS_QUERY_KEYS.byScope("personal"),+ active.backend.id,+ active.orgId,+ ],+ queryFn: () => getSettingsQueryFn("personal"),+ staleTime: 0,+ });+ isAcp = personalSettings?.agent_settings?.agent_kind === "acp";+ }++ if (isAcp) {+ return redirect("/settings/agents");}} catch {// Settings unfetchable — let the page render.diff --git a/src/utils/settings-utils.ts b/src/utils/settings-utils.tsindex 5a0a30f32b..451f8abf41 100644--- a/src/utils/settings-utils.ts+++ b/src/utils/settings-utils.ts@@ -60,14 +60,14 @@ export function isSettingsPageHidden(export function getFirstAvailablePath(featureFlags: WebClientFeatureFlags | undefined,): string | null {- // ``/settings/agent`` always wins: it is the single place to switch- // agent kinds (OpenHands / ACP) and the only sub-page that is always- // available regardless of feature flags. Landing here keeps the- // routing simple — ACP users no longer have to bounce through- // ``/settings/llm`` (which is disabled for them), and OpenHands users- // are one nav-click away from the LLM page.+ // ``/settings/agents`` (the Agent Profile library — the "Agent" page) always+ // wins: it is where the agent is defined (OpenHands / ACP, via the active+ // profile) and is always available regardless of feature flags. Landing here+ // keeps routing simple — ACP users no longer have to bounce through+ // ``/settings/llm`` (which is disabled for them), and OpenHands users are one+ // nav-click away from the LLM page.const fallbackOrder = [- { path: "/settings/agent", hidden: false },+ { path: "/settings/agents", hidden: false },{ path: "/settings/llm", hidden: !!featureFlags?.hide_llm_settings },{ path: "/settings", hidden: !!featureFlags?.hide_llm_settings },{ path: "/settings/app", hidden: false },diff --git a/tests/e2e/mock-llm/conversations/mock-llm-conversation.spec.ts b/tests/e2e/mock-llm/conversations/mock-llm-conversation.spec.tsindex 934b3cf3b9..78e21b60b5 100644--- a/tests/e2e/mock-llm/conversations/mock-llm-conversation.spec.ts+++ b/tests/e2e/mock-llm/conversations/mock-llm-conversation.spec.ts@@ -38,6 +38,7 @@ import {deleteConversation,resetMockLLM,setChatInput,+ ensureMockLLMAgentProfile,} from "../utils/mock-llm-helpers";const PROFILE_NAME = "mock-llm-e2e";@@ -235,6 +236,13 @@ test.describe("mock-LLM agent-server conversation", () => {`Expected settings llm.base_url="${MOCK_LLM_AGENT_URL}" but got "${llmBaseUrl}"`,).toBe(MOCK_LLM_AGENT_URL);});++ // Point the active agent profile at this LLM profile so the home composer+ // is unblocked in step 3. Conversations launch from the active AGENT+ // profile (#1571), whose `llm_profile_ref` — not the active LLM profile —+ // gates the composer; onboarding does this for real users, but this spec+ // seeds `openhands-onboarded` and configures the LLM directly.+ await ensureMockLLMAgentProfile(request, PROFILE_NAME);});// ── Step 3: Start a conversation and verify the mock agent responds ─diff --git a/tests/e2e/mock-llm/settings/mock-llm-acp-agent.spec.ts b/tests/e2e/mock-llm/settings/mock-llm-acp-agent.spec.tsindex 2351e409fe..a69d1dd61f 100644--- a/tests/e2e/mock-llm/settings/mock-llm-acp-agent.spec.ts+++ b/tests/e2e/mock-llm/settings/mock-llm-acp-agent.spec.ts@@ -32,6 +32,7 @@ import {resetToOpenHandsAgentViaUI,resetMockLLM,ensureMockLLMProfile,+ openAgentProfileEditor,selectDropdownOption,setChatInput,BACKEND_URL,@@ -99,12 +100,9 @@ test.describe("mock-LLM ACP agent conversation", () => {// don't fail. This UI flow is not what we're testing — the ACP UI is.await ensureMockLLMProfile(page);- await routeSessionApiKey(page);- await page.goto("/settings/agent", { waitUntil: "domcontentloaded" });- await dismissAnalyticsModal(page);-- // Wait for the agent settings form to load- await waitForTestId(page, "agent-settings-screen");+ // Settings → Agent is the Agent Profile library (#1571); edit the+ // seeded "default" profile through it rather than a standalone form.+ await openAgentProfileEditor(page, "default");// ── Switch agent type from OpenHands → ACP ──@@ -139,41 +137,37 @@ test.describe("mock-LLM ACP agent conversation", () => {// ── Save the configuration ──await test.step("save agent settings", async () => {- const saveBtn = page.getByTestId("agent-save-button");+ const saveBtn = page.getByTestId("save-agent-profile-btn");await expect(saveBtn).toBeEnabled({ timeout: 5_000 });await saveBtn.click();- // Wait for the save to complete — the button text changes briefly- // to "Saving..." and then back to "Save Changes", and becomes- // disabled again (isDirty flips to false).- await expect(saveBtn).toBeDisabled({ timeout: 10_000 });+ // A successful save returns the editor to the profile list.+ await waitForTestId(page, "add-agent-profile", 10_000);});- // ── Verify: settings API reflects the ACP configuration ──+ // ── Verify: agent-profiles API reflects the ACP configuration ──- await test.step("verify settings API reflects ACP config", async () => {- const resp = await request.get(`${BACKEND_URL}/api/settings`, {- headers: {- "X-Session-API-Key": SESSION_API_KEY,- "X-Expose-Secrets": "encrypted",+ await test.step("verify agent-profiles API reflects ACP config", async () => {+ const resp = await request.get(+ `${BACKEND_URL}/api/agent-profiles/default`,+ {+ headers: { "X-Session-API-Key": SESSION_API_KEY },},- });- expect(resp.ok(), `GET /api/settings returned ${resp.status()}`).toBe(- true,);- const settings = await resp.json();- const agentSettings = settings?.agent_settings as Record<string, unknown>;- expect(agentSettings?.agent_kind).toBe("acp");-- const command = agentSettings?.acp_command;expect(- Array.isArray(command),- `acp_command should be an array, got: ${JSON.stringify(command)}`,+ resp.ok(),+ `GET /api/agent-profiles/default returned ${resp.status()}`,).toBe(true);+ const detail = await resp.json();+ const profile = detail?.profile as Record<string, unknown>;+ expect(profile?.agent_kind).toBe("acp");++ // The agent-profiles API stores acp_command as a shell string+ // (ts-client `AgentProfile.acp_command: string | null`), unlike the+ // legacy `/api/settings` which exposed a token array.+ const command = profile?.acp_command;expect(- (command as string[]).some((tok: string) =>- tok.includes("mock-acp-server.py"),- ),+ typeof command === "string" && command.includes("mock-acp-server.py"),`acp_command should reference mock-acp-server.py, got: ${JSON.stringify(command)}`,).toBe(true);});@@ -184,10 +178,9 @@ test.describe("mock-LLM ACP agent conversation", () => {test("step 2: reload and verify ACP settings are persisted in UI", async ({page,}) => {- await routeSessionApiKey(page);- await page.goto("/settings/agent", { waitUntil: "domcontentloaded" });- await dismissAnalyticsModal(page);- await waitForTestId(page, "agent-settings-screen");+ // Settings → Agent is the Agent Profile library (#1571); re-open the+ // "default" profile's editor rather than a standalone form.+ await openAgentProfileEditor(page, "default");// The command textarea should show the mock server commandconst commandInput = page.getByTestId("agent-command-input");@@ -245,25 +238,27 @@ test.describe("mock-LLM ACP agent conversation", () => {page.off("request", capturePayload);conversationId = getConversationIdFromURL(page);- // ── Verify: POST /api/conversations payload has ACP agent settings ──+ // ── Verify: the conversation launched from the active (ACP) profile ──+ // Conversations now launch from the active AgentProfile (#1571): the+ // payload carries `agent_profile_id` and omits `agent_settings` (the two+ // are mutually exclusive). Step 1 switched the active "default" profile to+ // ACP, so this launch uses it — the ACP reply token below confirms the ACP+ // agent actually ran.- await test.step("verify conversation payload contains ACP settings", async () => {+ await test.step("verify conversation launched from the active agent profile", async () => {expect(capturedPayload,"POST /api/conversations payload was not captured",).not.toBeNull();- const agentSettings = capturedPayload!.agent_settings as- | Record<string, unknown>- | undefined;expect(- agentSettings,- "payload should contain agent_settings",+ capturedPayload!.agent_profile_id,+ `Expected agent_profile_id in payload, got: ${JSON.stringify(capturedPayload)}`,).toBeTruthy();expect(- agentSettings!.agent_kind,- `Expected agent_kind="acp" in payload, got: ${agentSettings!.agent_kind}`,- ).toBe("acp");+ capturedPayload!.agent_settings,+ "agent_settings must be omitted when launching from a profile",+ ).toBeUndefined();});// ── Verify: agent reply contains the ACP reply token ──diff --git a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.tsindex a65f13f9cd..590b5c6a60 100644--- a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts+++ b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts@@ -330,13 +330,16 @@ test.describe("same-model profile identity", () => {// ── Verify: profile switcher shows BETA, not ALPHA ──await test.step("profile switcher shows the correct profile name", async () => {- const switchButton = page.getByTestId("switch-profile-button");- await expect(switchButton).toBeVisible({ timeout: 10_000 });- // The button's visible text should contain PROFILE_BETA.+ // In a local OpenHands conversation the chat input renders the+ // in-conversation LLM-profile picker, whose label is the active+ // profile name (replaces the former switch-profile-button).+ const profilePicker = page.getByTestId("chat-input-llm-profile");+ await expect(profilePicker).toBeVisible({ timeout: 10_000 });+ // The picker's visible text should contain PROFILE_BETA.// Before the fix (PR #1123), it would show PROFILE_ALPHA because// profiles were matched by model name and .find() returned the// first alphabetical match.- await expect(switchButton).toContainText(PROFILE_BETA, {+ await expect(profilePicker).toContainText(PROFILE_BETA, {timeout: 10_000,});});@@ -348,10 +351,10 @@ test.describe("same-model profile identity", () => {// Re-wait for the conversation to loadawait waitForNonUserMessageText(page, REPLY_TOKEN, 30_000);- const switchButton = page.getByTestId("switch-profile-button");- await expect(switchButton).toBeVisible({ timeout: 10_000 });+ const profilePicker = page.getByTestId("chat-input-llm-profile");+ await expect(profilePicker).toBeVisible({ timeout: 10_000 });await expect(- switchButton,+ profilePicker,"Profile identity should persist across page reloads",).toContainText(PROFILE_BETA, { timeout: 10_000 });});diff --git a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts b/tests/e2e/mock-llm/utils/mock-llm-helpers.tsindex ee1e134e34..c50e1332c2 100644--- a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts+++ b/tests/e2e/mock-llm/utils/mock-llm-helpers.ts@@ -437,15 +437,100 @@ export async function ensureMockLLMProfile(await dismissAnalyticsModal(page);await waitForTestId(page, "add-llm-profile");- // If a profile with this name already exists, delete it first so we- // always start clean (other tests may have left stale config).- await deleteProfileIfExists(page, profileName);-- // ── Create the profile ──────────────────────────────────────────────- await createProfileViaUI(page, { profileName, model, apiKey, baseUrl });+ // ── Create the profile, or edit it in place if it already exists ────+ // Edit rather than delete-and-recreate: once the active agent profile+ // references this LLM profile (wired below via ensureMockLLMAgentProfile,+ // #1571), the LLMProfile FK guard rejects deletion and the delete-confirm+ // modal silently stays open, its backdrop blocking every later click.+ // Editing in place never deletes the profile (id/name stay stable), so it+ // sidesteps the FK guard while still converging onto the caller's+ // requested model/apiKey/baseUrl every time — a prior test in the same run+ // may have left a same-named profile configured for a *different* model+ // (e.g. image-upload's vision-capable override), so skipping the write+ // whenever the profile already exists silently keeps the wrong config.+ const exists =+ (await page+ .getByTestId("profile-row")+ .filter({ has: page.locator(`span[title="${profileName}"]`) })+ .count()) > 0;+ if (exists) {+ await editProfileViaUI(page, { profileName, model, apiKey, baseUrl });+ } else {+ await createProfileViaUI(page, { profileName, model, apiKey, baseUrl });+ }// ── Activate the profile ────────────────────────────────────────────await activateProfileViaUI(page, profileName);++ // ── Point the active agent profile at this LLM profile ──────────────+ // Conversations launch from the active AGENT profile (#1571), and the home+ // composer's "LLM ready" gate follows that profile's `llm_profile_ref` — not+ // the active LLM profile. The seeded "default" agent profile references a+ // keyless LLM, so activating an LLM profile alone leaves the composer+ // blocked. Mirror onboarding: wire the "default" agent profile to this key.+ await ensureMockLLMAgentProfile(page.request, profileName);+}++/**+ * Upsert + activate the well-known "default" agent profile so it references the+ * given LLM profile — the same thing onboarding does for a real user (#1571).+ *+ * Reusing the "default" name upserts the seeded profile (its id is preserved on+ * overwrite) rather than spawning a parallel one.+ */+export async function ensureMockLLMAgentProfile(+ request: APIRequestContext,+ llmProfileRef = "mock-llm",+) {+ const name = "default";+ const headers = {+ "X-Session-API-Key": SESSION_API_KEY,+ "Content-Type": "application/json",+ };++ const saveResp = await retryOnTransient(+ request,+ "POST",+ `${BACKEND_URL}/api/agent-profiles/${encodeURIComponent(name)}`,+ {+ headers,+ // disabled_skills omitted: an OpenHands profile launches with all+ // discovered skills by default (an empty deny-list) — software-agent-sdk#4017.+ data: {+ agent_kind: "openhands",+ llm_profile_ref: llmProfileRef,+ },+ },+ );+ expect(+ saveResp.ok(),+ `save agent profile "${name}": ${saveResp.status()}`,+ ).toBe(true);++ // Activate needs the stable id; the save response only echoes the name.+ const detailResp = await retryOnTransient(+ request,+ "GET",+ `${BACKEND_URL}/api/agent-profiles/${encodeURIComponent(name)}`,+ { headers },+ );+ expect(+ detailResp.ok(),+ `get agent profile "${name}": ${detailResp.status()}`,+ ).toBe(true);+ const id = (await detailResp.json())?.profile?.id as string | undefined;+ expect(id, `agent profile "${name}" id`).toBeTruthy();++ const activateResp = await retryOnTransient(+ request,+ "POST",+ `${BACKEND_URL}/api/agent-profiles/${encodeURIComponent(id!)}/activate`,+ { headers, data: {} },+ );+ expect(+ activateResp.ok(),+ `activate agent profile "${name}": ${activateResp.status()}`,+ ).toBe(true);}/**@@ -455,7 +540,12 @@ export async function ensureMockLLMProfile(* (the "add-llm-profile" button is visible). Does NOT activate the* profile — call `activateProfileViaUI` separately if needed.*/-export async function createProfileViaUI(+/**+ * Fill the LLM profile editor's fields and save. Shared by the create flow+ * ("Add LLM Profile") and the edit flow ("Edit" on an existing row) — both+ * land on the same editor form/testids.+ */+async function fillLlmProfileEditorAndSave(page: Page,{profileName,@@ -469,7 +559,6 @@ export async function createProfileViaUI(baseUrl?: string;},) {- await page.getByTestId("add-llm-profile").click();await waitForTestId(page, "profile-editor-title");const nameInput = page.getByTestId("profile-name-input");@@ -496,6 +585,47 @@ export async function createProfileViaUI(await waitForTestId(page, "add-llm-profile");}+/**+ * Create a new LLM profile and activate it through the Settings UI.+ * Assumes the page is already on /settings/llm with profiles loaded.+ */+export async function createProfileViaUI(+ page: Page,+ options: {+ profileName: string;+ model: string;+ apiKey?: string;+ baseUrl?: string;+ },+) {+ await page.getByTestId("add-llm-profile").click();+ await fillLlmProfileEditorAndSave(page, options);+}++/**+ * Edit an existing LLM profile's config (model/apiKey/baseUrl) through the+ * Settings UI. Assumes the page is already on /settings/llm with profiles+ * loaded and a profile named `options.profileName` exists.+ */+export async function editProfileViaUI(+ page: Page,+ options: {+ profileName: string;+ model: string;+ apiKey?: string;+ baseUrl?: string;+ },+) {+ const row = page+ .getByTestId("profile-row")+ .filter({ has: page.locator(`span[title="${options.profileName}"]`) })+ .first();+ await row.getByTestId("profile-menu-trigger").click();+ await waitForTestId(page, "profile-actions-menu");+ await page.getByTestId("profile-edit").click();+ await fillLlmProfileEditorAndSave(page, options);+}+/*** Delete a profile by name through the Settings UI if it exists.* Assumes the page is already on /settings/llm with profiles loaded.@@ -593,21 +723,57 @@ export async function selectDropdownOption(}/**- * Reset agent type back to OpenHands through the Settings → Agent UI.- * Used in afterAll cleanup to restore the default agent for subsequent tests.+ * Open the Settings → Agent profiles editor for a named profile.+ * Assumes the page can navigate freely (not already mid-flow elsewhere).+ *+ * Settings → Agent is now the Agent Profile library (#1571): the standalone+ * `/settings/agent` form was retired in favor of `/settings/agents`, whose+ * editor reuses the same embedded `agent-settings-screen` form. Locates the+ * row by the profile-name span's `title` attribute (mirrors `exactRow` in+ * `activateProfileViaUI` below) to avoid substring collisions between+ * profile names.*/-export async function resetToOpenHandsAgentViaUI(page: Page) {+export async function openAgentProfileEditor(page: Page, profileName: string) {await routeSessionApiKey(page);- await page.goto("/settings/agent", { waitUntil: "domcontentloaded" });+ await page.goto("/settings/agents", { waitUntil: "domcontentloaded" });await dismissAnalyticsModal(page);++ const row = page+ .getByTestId("agent-profile-row")+ .filter({ has: page.locator(`span[title="${profileName}"]`) })+ .first();+ await expect(row).toBeVisible({ timeout: 10_000 });+ await row.getByTestId("agent-profile-menu-trigger").click();+ await waitForTestId(page, "agent-profile-actions-menu");+ await page.getByTestId("agent-profile-edit").click();await waitForTestId(page, "agent-settings-screen");+}++/**+ * Reset agent type back to OpenHands through the Settings → Agent profiles UI.+ * Used in afterAll cleanup to restore the default agent for subsequent tests.+ */+export async function resetToOpenHandsAgentViaUI(page: Page) {+ await openAgentProfileEditor(page, "default");await selectDropdownOption(page, /Agent/, /OpenHands/);- const saveBtn = page.getByTestId("agent-save-button");+ // The LLM-profile selector only appears for openhands-kind profiles, and+ // is required to save — pick one if the switch left it unset.+ const llmSelector = page.getByRole("combobox", { name: /LLM/ });+ if (await llmSelector.isVisible().catch(() => false)) {+ const value = await llmSelector.inputValue().catch(() => "");+ if (!value) {+ await llmSelector.click();+ await page.getByRole("option").first().click();+ }+ }++ const saveBtn = page.getByTestId("save-agent-profile-btn");await expect(saveBtn).toBeEnabled({ timeout: 5_000 });await saveBtn.click();- await expect(saveBtn).toBeDisabled({ timeout: 10_000 });+ // A successful save returns the editor to the profile list.+ await waitForTestId(page, "add-agent-profile", 10_000);}/**diff --git a/vite.config.ts b/vite.config.tsindex d52f5d812d..7ba6f86586 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -41,6 +41,17 @@ const appBuildConfig = {output: {codeSplitting: {groups: [+ {+ // Keep the styling core (HeroUI + tailwind-variants + its+ // tailwind-merge/clsx deps) in one un-size-split chunk. When the+ // generic size-split vendor group slices these apart, a HeroUI+ // component's top-level `tv()` recipe can evaluate before+ // tailwind-variants' core is initialized, throwing+ // "TypeError: s is not a function" at module load and blanking the+ // whole app (root-layout module fails to load → reload loop).+ name: "vendor-styling",+ test: /node_modules[\\/](@heroui[\\/]|tailwind-variants[\\/]|tailwind-merge[\\/]|clsx[\\/])/,+ },{name: "vendor",test: /node_modules[\\/]/,