Skip to content

๐Ÿ™Œ OpenHands: AI-Driven Development

feat: always show the LLM selector; move agent-profile switching to the tools menu (#16099)

Hiep Le185ba90f1cd1
diff --git a/__tests__/components/context-menu/tools-context-menu.test.tsx b/__tests__/components/context-menu/tools-context-menu.test.tsx
index c7e089c2f2..ab5f748d1a 100644
--- a/__tests__/components/context-menu/tools-context-menu.test.tsx
+++ b/__tests__/components/context-menu/tools-context-menu.test.tsx
@@ -70,6 +70,27 @@ describe("SystemMessage UI Rendering", () => {
});
});
+describe("ToolsContextMenu - Switch agent profile", () => {
+ it("hides the Switch agent profile item unless the caller enables it", () => {
+ // The gate (pre-start only + profiles available) is owned by
+ // ChatInputActions; without the prop the item โ€” and its provider-backed
+ // submenu content โ€” must not mount.
+ render(
+ <ToolsContextMenu
+ onClose={() => {}}
+ onShowSkills={() => {}}
+ onShowPlugins={() => {}}
+ onShowHooks={() => {}}
+ onShowAgentTools={() => {}}
+ />,
+ );
+
+ expect(
+ screen.queryByTestId("switch-agent-profile-button"),
+ ).not.toBeInTheDocument();
+ });
+});
+
describe("ToolsContextMenu - Show Plugins", () => {
it("renders the Show Plugins item and calls onShowPlugins when clicked", async () => {
const onShowPlugins = vi.fn();
diff --git a/__tests__/components/features/chat/components/chat-input-actions.test.tsx b/__tests__/components/features/chat/components/chat-input-actions.test.tsx
index a55fe8361c..58cb28e1de 100644
--- a/__tests__/components/features/chat/components/chat-input-actions.test.tsx
+++ b/__tests__/components/features/chat/components/chat-input-actions.test.tsx
@@ -1,6 +1,6 @@
import React from "react";
-import { screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "test-utils";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import {
@@ -33,9 +33,6 @@ vi.mock("#/components/features/chat/change-agent-button", () => ({
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" />
),
@@ -58,6 +55,19 @@ vi.mock("#/hooks/query/use-active-conversation", () => ({
useActiveConversation: () => useActiveConversationMock(),
}));
+// Service-level mock (not the hook): drives the Switch-agent-profile gate,
+// which reads the real useAgentProfiles query.
+const listAgentProfilesMock = vi.fn();
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ default: {
+ listProfiles: (...args: unknown[]) => listAgentProfilesMock(...args),
+ getProfile: vi.fn(),
+ saveProfile: vi.fn(),
+ activateProfile: vi.fn(),
+ },
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
+}));
+
vi.mock("#/hooks/mutation/conversation-mutation-utils", () => ({
pauseConversation: vi.fn(),
resumeConversation: vi.fn(),
@@ -85,24 +95,40 @@ describe("ChatInputActions", () => {
useActiveConversationMock.mockReturnValue({ data: undefined });
});
- it("renders the AgentProfile picker on the home page (local)", () => {
+ it("renders the LLM-profile 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();
+ // The pill is always an LLM selector (OSS-5735) โ€” agent-profile switching
+ // lives in the "+" tools menu instead.
+ expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();
expect(
- screen.queryByTestId("llm-profile-picker-stub"),
+ screen.queryByTestId("chat-input-llm-model"),
).not.toBeInTheDocument();
+ });
+
+ it("renders the LLM-profile picker on the home page (cloud)", () => {
+ // Cloud used to fall back to a read-only model chip before a conversation
+ // started, surfacing the raw model path instead of the profile name (#1932
+ // review). The pill names the profile on every backend now.
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+
+ renderWithProviders(<ChatInputActions disabled={false} />, {
+ navigation: { conversationId: null },
+ });
+
+ expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();
expect(
screen.queryByTestId("chat-input-llm-model"),
).not.toBeInTheDocument();
});
- it("renders the AgentProfile picker inside a blank local OpenHands conversation", () => {
+ it("renders the LLM-profile picker inside a blank local OpenHands conversation", () => {
useActiveConversationMock.mockReturnValue({
data: { conversation_id: "test-conversation-id", llm_model: null },
});
@@ -114,10 +140,7 @@ describe("ChatInputActions", () => {
},
);
- expect(screen.getByTestId("agent-profile-picker-stub")).toBeInTheDocument();
- expect(
- screen.queryByTestId("llm-profile-picker-stub"),
- ).not.toBeInTheDocument();
+ expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();
expect(
screen.queryByTestId("chat-input-llm-model"),
).not.toBeInTheDocument();
@@ -135,11 +158,8 @@ describe("ChatInputActions", () => {
},
);
- // In a conversation the user live-switches the LLM profile, not start-new.
+ // In a conversation the user live-switches the LLM profile.
expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();
- expect(
- screen.queryByTestId("agent-profile-picker-stub"),
- ).not.toBeInTheDocument();
expect(
screen.queryByTestId("chat-input-llm-model"),
).not.toBeInTheDocument();
@@ -163,9 +183,6 @@ describe("ChatInputActions", () => {
// 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("llm-profile-picker-stub"),
).not.toBeInTheDocument();
@@ -191,9 +208,6 @@ describe("ChatInputActions", () => {
expect(screen.getByTestId("chat-input-llm-model")).toHaveTextContent(
"gpt-4o",
);
- expect(
- screen.queryByTestId("agent-profile-picker-stub"),
- ).not.toBeInTheDocument();
});
it("omits the model label on cloud when the active ACP conversation has no llm_model", () => {
@@ -235,9 +249,6 @@ describe("ChatInputActions", () => {
);
expect(screen.getByTestId("llm-profile-picker-stub")).toBeInTheDocument();
- expect(
- screen.queryByTestId("agent-profile-picker-stub"),
- ).not.toBeInTheDocument();
expect(
screen.queryByTestId("chat-input-llm-model"),
).not.toBeInTheDocument();
@@ -278,3 +289,103 @@ describe("ChatInputActions", () => {
expect(screen.getByTestId("change-agent-button-stub")).toBeInTheDocument();
});
});
+
+describe("ChatInputActions โ€” Switch agent profile gate (OSS-5735)", () => {
+ beforeEach(() => {
+ useActiveConversationMock.mockReset();
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ listAgentProfilesMock.mockReset();
+ listAgentProfilesMock.mockResolvedValue({
+ profiles: [{ id: "p1", name: "default", agent_kind: "openhands" }],
+ active_agent_profile_id: "p1",
+ });
+ });
+
+ afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ });
+
+ const openPlusMenu = () => {
+ fireEvent.click(screen.getByTestId("chat-plus-button"));
+ };
+
+ it("offers Switch agent profile in the + menu on the home page when profiles exist", async () => {
+ renderWithProviders(<ChatInputActions disabled={false} />, {
+ navigation: { conversationId: null },
+ });
+
+ openPlusMenu();
+
+ expect(
+ await screen.findByTestId("switch-agent-profile-button"),
+ ).toBeInTheDocument();
+ });
+
+ it("offers Switch agent profile in a blank (unstarted) conversation", async () => {
+ useActiveConversationMock.mockReturnValue({
+ data: { conversation_id: "conv-blank", llm_model: null },
+ });
+
+ renderWithProviders(
+ <ChatInputActions disabled={false} hasStartedConversation={false} />,
+ { navigation: { conversationId: "conv-blank" } },
+ );
+
+ openPlusMenu();
+
+ expect(
+ await screen.findByTestId("switch-agent-profile-button"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not offer Switch agent profile once the conversation has started", async () => {
+ useActiveConversationMock.mockReturnValue({
+ data: { conversation_id: "conv-started", llm_model: "gpt-4o" },
+ });
+
+ renderWithProviders(
+ <ChatInputActions disabled={false} hasStartedConversation />,
+ { navigation: { conversationId: "conv-started" } },
+ );
+
+ openPlusMenu();
+
+ expect(await screen.findByTestId("tools-context-menu")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("switch-agent-profile-button"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not offer Switch agent profile when the backend has no profiles", async () => {
+ listAgentProfilesMock.mockResolvedValue({
+ profiles: [],
+ active_agent_profile_id: null,
+ });
+
+ renderWithProviders(<ChatInputActions disabled={false} />, {
+ navigation: { conversationId: null },
+ });
+
+ openPlusMenu();
+
+ await waitFor(() => expect(listAgentProfilesMock).toHaveBeenCalled());
+ expect(
+ screen.queryByTestId("switch-agent-profile-button"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not offer Switch agent profile while a cloud start task is provisioning", async () => {
+ renderWithProviders(
+ <ChatInputActions disabled={false} hasStartedConversation={false} />,
+ { navigation: { conversationId: "task-start-1" } },
+ );
+
+ openPlusMenu();
+
+ await waitFor(() => expect(listAgentProfilesMock).toHaveBeenCalled());
+ expect(
+ screen.queryByTestId("switch-agent-profile-button"),
+ ).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.tsx
index 172499fba9..ef63736b74 100644
--- 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.tsx
@@ -35,6 +35,7 @@ function state(overrides = {}) {
currentProfileModel: "openai/gpt-4o-mini",
isLoading: false,
isSwitching: false,
+ canSwitchProfile: true,
selectProfile,
...overrides,
};
@@ -78,6 +79,22 @@ describe("ChatInputLlmProfilePicker", () => {
expect(selectProfile).not.toHaveBeenCalled();
});
+ it("names the current profile without selectable options when switching is unavailable", () => {
+ useChatInputLlmProfileStateMock.mockReturnValue(
+ state({ canSwitchProfile: false }),
+ );
+
+ renderWithProviders(<ChatInputLlmProfilePicker />);
+ fireEvent.click(screen.getByTestId("chat-input-llm-profile"));
+
+ expect(
+ screen.getByTestId("chat-input-llm-profile-current"),
+ ).toHaveTextContent("Fast");
+ expect(
+ screen.queryByTestId("chat-input-llm-profile-option-Smart"),
+ ).not.toBeInTheDocument();
+ });
+
it("links to the LLM profiles settings page", () => {
const { container } = renderWithProviders(<ChatInputLlmProfilePicker />);
fireEvent.click(screen.getByTestId("chat-input-llm-profile"));
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.tsx
index fd975199c9..80fb301b17 100644
--- a/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx
+++ b/__tests__/components/features/chat/components/chat-input-profile-picker.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, screen } from "@testing-library/react";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderWithProviders } from "test-utils";
import { setStoredConversationMetadata } from "#/api/conversation-metadata-store";
@@ -17,7 +17,7 @@ vi.mock("#/hooks/query/use-active-conversation", () => ({
}));
vi.mock("#/hooks/mutation/use-create-conversation", () => ({
- useCreateConversation: () => ({ mutate: createConversationMutate }),
+ useCreateConversation: () => ({ mutateAsync: createConversationMutate }),
CREATE_CONVERSATION_MUTATION_KEY: ["create-conversation"],
}));
@@ -29,19 +29,24 @@ vi.mock("#/hooks/mutation/use-activate-agent-profile", () => ({
ACTIVATE_AGENT_PROFILE_MUTATION_KEY: ["activate-agent-profile"],
}));
-import { ChatInputProfilePicker } from "#/components/features/chat/components/chat-input-profile-picker";
+import { ChatInputProfileMenuContent } 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" },
];
-describe("ChatInputProfilePicker", () => {
+describe("ChatInputProfileMenuContent", () => {
+ const onClose = vi.fn();
+
beforeEach(() => {
useAgentProfilesMock.mockReset();
useActiveConversationMock.mockReset();
activateProfileMutate.mockReset();
createConversationMutate.mockReset();
+ // selectProfile chains .then off mutateAsync โ€” keep a resolved default.
+ createConversationMutate.mockResolvedValue({ conversation_id: "conv-x" });
+ onClose.mockReset();
localStorage.clear();
useAgentProfilesMock.mockReturnValue({
@@ -54,66 +59,48 @@ describe("ChatInputProfilePicker", () => {
});
});
- const renderHomePicker = () =>
- renderWithProviders(<ChatInputProfilePicker />, {
- navigation: { conversationId: null },
- });
-
- it("renders nothing when there are no profiles", () => {
- useAgentProfilesMock.mockReturnValue({
- data: { profiles: [], active_agent_profile_id: null },
- isLoading: false,
- });
-
- const { container } = renderHomePicker();
- expect(container).toBeEmptyDOMElement();
- });
-
- it("renders nothing while a cloud start task is provisioning", () => {
- const { container } = renderWithProviders(<ChatInputProfilePicker />, {
- navigation: { conversationId: "task-start-1" },
- });
-
- expect(container).toBeEmptyDOMElement();
- });
-
- it("labels the button with the active profile", () => {
- renderHomePicker();
- expect(screen.getByTestId("chat-input-agent-profile")).toHaveTextContent(
- "Default",
+ // The menu content renders <li> children (it lives inside the tools menu's
+ // submenu <ContextMenu> in the app), so tests wrap it in a bare <ul>.
+ const renderMenu = (navigation: object = { conversationId: null }) =>
+ renderWithProviders(
+ <ul>
+ <ChatInputProfileMenuContent onClose={onClose} />
+ </ul>,
+ { navigation },
);
- });
- it("activates the picked profile", () => {
- renderHomePicker();
- fireEvent.click(screen.getByTestId("chat-input-agent-profile"));
+ it("activates the picked profile on the home page", () => {
+ renderMenu();
fireEvent.click(
screen.getByTestId("chat-input-agent-profile-option-Codex"),
);
expect(activateProfileMutate).toHaveBeenCalledWith("id-codex");
+ expect(onClose).toHaveBeenCalled();
});
it("does not activate when the active profile is re-selected", () => {
- renderHomePicker();
- fireEvent.click(screen.getByTestId("chat-input-agent-profile"));
+ renderMenu();
fireEvent.click(
screen.getByTestId("chat-input-agent-profile-option-Default"),
);
expect(activateProfileMutate).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
});
it("links to the AgentProfile library in settings", () => {
- const { container } = renderHomePicker();
- fireEvent.click(screen.getByTestId("chat-input-agent-profile"));
+ const { container } = renderMenu();
expect(
container.ownerDocument.querySelector('a[href="/settings/agents"]'),
).not.toBeNull();
});
- it("shows the launched profile inside a blank conversation", () => {
+ it("treats the launched profile as current inside a blank conversation", () => {
+ // The active pointer is Codex, but this blank conversation was launched
+ // from Default โ€” re-selecting Default must be a no-op (no replacement
+ // conversation, no activate).
useAgentProfilesMock.mockReturnValue({
data: { profiles: PROFILES, active_agent_profile_id: "id-codex" },
isLoading: false,
@@ -129,17 +116,18 @@ describe("ChatInputProfilePicker", () => {
isLoading: false,
});
- renderWithProviders(<ChatInputProfilePicker />, {
- navigation: { conversationId: "conv-1" },
- });
-
- expect(screen.getByTestId("chat-input-agent-profile")).toHaveTextContent(
- "Default",
+ renderMenu({ conversationId: "conv-1" });
+ fireEvent.click(
+ screen.getByTestId("chat-input-agent-profile-option-Default"),
);
+
+ expect(createConversationMutate).not.toHaveBeenCalled();
+ expect(activateProfileMutate).not.toHaveBeenCalled();
});
- it("starts a replacement conversation with the selected profile and workspace", () => {
+ it("starts a replacement conversation with the selected profile and workspace", async () => {
const navigate = vi.fn();
+ createConversationMutate.mockResolvedValue({ conversation_id: "conv-2" });
useActiveConversationMock.mockReturnValue({
data: {
id: "conv-workspace",
@@ -153,30 +141,25 @@ describe("ChatInputProfilePicker", () => {
isLoading: false,
});
- renderWithProviders(<ChatInputProfilePicker />, {
- navigation: { conversationId: "conv-workspace", navigate },
- });
- fireEvent.click(screen.getByTestId("chat-input-agent-profile"));
+ renderMenu({ conversationId: "conv-workspace", navigate });
expect(screen.getByText("CHAT$START_NEW_WITH_PROFILE_HINT")).toBeVisible();
fireEvent.click(
screen.getByTestId("chat-input-agent-profile-option-Codex"),
);
- expect(createConversationMutate).toHaveBeenCalledWith(
- {
- agentProfileId: "id-codex",
- entryPoint: "blank_conversation_profile_picker",
- workingDir: "/workspace/alpha",
- workspaceMode: "local_repo",
- },
- expect.objectContaining({ onSuccess: expect.any(Function) }),
- );
+ expect(createConversationMutate).toHaveBeenCalledWith({
+ agentProfileId: "id-codex",
+ entryPoint: "blank_conversation_profile_picker",
+ workingDir: "/workspace/alpha",
+ workspaceMode: "local_repo",
+ });
expect(activateProfileMutate).not.toHaveBeenCalled();
- const onSuccess = createConversationMutate.mock.calls[0]?.[1]?.onSuccess;
- onSuccess({ conversation_id: "conv-2" });
- expect(navigate).toHaveBeenCalledWith("/conversations/conv-2");
+ // Navigation rides the mutateAsync promise (survives the menu unmounting).
+ await waitFor(() =>
+ expect(navigate).toHaveBeenCalledWith("/conversations/conv-2"),
+ );
});
it("preserves repository and plugin context when changing a blank conversation profile", () => {
@@ -206,10 +189,7 @@ describe("ChatInputProfilePicker", () => {
isLoading: false,
});
- renderWithProviders(<ChatInputProfilePicker />, {
- navigation: { conversationId: "conv-repo" },
- });
- fireEvent.click(screen.getByTestId("chat-input-agent-profile"));
+ renderMenu({ conversationId: "conv-repo" });
fireEvent.click(
screen.getByTestId("chat-input-agent-profile-option-Codex"),
);
@@ -230,7 +210,6 @@ describe("ChatInputProfilePicker", () => {
},
],
}),
- expect.any(Object),
);
});
});
diff --git a/__tests__/components/features/chat/components/resolve-picker-kind.test.ts b/__tests__/components/features/chat/components/resolve-picker-kind.test.ts
index ae9e81b7b6..a430838a70 100644
--- a/__tests__/components/features/chat/components/resolve-picker-kind.test.ts
+++ b/__tests__/components/features/chat/components/resolve-picker-kind.test.ts
@@ -2,149 +2,19 @@ import { describe, expect, it } from "vitest";
import {
hasConversationStarted,
resolvePickerKind,
- type ResolvePickerKindInput,
} from "#/components/features/chat/components/resolve-picker-kind";
-const base: ResolvePickerKindInput = {
- hasConversation: false,
- isCloud: false,
- isAcp: false,
- profilesAvailable: true,
-};
-
+// The pill is always an LLM selector (OSS-5735): agent-profile switching lives
+// in the "+" tools menu, and neither the backend nor the conversation's state
+// branches here any more โ€” whether a pick is actionable is decided in
+// useChatInputLlmProfileState, so cloud never falls back to a raw model chip.
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");
- });
+ it("shows the constrained model picker in an ACP context", () => {
+ expect(resolvePickerKind({ isAcp: true })).toBe("model");
});
- describe("inside a conversation", () => {
- it("shows the agent-profile picker for an unstarted conversation when profiles exist", () => {
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: false,
- isCloud: false,
- isAcp: false,
- profilesAvailable: true,
- }),
- ).toBe("agent-profile");
- });
-
- it("uses the pre-run fallback for an unstarted conversation when profiles are unavailable", () => {
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: false,
- isCloud: false,
- profilesAvailable: false,
- }),
- ).toBe("llm-profile");
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: false,
- isCloud: true,
- profilesAvailable: false,
- }),
- ).toBe("model");
- });
-
- it("shows the model picker for an ACP conversation regardless of backend", () => {
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: true,
- isCloud: false,
- isAcp: true,
- }),
- ).toBe("model");
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: 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,
- hasStartedConversation: true,
- isCloud: false,
- isAcp: false,
- }),
- ).toBe("llm-profile");
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: true,
- isCloud: true,
- isAcp: false,
- }),
- ).toBe("llm-profile");
- });
-
- it("ignores profilesAvailable once a conversation is active", () => {
- expect(
- resolvePickerKind({
- ...base,
- hasConversation: true,
- hasStartedConversation: true,
- isCloud: false,
- isAcp: false,
- profilesAvailable: false,
- }),
- ).toBe("llm-profile");
- });
+ it("shows the LLM-profile picker for an OpenHands context", () => {
+ expect(resolvePickerKind({ isAcp: false })).toBe("llm-profile");
});
});
diff --git a/__tests__/hooks/mutation/use-switch-acp-model.test.tsx b/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
index f6b465ad7b..10c1a48352 100644
--- a/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
+++ b/__tests__/hooks/mutation/use-switch-acp-model.test.tsx
@@ -3,6 +3,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { useSwitchAcpModel } from "#/hooks/mutation/use-switch-acp-model";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
import SettingsService from "#/api/settings-service/settings-service.api";
import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
@@ -15,6 +16,14 @@ vi.mock(
}),
);
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ default: {
+ listProfiles: vi.fn(),
+ getProfile: vi.fn(),
+ saveProfile: vi.fn(),
+ },
+}));
+
vi.mock("#/api/settings-service/settings-service.api", () => ({
default: {
saveSettings: vi.fn(),
@@ -75,7 +84,15 @@ describe("useSwitchAcpModel", () => {
});
});
- it("persists the model as the agent-settings default on the home page (conversationId === null)", async () => {
+ it("persists the model as the agent-settings default on the home page when no ACP profile is active", async () => {
+ // Legacy/no-ACP-profile fallback: an active OpenHands profile means the
+ // ACP-profile persist path doesn't apply, so the write goes to settings.
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [
+ { id: "id-default", name: "default", agent_kind: "openhands" },
+ ],
+ active_agent_profile_id: "id-default",
+ } as never);
vi.mocked(SettingsService.saveSettings).mockResolvedValue(true);
const { result, invalidateQueriesSpy } = renderSwitchHook();
@@ -91,6 +108,7 @@ describe("useSwitchAcpModel", () => {
expect(SettingsService.saveSettings).toHaveBeenCalledWith({
agent_settings_diff: { acp_model: "gemini-2.5-pro" },
});
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
expect(
AgentServerConversationService.switchAcpModel,
).not.toHaveBeenCalled();
@@ -102,6 +120,73 @@ describe("useSwitchAcpModel", () => {
});
});
+ it("persists the model into the active ACP profile on the home page", async () => {
+ // The profile is the launch source (agent_profile_id and agent_settings
+ // are mutually exclusive), so the pick must land on the profile itself.
+ vi.mocked(AgentProfilesService.listProfiles).mockResolvedValue({
+ profiles: [{ id: "id-claude", name: "claude", agent_kind: "acp" }],
+ active_agent_profile_id: "id-claude",
+ } as never);
+ vi.mocked(AgentProfilesService.getProfile).mockResolvedValue({
+ profile: {
+ id: "id-claude",
+ name: "claude",
+ revision: 3,
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "claude-sonnet-4-6",
+ acp_session_mode: "default",
+ },
+ } as never);
+ vi.mocked(AgentProfilesService.saveProfile).mockResolvedValue({
+ name: "claude",
+ message: "saved",
+ } as never);
+
+ const { result, invalidateQueriesSpy } = renderSwitchHook();
+
+ result.current.mutate({ conversationId: null, model: "claude-opus-4-6" });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ // Model-only merge over the stored profile: unmodeled fields survive,
+ // identity (id/revision) is stripped by mergeAgentProfileSaveInput.
+ expect(AgentProfilesService.saveProfile).toHaveBeenCalledWith("claude", {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "claude-opus-4-6",
+ acp_session_mode: "default",
+ });
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ // The agent-profiles prefix covers the list + detail entries just
+ // rewritten, so the home picker re-derives from the new model.
+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({
+ queryKey: ["agent-profiles"],
+ });
+ });
+
+ it("falls back to the agent-settings default when the profiles surface is unavailable", async () => {
+ vi.mocked(AgentProfilesService.listProfiles).mockRejectedValue(
+ new Error("404"),
+ );
+ vi.mocked(SettingsService.saveSettings).mockResolvedValue(true);
+
+ const { result } = renderSwitchHook();
+
+ result.current.mutate({ conversationId: null, model: "gemini-2.5-pro" });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(SettingsService.saveSettings).toHaveBeenCalledWith({
+ agent_settings_diff: { acp_model: "gemini-2.5-pro" },
+ });
+ expect(AgentProfilesService.saveProfile).not.toHaveBeenCalled();
+ });
+
it("does not invalidate caches when the live switch fails", async () => {
vi.mocked(AgentServerConversationService.switchAcpModel).mockRejectedValue(
new Error("boom"),
diff --git a/__tests__/hooks/query/use-active-acp-profile-detail.test.tsx b/__tests__/hooks/query/use-active-acp-profile-detail.test.tsx
new file mode 100644
index 0000000000..7138ad38ce
--- /dev/null
+++ b/__tests__/hooks/query/use-active-acp-profile-detail.test.tsx
@@ -0,0 +1,80 @@
+import { screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+import { useActiveAcpProfileDetail } from "#/hooks/query/use-active-acp-profile-detail";
+
+const listProfilesMock = vi.fn();
+const getProfileMock = vi.fn();
+
+vi.mock("#/api/agent-profiles-service/agent-profiles-service.api", () => ({
+ default: {
+ listProfiles: (...args: unknown[]) => listProfilesMock(...args),
+ getProfile: (...args: unknown[]) => getProfileMock(...args),
+ },
+ WELL_KNOWN_DEFAULT_AGENT_PROFILE_NAME: "default",
+}));
+
+function Probe() {
+ const profile = useActiveAcpProfileDetail();
+ return (
+ <div data-testid="acp-detail">
+ {profile ? `${profile.acp_server}:${profile.acp_model}` : "none"}
+ </div>
+ );
+}
+
+describe("useActiveAcpProfileDetail", () => {
+ beforeEach(() => {
+ listProfilesMock.mockReset();
+ getProfileMock.mockReset();
+ });
+
+ it("resolves the active ACP profile's server and model on the home page", async () => {
+ listProfilesMock.mockResolvedValue({
+ profiles: [{ id: "id-claude", name: "claude", agent_kind: "acp" }],
+ active_agent_profile_id: "id-claude",
+ });
+ getProfileMock.mockResolvedValue({
+ profile: {
+ id: "id-claude",
+ name: "claude",
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "sonnet",
+ },
+ });
+
+ renderWithProviders(<Probe />, { navigation: { conversationId: null } });
+
+ expect(await screen.findByText("claude-code:sonnet")).toBeInTheDocument();
+ expect(getProfileMock).toHaveBeenCalledWith("claude");
+ });
+
+ it("does not fetch the detail while a conversation is open", async () => {
+ listProfilesMock.mockResolvedValue({
+ profiles: [{ id: "id-claude", name: "claude", agent_kind: "acp" }],
+ active_agent_profile_id: "id-claude",
+ });
+
+ renderWithProviders(<Probe />, {
+ navigation: { conversationId: "conv-1" },
+ });
+
+ await waitFor(() => expect(listProfilesMock).toHaveBeenCalled());
+ expect(getProfileMock).not.toHaveBeenCalled();
+ expect(screen.getByTestId("acp-detail")).toHaveTextContent("none");
+ });
+
+ it("does not fetch the detail when the active profile is OpenHands", async () => {
+ listProfilesMock.mockResolvedValue({
+ profiles: [{ id: "id-oh", name: "default", agent_kind: "openhands" }],
+ active_agent_profile_id: "id-oh",
+ });
+
+ renderWithProviders(<Probe />, { navigation: { conversationId: null } });
+
+ await waitFor(() => expect(listProfilesMock).toHaveBeenCalled());
+ expect(getProfileMock).not.toHaveBeenCalled();
+ expect(screen.getByTestId("acp-detail")).toHaveTextContent("none");
+ });
+});
diff --git a/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
index 32b5b81685..0799144ffc 100644
--- a/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
+++ b/__tests__/hooks/use-chat-input-llm-profile-state.test.tsx
@@ -27,6 +27,12 @@ vi.mock("#/stores/model-store", () => ({
useModelStore: (selector: (s: typeof modelStoreState) => unknown) =>
selector(modelStoreState),
}));
+// The org-permission check reads the active backend from a context this
+// wrapper-less harness doesn't provide; drive it per test instead.
+const useCanManageOrgProfilesMock = vi.fn();
+vi.mock("#/hooks/use-can-manage-org-profiles", () => ({
+ useCanManageOrgProfiles: () => useCanManageOrgProfilesMock(),
+}));
// eslint-disable-next-line import/first
import { useChatInputLlmProfileState } from "#/hooks/use-chat-input-llm-profile-state";
@@ -59,6 +65,9 @@ describe("useChatInputLlmProfileState", () => {
data: { profiles: PROFILES, active_profile: "Fast" },
isLoading: false,
});
+ useCanManageOrgProfilesMock.mockReset();
+ // Local backends always own their profiles.
+ useCanManageOrgProfilesMock.mockReturnValue(true);
});
it("prefers the profile stamped on the conversation over a model match", () => {
@@ -119,4 +128,41 @@ describe("useChatInputLlmProfileState", () => {
result.current.selectProfile("Fast");
expect(switchAndLog).not.toHaveBeenCalled();
});
+
+ it("activates the picked profile account-wide from the home page", () => {
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+
+ const { result } = renderState();
+ result.current.selectProfile("Smart");
+
+ // No conversation โ†’ the switch activates the profile globally so the next
+ // conversation launches with it.
+ expect(switchAndLog).toHaveBeenCalledWith(null, "Smart");
+ });
+
+ it("keeps the home picker read-only for a member who cannot manage org profiles", () => {
+ // A home pick hits the org-gated activate endpoint, which a cloud member
+ // could only 403 on.
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+ useCanManageOrgProfilesMock.mockReturnValue(false);
+
+ const { result } = renderState();
+ result.current.selectProfile("Smart");
+
+ expect(result.current.canSwitchProfile).toBe(false);
+ expect(switchAndLog).not.toHaveBeenCalled();
+ });
+
+ it("keeps the picker read-only while a cloud start task is provisioning", () => {
+ // `task-โ€ฆ` is not a real conversation id yet, so /switch_profile would 404.
+ useOptionalConversationIdMock.mockReturnValue({
+ conversationId: "task-abc",
+ });
+
+ const { result } = renderState();
+ result.current.selectProfile("Smart");
+
+ expect(result.current.canSwitchProfile).toBe(false);
+ 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.tsx
index 9ea4143f33..826a8f79d8 100644
--- a/__tests__/hooks/use-chat-input-model-state.test.tsx
+++ b/__tests__/hooks/use-chat-input-model-state.test.tsx
@@ -35,6 +35,19 @@ vi.mock("#/hooks/use-conversation-id", () => ({
useOptionalConversationId: () => useOptionalConversationIdMock(),
}));
+// The detail query and the org-permission check need a QueryClient this
+// wrapper-less harness doesn't provide; both are driven per test (detail null
+// โ†’ the settings fallback the older tests exercise).
+const useActiveAcpProfileDetailMock = vi.fn();
+vi.mock("#/hooks/query/use-active-acp-profile-detail", () => ({
+ useActiveAcpProfileDetail: () => useActiveAcpProfileDetailMock(),
+}));
+
+const useCanManageOrgProfilesMock = vi.fn();
+vi.mock("#/hooks/use-can-manage-org-profiles", () => ({
+ useCanManageOrgProfiles: () => useCanManageOrgProfilesMock(),
+}));
+
// `getAcpProvider`/`labelForAcpModel`/`resolveEffectiveAcpModel` are exercised
// for real (not mocked) so the test pins the actual registry-sourced model
// list the picker shows.
@@ -66,6 +79,10 @@ describe("useChatInputModelState", () => {
useAcpModelContextMock.mockReturnValue(acpContext());
useOptionalConversationIdMock.mockReset();
useOptionalConversationIdMock.mockReturnValue({ conversationId: null });
+ useActiveAcpProfileDetailMock.mockReset();
+ useActiveAcpProfileDetailMock.mockReturnValue(null);
+ useCanManageOrgProfilesMock.mockReset();
+ useCanManageOrgProfilesMock.mockReturnValue(true);
});
it("non-ACP: shows the conversation/settings llm_model with no picker", () => {
@@ -182,6 +199,60 @@ describe("useChatInputModelState", () => {
expect(result.current.currentModelId).toBe(provider?.default_model);
});
+ it("home ACP: the active profile's detail overrides stale agent settings for provider and model", () => {
+ // Activation is pointer-only: settings still describe claude-code, but the
+ // active ACP profile is codex โ€” the picker must follow the profile (the
+ // conversation launch source), not the settings.
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: {
+ agent_kind: "acp",
+ acp_server: "claude-code",
+ acp_model: "claude-sonnet-4-6",
+ },
+ },
+ });
+ useActiveAcpProfileDetailMock.mockReturnValue({
+ id: "id-codex",
+ name: "codex-test",
+ agent_kind: "acp",
+ acp_server: "codex",
+ acp_model: "gpt-5.5",
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.currentModelId).toBe("gpt-5.5");
+ expect(result.current.availableAcpModels).toEqual(
+ getAcpProvider("codex")?.available_models,
+ );
+ });
+
+ it("home ACP on cloud: hides the selectable rows from members who cannot manage org profiles", () => {
+ // A home pick persists into the org-owned profile; a member's pick would
+ // only 403. The chip and settings link remain (showAcpPicker false).
+ useActiveBackendMock.mockReturnValue({ backend: { kind: "cloud" } });
+ useCanManageOrgProfilesMock.mockReturnValue(false);
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ useSettingsMock.mockReturnValue({
+ data: {
+ agent_settings: { agent_kind: "acp", acp_server: "claude-code" },
+ },
+ });
+ useAcpModelContextMock.mockReturnValue(
+ acpContext({ isHomeAcp: true, isAcpContext: true }),
+ );
+
+ const { result } = renderHook(() => useChatInputModelState());
+
+ expect(result.current.availableAcpModels.length).toBeGreaterThan(0);
+ expect(result.current.showAcpPicker).toBe(false);
+ });
+
it("showAcpPicker: cloud backend shows the picker when a model list is present (cloud ACP supports mid-conversation switching)", () => {
useActiveBackendMock.mockReturnValue({ backend: { kind: "cloud" } });
useActiveConversationMock.mockReturnValue({
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index a2ac71fd09..9c86b87081 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -845,9 +845,11 @@ class AgentServerConversationService {
* session, preserving context. Mirrors {@link switchProfile}'s
* local-backend-only guard and per-conversation ConversationClient call.
*
- * Only valid once an ACP session exists (after the first message); the
- * agent-server returns 409 before then โ€” the home/no-session default is
- * persisted via Settings instead (see ``use-switch-acp-model``).
+ * Works on a created-but-not-yet-run conversation too: the agent-server
+ * treats a pre-first-run switch as a persist-only deferral (the model is
+ * mirrored into the conversation's stored agent and applied when the session
+ * starts). The home/no-conversation default is persisted via the active ACP
+ * profile / Settings instead (see ``use-switch-acp-model``).
*/
static async switchAcpModel(
conversationId: string,
diff --git a/src/components/features/chat/chat-add-file-button.tsx b/src/components/features/chat/chat-add-file-button.tsx
index c32cbd16cb..c5c4c9bc32 100644
--- a/src/components/features/chat/chat-add-file-button.tsx
+++ b/src/components/features/chat/chat-add-file-button.tsx
@@ -16,11 +16,19 @@ import { HooksModal } from "#/components/features/conversation-panel/hooks-modal
export interface ChatAddFileButtonProps {
handleFileIconClick: () => void;
disabled?: boolean;
+ /**
+ * Offer the "Switch agent profile" submenu. Computed by ChatInputActions:
+ * only while starting a new conversation (home or a blank conversation) and
+ * only when the backend has agent profiles (OSS-5735 โ€” once a conversation
+ * starts, the agent profile is locked).
+ */
+ showAgentProfileSwitch?: boolean;
}
export function ChatAddFileButton({
handleFileIconClick,
disabled = false,
+ showAgentProfileSwitch = false,
}: ChatAddFileButtonProps) {
const { t } = useTranslation("openhands");
const { conversationId } = useOptionalConversationId();
@@ -85,6 +93,7 @@ export function ChatAddFileButton({
{menuOpen && (
<ToolsContextMenu
onClose={() => setMenuOpen(false)}
+ showAgentProfileSwitch={showAgentProfileSwitch}
onShowSkills={handleShowSkills}
onShowPlugins={handleShowPlugins}
onShowHooks={handleShowHooks}
diff --git a/src/components/features/chat/components/chat-input-actions.tsx b/src/components/features/chat/components/chat-input-actions.tsx
index 2ba1fa8a5c..5974edac52 100644
--- a/src/components/features/chat/components/chat-input-actions.tsx
+++ b/src/components/features/chat/components/chat-input-actions.tsx
@@ -5,10 +5,6 @@ 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 {
- ChatInputProfilePicker,
- ChatInputProfileMenuContent,
-} from "./chat-input-profile-picker";
import {
ChatInputLlmProfilePicker,
ChatInputLlmProfileMenuContent,
@@ -70,16 +66,18 @@ 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;
+ // Agent-profile switching lives in the "+" tools menu while the conversation
+ // hasn't started (OSS-5735) โ€” the pill itself is always an LLM selector. The
+ // gate is computed here (not in the menu) so ToolsContextMenu only mounts the
+ // profile submenu when it can actually be used: pre-start, not on a task
+ // route, and only when the backend has profiles (#1571 fallback). Fetch is
+ // limited to the pre-start window.
+ const isPreStart = !conversationId || hasStartedConversation === false;
+ const agentProfilesForStart = useAgentProfiles({ enabled: isPreStart });
+ const showAgentProfileSwitch =
+ isPreStart &&
+ !(conversationId?.startsWith("task-") ?? false) &&
+ (agentProfilesForStart.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;
@@ -245,15 +243,9 @@ 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,
- hasStartedConversation,
- isCloud,
- isAcp: modelState.isAcpContext,
- profilesAvailable: !agentProfilesUnavailableOnHome,
- });
+ // Which chat-input LLM picker to show โ€” the constrained ACP model picker or
+ // the LLM-profile picker (unit-tested in `resolve-picker-kind.test.ts`).
+ const pickerKind = resolvePickerKind({ isAcp: modelState.isAcpContext });
// Shared styling for the settings link inside the overflow submenu content.
const overflowSettingsLinkClassName = cn(
@@ -416,13 +408,6 @@ export function ChatInputActions({
settingsLinkClassName={overflowSettingsLinkClassName}
settingsIconClassName={overflowSettingsIconClassName}
/>
- ) : pickerKind === "agent-profile" ? (
- <ChatInputProfileMenuContent
- onClose={closeOverflowMenus}
- dividerInset="menu"
- settingsLinkClassName={overflowSettingsLinkClassName}
- settingsIconClassName={overflowSettingsIconClassName}
- />
) : (
<ChatInputLlmProfileMenuContent
onClose={closeOverflowMenus}
@@ -449,6 +434,7 @@ export function ChatInputActions({
<ChatAddFileButton
disabled={disabled}
handleFileIconClick={onAddFileClick}
+ showAgentProfileSwitch={showAgentProfileSwitch}
/>
</div>
{showChangeAgentButton && (
@@ -457,12 +443,10 @@ export function ChatInputActions({
</div>
)}
<div ref={modelRef} className={cn(!showModelInline && "hidden")}>
- {/* Picker depends on backend + whether we're in a conversation;
- see the `pickerKind` cases above. */}
+ {/* Picker depends on backend + ACP context; see the `pickerKind`
+ cases above. */}
{pickerKind === "model" ? (
<ChatInputModel />
- ) : pickerKind === "agent-profile" ? (
- <ChatInputProfilePicker />
) : (
<ChatInputLlmProfilePicker />
)}
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.tsx
index b2fa243f42..564028d0a9 100644
--- a/src/components/features/chat/components/chat-input-llm-profile-picker.tsx
+++ b/src/components/features/chat/components/chat-input-llm-profile-picker.tsx
@@ -42,8 +42,18 @@ export function ChatInputLlmProfileMenuContent({
settingsIconClassName,
}: ChatInputLlmProfileMenuContentProps) {
const { t } = useTranslation("openhands");
- const { profiles, currentProfileName, selectProfile } =
- useChatInputLlmProfileState();
+ const {
+ profiles,
+ currentProfileName,
+ currentProfileModel,
+ canSwitchProfile,
+ selectProfile,
+ } = useChatInputLlmProfileState();
+ // Read-only surfaces (a cloud member on the home page, or a start-task route)
+ // still name the active profile โ€” the same shape ChatInputModelMenuContent
+ // uses when the ACP picker is gated off.
+ const showProfileList = canSwitchProfile && profiles.length > 0;
+ const readOnlyProfileName = canSwitchProfile ? null : currentProfileName;
const handleSelect = (profileName: string) => {
selectProfile(profileName);
@@ -52,7 +62,7 @@ export function ChatInputLlmProfileMenuContent({
return (
<>
- {profiles.length > 0 && (
+ {showProfileList && (
<>
{/* role="presentation" keeps this a valid <li> child of the
ContextMenu <ul> without exposing the label as a menu item. */}
@@ -107,7 +117,23 @@ export function ChatInputLlmProfileMenuContent({
})}
</>
)}
- {profiles.length > 0 && <Divider inset={dividerInset} />}
+ {readOnlyProfileName && (
+ <li className="text-sm" data-testid="chat-input-llm-profile-current">
+ <div className="flex flex-col gap-0.5 p-2 leading-5 text-[var(--oh-foreground)]">
+ <span className="truncate" title={readOnlyProfileName}>
+ {readOnlyProfileName}
+ </span>
+ {currentProfileModel && (
+ <span className="truncate text-xs leading-4 text-[var(--oh-muted)]">
+ {currentProfileModel}
+ </span>
+ )}
+ </div>
+ </li>
+ )}
+ {(showProfileList || readOnlyProfileName) && (
+ <Divider inset={dividerInset} />
+ )}
<li className="text-sm">
<NavigationLink
to="/settings/llm"
diff --git a/src/components/features/chat/components/chat-input-profile-picker.tsx b/src/components/features/chat/components/chat-input-profile-picker.tsx
index ad70673d54..635f0b3bda 100644
--- a/src/components/features/chat/components/chat-input-profile-picker.tsx
+++ b/src/components/features/chat/components/chat-input-profile-picker.tsx
@@ -1,26 +1,13 @@
-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;
@@ -29,6 +16,14 @@ interface ChatInputProfileMenuContentProps {
settingsIconClassName?: string;
}
+/**
+ * The agent-profile list rendered inside the "+" tools menu's "Switch agent
+ * profile" submenu, offered only while starting a new conversation (OSS-5735 โ€”
+ * the profile is locked once a conversation starts). Selecting a profile
+ * activates it (home) or recreates the blank conversation with it (see
+ * `useChatInputProfileState`). The chat-input pill itself is always an LLM
+ * selector; the former `ChatInputProfilePicker` pill is gone.
+ */
export function ChatInputProfileMenuContent({
onClose,
dividerInset,
@@ -130,65 +125,3 @@ export function ChatInputProfileMenuContent({
</>
);
}
-
-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.ts
index 4f7dadfdef..d4802fe48c 100644
--- a/src/components/features/chat/components/resolve-picker-kind.ts
+++ b/src/components/features/chat/components/resolve-picker-kind.ts
@@ -1,4 +1,4 @@
-export type PickerKind = "model" | "agent-profile" | "llm-profile";
+export type PickerKind = "model" | "llm-profile";
export interface ConversationStartState {
isLoadingHistory: boolean;
@@ -25,22 +25,19 @@ export function hasConversationStarted({
}
export interface ResolvePickerKindInput {
- hasConversation: boolean;
- hasStartedConversation?: boolean;
- isCloud: boolean;
+ /** The current context runs an ACP agent (active conversation or active ACP profile). */
isAcp: boolean;
- profilesAvailable: boolean;
}
+// The chat-input pill is always an LLM selector (OSS-5735): the ACP model
+// picker in an ACP context (constrained to that provider's models), the LLM
+// profile picker otherwise โ€” on every backend, before and during a
+// conversation, so the pill always names the LLM profile rather than a raw
+// model path. Whether a pick is actionable (cloud org permission, start-task
+// route) is decided in ``useChatInputLlmProfileState``, not by swapping in a
+// different pill. Agent-profile switching lives in the "+" tools menu while
+// the conversation hasn't started, not here.
export function resolvePickerKind({
- hasConversation,
- hasStartedConversation = hasConversation,
- isCloud,
isAcp,
- profilesAvailable,
}: ResolvePickerKindInput): PickerKind {
- if (!hasConversation || !hasStartedConversation) {
- if (profilesAvailable) return "agent-profile";
- return isCloud ? "model" : "llm-profile";
- }
return isAcp ? "model" : "llm-profile";
}
diff --git a/src/components/features/controls/tools-context-menu.tsx b/src/components/features/controls/tools-context-menu.tsx
index efe4a458b6..e149ee6dbd 100644
--- a/src/components/features/controls/tools-context-menu.tsx
+++ b/src/components/features/controls/tools-context-menu.tsx
@@ -14,11 +14,13 @@ import SkillsIcon from "#/icons/skills.svg?react";
import PuzzleIcon from "#/icons/u-puzzle-piece.svg?react";
import FishingHookIcon from "#/icons/fishing-hook.svg?react";
import ToolsIcon from "#/icons/u-tools.svg?react";
+import RobotIcon from "#/icons/u-robot.svg?react";
import SettingsIcon from "#/icons/settings.svg?react";
import CarretRightFillIcon from "#/icons/carret-right-fill.svg?react";
import { ToolsContextMenuIconText } from "./tools-context-menu-icon-text";
import { GitToolsSubmenu } from "./git-tools-submenu";
import { MacrosSubmenu } from "./macros-submenu";
+import { ChatInputProfileMenuContent } from "#/components/features/chat/components/chat-input-profile-picker";
import { ArchivedDisabledTooltip } from "../context-menu/archived-disabled-tooltip";
import { useIsArchivedConversation } from "#/hooks/use-is-archived-conversation";
@@ -31,6 +33,12 @@ interface ToolsContextMenuProps {
shouldShowAgentTools?: boolean;
shouldShowHooks?: boolean;
shouldShowPlugins?: boolean;
+ /**
+ * Offer the "Switch agent profile" submenu (OSS-5735). The caller owns the
+ * gating (pre-start only + profiles available) so this menu stays renderable
+ * without query/navigation providers when the item is off.
+ */
+ showAgentProfileSwitch?: boolean;
/** When set, renders a divider and this action as the last menu item. */
footerAction?: {
testId: string;
@@ -49,6 +57,7 @@ export function ToolsContextMenu({
shouldShowAgentTools = true,
shouldShowHooks = false,
shouldShowPlugins = false,
+ showAgentProfileSwitch = false,
footerAction,
}: ToolsContextMenuProps) {
const { t } = useTranslation("openhands");
@@ -56,15 +65,15 @@ export function ToolsContextMenu({
const { providers } = useUserProviders();
const isArchivedConversation = useIsArchivedConversation();
- const [activeSubmenu, setActiveSubmenu] = useState<"git" | "macros" | null>(
- null,
- );
+ const [activeSubmenu, setActiveSubmenu] = useState<
+ "git" | "macros" | "agent-profile" | null
+ >(null);
const hasRepository = !!conversation?.selected_repository;
const providersAreSet = providers.length > 0;
const showGitTools = hasRepository && providersAreSet;
- const handleSubmenuClick = (submenu: "git" | "macros") => {
+ const handleSubmenuClick = (submenu: "git" | "macros" | "agent-profile") => {
if (isArchivedConversation) {
return;
}
@@ -86,6 +95,48 @@ export function ToolsContextMenu({
alignment="left"
className="left-[-16px] mb-2 bottom-full overflow-visible min-w-[200px]"
>
+ {/* Switch agent profile โ€” only while starting a new conversation; the
+ profile is locked once the conversation starts (OSS-5735). Selecting
+ a profile activates it (home) or recreates the blank conversation
+ with it (see ChatInputProfileMenuContent). No archived gating: this
+ never renders in a started (archivable) conversation. */}
+ {showAgentProfileSwitch && (
+ <div className="relative group/agent-profile">
+ <ContextMenuListItem
+ testId="switch-agent-profile-button"
+ onClick={() => handleSubmenuClick("agent-profile")}
+ >
+ <ToolsContextMenuIconText
+ icon={<RobotIcon width={16} height={16} aria-hidden />}
+ text={t(I18nKey.CHAT$SWITCH_AGENT_PROFILE)}
+ rightIcon={<CarretRightFillIcon width={10} height={10} />}
+ />
+ </ContextMenuListItem>
+ <div
+ className={cn(
+ "absolute left-full top-[-4px] z-60 opacity-0 invisible pointer-events-none transition-all duration-200 ml-[1px]",
+ "group-hover/agent-profile:opacity-100 group-hover/agent-profile:visible group-hover/agent-profile:pointer-events-auto",
+ "hover:opacity-100 hover:visible hover:pointer-events-auto",
+ activeSubmenu === "agent-profile" &&
+ "opacity-100 visible pointer-events-auto",
+ )}
+ >
+ {/* overflow-y-auto so a long profile list scrolls within the menu;
+ safe because the content has no floating children โ€” only the
+ flat profile list + Manage link. */}
+ <ContextMenu
+ testId="agent-profile-submenu"
+ className="min-w-[220px] max-w-[320px] max-h-[60vh] overflow-y-auto gap-0"
+ >
+ <ChatInputProfileMenuContent
+ onClose={handleClose}
+ dividerInset="menu"
+ />
+ </ContextMenu>
+ </div>
+ </div>
+ )}
+
{/* Git Tools */}
{showGitTools && (
<div className="relative group/git">
diff --git a/src/hooks/mutation/use-switch-acp-model.ts b/src/hooks/mutation/use-switch-acp-model.ts
index f4b816b03c..3c54adff5b 100644
--- a/src/hooks/mutation/use-switch-acp-model.ts
+++ b/src/hooks/mutation/use-switch-acp-model.ts
@@ -1,7 +1,17 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import AgentProfilesService, {
+ type AgentProfileListResponse,
+} from "#/api/agent-profiles-service/agent-profiles-service.api";
import SettingsService from "#/api/settings-service/settings-service.api";
-import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import { mergeAgentProfileSaveInput } from "#/components/features/settings/agent-profiles/merge-agent-profile-save-input";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ AGENT_PROFILES_QUERY_KEYS,
+ AGENT_PROFILES_RETRY_OPTIONS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+import { agentProfileDetailQueryKey } from "#/hooks/query/use-active-acp-profile-detail";
import { invalidateConversationQueries } from "./conversation-mutation-utils";
interface SwitchAcpModelVars {
@@ -9,8 +19,7 @@ interface SwitchAcpModelVars {
* When set, the ACP conversation's running model is swapped live via the
* wrapper's ``session/set_model`` (POST /switch_acp_model) and the user's
* saved default is untouched. When null (home page / no session), the model
- * is persisted as the agent-settings default so the next conversation
- * created here inherits it.
+ * is persisted as the default the next conversation launches with.
*/
conversationId: string | null;
model: string;
@@ -19,15 +28,24 @@ interface SwitchAcpModelVars {
/**
* ACP analog of {@link useSwitchLlmProfile}. Switches the ACP model
* per-conversation when called from inside a conversation (live in-place model
- * switch); persists it as the agent-settings default when called from the home
- * page (no live session to switch โ€” the agent-server returns 409 before the
- * first message, so we write the default the next conversation inherits).
+ * switch; a created-but-not-yet-run conversation is a persist-only deferral on
+ * the server, so blank conversations work too); persists it as the launch
+ * default when called from the home page.
+ *
+ * The home-page persist target is the **active ACP AgentProfile**: profile
+ * launches resolve the agent server-side purely from the stored profile
+ * (``agent_profile_id`` and ``agent_settings`` are mutually exclusive launch
+ * sources), so writing ``agent_settings.acp_model`` would not affect them.
+ * Only when no ACP profile is active (a legacy backend without the
+ * /api/agent-profiles surface) does the write fall back to the
+ * ``agent_settings_diff`` the legacy launch path reads.
*
* Invalidates the same conversation/settings query keys the profile hook does
* so the chat-input model chip + conversation chip refresh with the new model.
*/
export const useSwitchAcpModel = () => {
const queryClient = useQueryClient();
+ const { backend, orgId } = useActiveBackend();
return useMutation({
mutationFn: async ({ conversationId, model }: SwitchAcpModelVars) => {
@@ -38,7 +56,49 @@ export const useSwitchAcpModel = () => {
);
return;
}
- // Home page / no session: persist as the agent-settings default. The
+
+ // Home page: resolve the active profile from the shared query cache
+ // (same keys/retry policy as useCreateConversation's launch path, so a
+ // pick can't disagree with what a subsequent send would launch).
+ let agentProfiles: AgentProfileListResponse | undefined;
+ try {
+ agentProfiles = await queryClient.ensureQueryData({
+ queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backend.id, orgId],
+ queryFn: AgentProfilesService.listProfiles,
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ });
+ } catch {
+ // Profiles unavailable โ†’ legacy agent_settings persist below.
+ }
+ const activeProfile = agentProfiles?.profiles?.find(
+ (profile) =>
+ profile.id != null &&
+ profile.id === agentProfiles?.active_agent_profile_id,
+ );
+
+ if (activeProfile?.agent_kind === "acp") {
+ // Merge over the stored profile so a model-only pick can't wipe the
+ // fields this surface doesn't model (command, session mode, โ€ฆ).
+ const detail = await queryClient.ensureQueryData({
+ queryKey: agentProfileDetailQueryKey(
+ backend.id,
+ orgId,
+ activeProfile.name,
+ ),
+ queryFn: () => AgentProfilesService.getProfile(activeProfile.name),
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ });
+ await AgentProfilesService.saveProfile(
+ activeProfile.name,
+ mergeAgentProfileSaveInput(detail.profile, {
+ agent_kind: "acp",
+ acp_model: model,
+ }),
+ );
+ return;
+ }
+
+ // Legacy/no-profile backends: persist as the agent-settings default. The
// backend deep-merges ``agent_settings_diff`` into the existing
// ``agent_settings`` dict, so a scalar ``acp_model`` diff updates only
// the model and preserves the selected provider + command.
@@ -52,16 +112,22 @@ export const useSwitchAcpModel = () => {
} else {
// Mirror useSwitchLlmProfile's home-page path: clear the stale settings
// cache so the next conversation-start reads the newly saved default,
- // and refetch the settings query so the home-page chip updates.
+ // and refetch the settings query so the home-page chip updates. The
+ // agent-profiles prefix covers both the list and the detail entry the
+ // profile-persist path just rewrote.
SettingsService.invalidateCache();
queryClient.invalidateQueries({
queryKey: SETTINGS_QUERY_KEYS.personal(),
});
+ queryClient.invalidateQueries({
+ queryKey: AGENT_PROFILES_QUERY_KEYS.all,
+ });
}
},
// 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.
+ // toast reports a failed switch / profile or settings write rather than
+ // swallowing it.
});
};
diff --git a/src/hooks/query/use-active-acp-profile-detail.ts b/src/hooks/query/use-active-acp-profile-detail.ts
new file mode 100644
index 0000000000..c3933e5bbe
--- /dev/null
+++ b/src/hooks/query/use-active-acp-profile-detail.ts
@@ -0,0 +1,68 @@
+import { useQuery } from "@tanstack/react-query";
+import type { ACPAgentProfile } from "@openhands/typescript-client";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
+import { useActiveAgentProfile } from "#/hooks/use-active-agent-profile";
+import {
+ CONFIG_CACHE_OPTIONS,
+ AGENT_PROFILES_QUERY_KEYS,
+ AGENT_PROFILES_RETRY_OPTIONS,
+} from "./query-keys";
+
+/**
+ * Cache key for one profile's full detail. Lives under the agent-profiles
+ * prefix on purpose: activate/save/delete invalidate that prefix, so the
+ * detail refetches for free. (`useActivateAgentProfile.onMutate` also
+ * `setQueriesData`s the prefix, writing a stray `active_agent_profile_id`
+ * onto this entry โ€” benign, consumers only read `.profile`.) Shared with
+ * `useSwitchAcpModel`, which `ensureQueryData`s the same entry.
+ */
+export function agentProfileDetailQueryKey(
+ backendId: string,
+ orgId: string | null | undefined,
+ name: string,
+) {
+ return [
+ ...AGENT_PROFILES_QUERY_KEYS.all,
+ backendId,
+ orgId,
+ "detail",
+ name,
+ ] as const;
+}
+
+/**
+ * Full detail of the active AgentProfile when it is ACP and no conversation is
+ * open. `AgentProfileSummary` carries no `acp_server`/`acp_model`, and profile
+ * activation never writes `settings.agent_settings` โ€” so the home-page ACP
+ * model picker must read the active profile's own fields (the conversation
+ * launch source) rather than the possibly-stale global agent settings.
+ *
+ * Returns the ACP-narrowed profile, or `null` while loading / when the active
+ * profile isn't ACP / on legacy backends without the profiles surface (callers
+ * fall back to `settings.agent_settings` there).
+ */
+export function useActiveAcpProfileDetail(): ACPAgentProfile | null {
+ const { backend, orgId } = useActiveBackend();
+ const { conversationId } = useOptionalConversationId();
+ const { activeProfile } = useActiveAgentProfile();
+ const activeAcpProfileName =
+ activeProfile?.agent_kind === "acp" ? activeProfile.name : null;
+
+ const { data } = useQuery({
+ queryKey: agentProfileDetailQueryKey(
+ backend.id,
+ orgId,
+ activeAcpProfileName ?? "",
+ ),
+ queryFn: () => AgentProfilesService.getProfile(activeAcpProfileName!),
+ enabled: !conversationId && activeAcpProfileName != null,
+ ...CONFIG_CACHE_OPTIONS,
+ ...AGENT_PROFILES_RETRY_OPTIONS,
+ meta: { disableToast: true },
+ });
+
+ const profile = data?.profile;
+ return profile?.agent_kind === "acp" ? profile : null;
+}
diff --git a/src/hooks/use-chat-input-llm-profile-state.ts b/src/hooks/use-chat-input-llm-profile-state.ts
index f2894f4e1c..e986e95987 100644
--- a/src/hooks/use-chat-input-llm-profile-state.ts
+++ b/src/hooks/use-chat-input-llm-profile-state.ts
@@ -4,6 +4,7 @@ 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 { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-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";
@@ -17,23 +18,31 @@ export interface ChatInputLlmProfileState {
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).
+ * Whether picking a profile here would actually land. False on a cloud
+ * start-task route and for a cloud member on the home page; the surfaces
+ * still name the active profile, they just drop the selectable rows.
+ */
+ canSwitchProfile: boolean;
+ /**
+ * Switch the LLM profile: live via `/switch_profile` when inside a
+ * conversation, or activate it globally when on the home page (no
+ * conversation) โ€” see {@link useSwitchLlmProfile}.
*/
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
+ * Backs the OpenHands LLM-profile switcher pill, both on the home page (where
+ * a pick activates the profile globally so the next conversation launches
+ * with it) and inside a conversation (live swap). The ACP analog is
+ * {@link useChatInputModelState}. Mirrors 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 canManageOrgProfiles = useCanManageOrgProfiles();
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
@@ -72,12 +81,21 @@ export function useChatInputLlmProfileState(): ChatInputLlmProfileState {
conversationModel ??
null;
+ // A home pick activates the profile account-wide โ€” on cloud that's the
+ // org-gated activate endpoint a member can only 403 on. A cloud `task-โ€ฆ`
+ // route has no real conversation id yet, so the per-conversation
+ // /switch_profile would 404. Either way the pill still names the active
+ // profile; only the selectable rows drop out.
+ const isTaskRoute = conversationId?.startsWith("task-") ?? false;
+ const canSwitchProfile =
+ !isTaskRoute && (!!conversationId || canManageOrgProfiles);
+
const selectProfile = useCallback(
(profileName: string) => {
- if (profileName === currentProfileName) return;
+ if (!canSwitchProfile || profileName === currentProfileName) return;
switchAndLog(conversationId, profileName);
},
- [conversationId, currentProfileName, switchAndLog],
+ [canSwitchProfile, conversationId, currentProfileName, switchAndLog],
);
return {
@@ -86,6 +104,7 @@ export function useChatInputLlmProfileState(): ChatInputLlmProfileState {
currentProfileModel,
isLoading,
isSwitching,
+ canSwitchProfile,
selectProfile,
};
}
diff --git a/src/hooks/use-chat-input-model-state.ts b/src/hooks/use-chat-input-model-state.ts
index f5cb99f36c..6a81e52505 100644
--- a/src/hooks/use-chat-input-model-state.ts
+++ b/src/hooks/use-chat-input-model-state.ts
@@ -4,6 +4,9 @@ import {
type AcpModelContext,
useAcpModelContext,
} from "#/hooks/use-acp-model-context";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useCanManageOrgProfiles } from "#/hooks/use-can-manage-org-profiles";
+import { useActiveAcpProfileDetail } from "#/hooks/query/use-active-acp-profile-detail";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import {
getAcpPreferredDefaultModel,
@@ -28,6 +31,14 @@ export function useChatInputModelState(): ChatInputModelState {
const { data: conversation } = useActiveConversation();
const { data: settings } = useSettings();
const { conversationId } = useOptionalConversationId();
+ const { backend } = useActiveBackend();
+ const canManageOrgProfiles = useCanManageOrgProfiles();
+ // The active ACP AgentProfile's own fields are the conversation launch
+ // source (activation never writes agent_settings, so the global settings
+ // may describe a different provider). Null in a conversation, while
+ // loading, when the active profile isn't ACP, or on legacy backends
+ // without the profiles surface โ€” settings are the fallback in that window.
+ const activeAcpProfile = useActiveAcpProfileDetail();
const {
isActiveAcpConversation,
isHomeAcp,
@@ -36,19 +47,28 @@ export function useChatInputModelState(): ChatInputModelState {
destinationLabel,
} = useAcpModelContext();
+ const settingsAcpServerKey =
+ typeof settings?.agent_settings?.acp_server === "string"
+ ? settings.agent_settings.acp_server
+ : null;
const acpServerKey = isActiveAcpConversation
? conversation?.acp_server
: isHomeAcp
- ? typeof settings?.agent_settings?.acp_server === "string"
- ? settings.agent_settings.acp_server
- : null
+ ? (activeAcpProfile?.acp_server ?? settingsAcpServerKey)
: null;
const acpProvider = isAcpContext ? getAcpProvider(acpServerKey) : undefined;
- const acpConfiguredModel =
+ const settingsAcpModel =
typeof settings?.agent_settings?.acp_model === "string"
? settings.agent_settings.acp_model
: null;
+ // Home: read the model from the same source as the server key โ€” mixing the
+ // profile's provider with a stale settings model could pair e.g. a codex
+ // provider with a claude model.
+ const acpConfiguredModel =
+ isHomeAcp && activeAcpProfile
+ ? activeAcpProfile.acp_model
+ : settingsAcpModel;
let currentModelId: string | null = null;
if (isActiveAcpConversation) {
@@ -77,7 +97,13 @@ export function useChatInputModelState(): ChatInputModelState {
? (labelForAcpModel(acpServerKey, currentModelId) ?? currentModelId)
: currentModelId;
const availableAcpModels = acpProvider?.available_models ?? [];
- const showAcpPicker = isAcpContext && availableAcpModels.length > 0;
+ // A home-page pick persists into the active ACP profile, which on cloud is
+ // org-owned โ€” hide the selectable rows from members who'd only get a 403.
+ // Conversation-scoped switches (blank or started) stay member-allowed.
+ const canPersistHomeAcpModel =
+ !isHomeAcp || backend.kind !== "cloud" || canManageOrgProfiles;
+ const showAcpPicker =
+ isAcpContext && availableAcpModels.length > 0 && canPersistHomeAcpModel;
const switchConversationId = isActiveAcpConversation
? (conversationId ?? null)
: null;
diff --git a/src/hooks/use-chat-input-profile-state.ts b/src/hooks/use-chat-input-profile-state.ts
index 57b3cbb883..18ed5275a0 100644
--- a/src/hooks/use-chat-input-profile-state.ts
+++ b/src/hooks/use-chat-input-profile-state.ts
@@ -84,9 +84,16 @@ export function useChatInputProfileState(): ChatInputProfileState {
variables.plugins = metadata.plugins;
}
- createConversation.mutate(variables, {
- onSuccess: (data) => navigate(`/conversations/${data.conversation_id}`),
- });
+ // mutateAsync, not mutate-scoped callbacks: this hook lives inside the
+ // tools-menu content, which unmounts as soon as a profile is picked, and
+ // React Query drops mutate-scoped callbacks on unmount โ€” the replacement
+ // conversation would be created without ever navigating to it. The
+ // promise (and the navigate closure) survive the unmount. Errors are
+ // already surfaced by the global mutation toast; swallow the rejection.
+ createConversation
+ .mutateAsync(variables)
+ .then((data) => navigate(`/conversations/${data.conversation_id}`))
+ .catch(() => {});
},
[
activateProfile,
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 39ba4c4459..03a8e18dfd 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -2379,6 +2379,23 @@
"uk": "ะŸั€ะพั„ั–ะปัŒ ะฐะณะตะฝั‚ะฐ",
"ca": "Perfil d'agent"
},
+ "CHAT$SWITCH_AGENT_PROFILE": {
+ "en": "Switch agent profile",
+ "ja": "ใ‚จใƒผใ‚ธใ‚งใƒณใƒˆใƒ—ใƒญใƒ•ใ‚กใ‚คใƒซใ‚’ๅˆ‡ใ‚Šๆ›ฟใˆ",
+ "zh-CN": "ๅˆ‡ๆขไปฃ็†้…็ฝฎๆ–‡ไปถ",
+ "zh-TW": "ๅˆ‡ๆ›ไปฃ็†่จญๅฎšๆช”",
+ "ko-KR": "์—์ด์ „ํŠธ ํ”„๋กœํ•„ ์ „ํ™˜",
+ "no": "Bytt agentprofil",
+ "it": "Cambia profilo agente",
+ "pt": "Trocar perfil de agente",
+ "es": "Cambiar perfil de agente",
+ "ar": "ุชุจุฏูŠู„ ู…ู„ู ุชุนุฑูŠู ุงู„ูˆูƒูŠู„",
+ "fr": "Changer de profil d'agent",
+ "tr": "Ajan profilini deฤŸiลŸtir",
+ "de": "Agentenprofil wechseln",
+ "uk": "ะ—ะผั–ะฝะธั‚ะธ ะฟั€ะพั„ั–ะปัŒ ะฐะณะตะฝั‚ะฐ",
+ "ca": "Canvia el perfil d'agent"
+ },
"CHAT$MANAGE_AGENT_PROFILES": {
"en": "Manage agent profiles",
"ja": "ใ‚จใƒผใ‚ธใ‚งใƒณใƒˆใƒ—ใƒญใƒ•ใ‚กใ‚คใƒซใ‚’็ฎก็†",