Skip to content

🙌 OpenHands: AI-Driven Development

feat(chat): add /model slash command to list and switch LLM profiles (#14288)

Vasco Schiavo34058db51aa8
diff --git a/frontend/__tests__/components/chat/model-messages.test.tsx b/frontend/__tests__/components/chat/model-messages.test.tsx
new file mode 100644
index 0000000000..29ce3f580e
--- /dev/null
+++ b/frontend/__tests__/components/chat/model-messages.test.tsx
@@ -0,0 +1,154 @@
+import React from "react";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";
+import { ModelMessages } from "#/components/features/chat/model-messages";
+import { useModelStore } from "#/stores/model-store";
+
+// Trans needs an i18next instance to render — without one, it emits nothing
+// in the test env. Render a deterministic string so we can assert on it; the
+// mocked `cmd` slot wraps `values.name` in a <strong> so MonoComponent's
+// semantics are exercised even though the real component isn't mounted.
+vi.mock("react-i18next", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-i18next")>();
+ return {
+ ...actual,
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: "en", exists: () => false },
+ }),
+ Trans: ({
+ i18nKey,
+ values,
+ components,
+ }: {
+ i18nKey: string;
+ values?: Record<string, string>;
+ components?: Record<string, React.ReactElement>;
+ }) => {
+ const cmd = components?.cmd;
+ return (
+ <span>
+ {`${i18nKey}:`}
+ {cmd ? React.cloneElement(cmd, {}, values?.name ?? "") : values?.name}
+ </span>
+ );
+ },
+ };
+});
+
+const CONV = "conv-1";
+
+const profile = (
+ name: string,
+ overrides: Partial<LlmProfileSummary> = {},
+): LlmProfileSummary => ({
+ name,
+ model: "anthropic/claude-sonnet-4-6",
+ base_url: null,
+ api_key_set: true,
+ ...overrides,
+});
+
+describe("<ModelMessages />", () => {
+ beforeEach(() => {
+ useModelStore.setState({ entriesByConversation: {} });
+ });
+
+ it("renders nothing when there are no entries", () => {
+ const { container } = render(
+ <ModelMessages conversationId={CONV} anchorEventId={null} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders the empty-profiles hint", () => {
+ useModelStore.getState().show(CONV, null, []);
+ render(<ModelMessages conversationId={CONV} anchorEventId={null} />);
+ expect(screen.getByText("MODEL$NO_SAVED_PROFILES")).toBeInTheDocument();
+ expect(screen.getByText("MODEL$NO_PROFILES_HINT")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /got it/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("starts collapsed and reveals profile rows then row details on expansion", async () => {
+ useModelStore
+ .getState()
+ .show(CONV, null, [profile("default"), profile("scratch")]);
+ const user = userEvent.setup();
+ render(<ModelMessages conversationId={CONV} anchorEventId={null} />);
+
+ expect(screen.getByText("MODEL$AVAILABLE_PROFILES")).toBeInTheDocument();
+ // Outer toggle is collapsed: profile rows are not in the document yet.
+ expect(
+ screen.queryByRole("button", { name: /default/i }),
+ ).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /expand/i }));
+
+ // Profile rows are now visible, but per-row details remain collapsed.
+ expect(screen.queryByText(/api_key:/i)).toBeNull();
+
+ await user.click(screen.getByRole("button", { name: /default/i }));
+ expect(screen.getByText(/api_key:\s+set/i)).toBeInTheDocument();
+ });
+
+ it("only renders entries whose anchor matches the prop", () => {
+ useModelStore.getState().show(CONV, null, [profile("default")]);
+ useModelStore.getState().show(CONV, "evt-1", [profile("scratch")]);
+
+ // Anchor null → only the first entry is visible.
+ const { unmount } = render(
+ <ModelMessages conversationId={CONV} anchorEventId={null} />,
+ );
+ expect(screen.getAllByTestId("model-messages")).toHaveLength(1);
+ expect(screen.getByText("MODEL$AVAILABLE_PROFILES")).toBeInTheDocument();
+ unmount();
+
+ // Anchor "evt-1" → only the second entry is visible (different profile name).
+ render(<ModelMessages conversationId={CONV} anchorEventId="evt-1" />);
+ expect(screen.getByText("MODEL$AVAILABLE_PROFILES")).toBeInTheDocument();
+ });
+
+ it("does not render entries from other conversations", () => {
+ useModelStore.getState().show("other-conv", null, [profile("default")]);
+ const { container } = render(
+ <ModelMessages conversationId={CONV} anchorEventId={null} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders a switch entry with the profile name in a <strong>", () => {
+ useModelStore.getState().recordSwitch(CONV, null, "gpt-5");
+ render(<ModelMessages conversationId={CONV} anchorEventId={null} />);
+
+ // Switch branch is taken: the SWITCHED_TO_PROFILE key is rendered, and
+ // none of the list-branch keys are.
+ expect(screen.getByText(/MODEL\$SWITCHED_TO_PROFILE/)).toBeInTheDocument();
+ expect(screen.queryByText("MODEL$AVAILABLE_PROFILES")).toBeNull();
+ expect(screen.queryByText("MODEL$NO_SAVED_PROFILES")).toBeNull();
+
+ // The profile name renders inside MonoComponent's <strong> wrapper.
+ const name = screen.getByText("gpt-5");
+ expect(name.tagName).toBe("STRONG");
+ expect(name.className).toContain("font-mono");
+ });
+
+ it("filters switch entries by anchor like list entries", () => {
+ useModelStore.getState().recordSwitch(CONV, "evt-77", "gpt-5");
+ useModelStore.getState().recordSwitch(CONV, null, "claude-sonnet");
+
+ const { unmount } = render(
+ <ModelMessages conversationId={CONV} anchorEventId={null} />,
+ );
+ expect(screen.getByText("claude-sonnet")).toBeInTheDocument();
+ expect(screen.queryByText("gpt-5")).toBeNull();
+ unmount();
+
+ render(<ModelMessages conversationId={CONV} anchorEventId="evt-77" />);
+ expect(screen.getByText("gpt-5")).toBeInTheDocument();
+ expect(screen.queryByText("claude-sonnet")).toBeNull();
+ });
+});
diff --git a/frontend/__tests__/components/features/conversation/archived-conversation-view.test.tsx b/frontend/__tests__/components/features/conversation/archived-conversation-view.test.tsx
index a4ddb7dcdd..31f385470b 100644
--- a/frontend/__tests__/components/features/conversation/archived-conversation-view.test.tsx
+++ b/frontend/__tests__/components/features/conversation/archived-conversation-view.test.tsx
@@ -89,6 +89,7 @@ vi.mock("#/components/v1/chat", () => ({
),
shouldRenderEvent: () => true,
hasUserEvent: () => false,
+ getRenderedV1Events: (events: unknown[]) => events,
}));
const createQueryClient = () =>
diff --git a/frontend/__tests__/hooks/chat/use-model-interceptor.test.ts b/frontend/__tests__/hooks/chat/use-model-interceptor.test.ts
new file mode 100644
index 0000000000..1e534d065c
--- /dev/null
+++ b/frontend/__tests__/hooks/chat/use-model-interceptor.test.ts
@@ -0,0 +1,265 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";
+import { useModelInterceptor } from "#/hooks/chat/use-model-interceptor";
+import { useEventStore } from "#/stores/use-event-store";
+import { useModelStore } from "#/stores/model-store";
+
+const renderInterceptor = (
+ conversationId: string | null,
+ onSubmit: (m: string) => void,
+) => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+ return {
+ queryClient,
+ ...renderHook(() => useModelInterceptor(conversationId, onSubmit), {
+ wrapper,
+ }),
+ };
+};
+
+const mockListProfiles = vi.hoisted(() =>
+ vi.fn<
+ () => Promise<{
+ profiles: LlmProfileSummary[];
+ active_profile: string | null;
+ }>
+ >(),
+);
+const mockSwitchProfile = vi.hoisted(() =>
+ vi.fn<(id: string, name: string) => Promise<void>>(),
+);
+const mockDisplayErrorToast = vi.hoisted(() => vi.fn<(msg: string) => void>());
+const mockDisplaySuccessToast = vi.hoisted(() =>
+ vi.fn<(msg: string) => void>(),
+);
+
+vi.mock("#/api/settings-service/profiles-service.api", () => ({
+ default: { listProfiles: () => mockListProfiles() },
+}));
+
+vi.mock("#/api/conversation-service/v1-conversation-service.api", () => ({
+ default: {
+ switchProfile: (id: string, name: string) => mockSwitchProfile(id, name),
+ },
+}));
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: (msg: string) => mockDisplayErrorToast(msg),
+ displaySuccessToast: (msg: string) => mockDisplaySuccessToast(msg),
+}));
+
+const CONV = "conv-1";
+const entries = () =>
+ useModelStore.getState().entriesByConversation[CONV] ?? [];
+
+describe("useModelInterceptor", () => {
+ beforeEach(() => {
+ useModelStore.setState({ entriesByConversation: {} });
+ useEventStore.setState({ events: [], uiEvents: [] });
+ mockListProfiles.mockReset();
+ mockSwitchProfile.mockReset();
+ mockDisplayErrorToast.mockReset();
+ mockDisplaySuccessToast.mockReset();
+ });
+
+ it("falls through to onSubmit for non-/model messages", () => {
+ const onSubmit = vi.fn();
+ const { result } = renderInterceptor(CONV, onSubmit);
+ act(() => result.current("hello world"));
+ expect(onSubmit).toHaveBeenCalledWith("hello world");
+ expect(mockListProfiles).not.toHaveBeenCalled();
+ expect(mockSwitchProfile).not.toHaveBeenCalled();
+ });
+
+ it("intercepts bare /model and pushes the listed profiles to the store", async () => {
+ mockListProfiles.mockResolvedValueOnce({
+ profiles: [
+ {
+ name: "default",
+ model: "anthropic/claude-sonnet-4-6",
+ base_url: null,
+ api_key_set: true,
+ },
+ ],
+ active_profile: "default",
+ });
+ const onSubmit = vi.fn();
+ const { result } = renderInterceptor(CONV, onSubmit);
+
+ act(() => result.current("/model"));
+
+ expect(onSubmit).not.toHaveBeenCalled();
+ await waitFor(() => expect(entries()).toHaveLength(1));
+ expect(entries()[0]).toMatchObject({
+ anchorEventId: null,
+ profiles: [{ name: "default" }],
+ });
+ });
+
+ it("anchors to the latest *rendered* event, skipping events filtered out by shouldRenderEvent", async () => {
+ const renderedMessage = {
+ id: "evt-77",
+ timestamp: "2026-05-01T10:00:00Z",
+ source: "user",
+ llm_message: { role: "user", content: "hi" },
+ };
+ // ConversationStateUpdateEvent is excluded by shouldRenderEvent — if the
+ // interceptor anchored to it the toggle would have no slot to mount in.
+ const trailingStateUpdate = {
+ id: "evt-78",
+ timestamp: "2026-05-01T10:00:01Z",
+ source: "agent",
+ kind: "ConversationStateUpdateEvent",
+ key: "execution_status",
+ };
+ useEventStore.setState({
+ events: [],
+ uiEvents: [renderedMessage as never, trailingStateUpdate as never],
+ });
+ mockListProfiles.mockResolvedValueOnce({
+ profiles: [
+ {
+ name: "default",
+ model: "anthropic/claude-sonnet-4-6",
+ base_url: null,
+ api_key_set: true,
+ },
+ ],
+ active_profile: "default",
+ });
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model"));
+
+ await waitFor(() => expect(entries()).toHaveLength(1));
+ expect(entries()[0].anchorEventId).toBe("evt-77");
+ });
+
+ it("intercepts /model <name> and switches via V1ConversationService", async () => {
+ mockSwitchProfile.mockResolvedValueOnce(undefined);
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model gpt-5"));
+
+ await waitFor(() =>
+ expect(mockSwitchProfile).toHaveBeenCalledWith(CONV, "gpt-5"),
+ );
+ // No success toast — the chat info block (recorded in the store) is the
+ // sole user-visible confirmation; toast would be redundant.
+ expect(mockDisplaySuccessToast).not.toHaveBeenCalled();
+ });
+
+ it("records a switch entry in the store after a successful /model <name>", async () => {
+ mockSwitchProfile.mockResolvedValueOnce(undefined);
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model gpt-5"));
+
+ await waitFor(() => expect(entries()).toHaveLength(1));
+ expect(entries()[0]).toMatchObject({
+ anchorEventId: null,
+ profiles: [],
+ switchedTo: "gpt-5",
+ });
+ });
+
+ it("anchors the switch entry to the latest rendered event", async () => {
+ const renderedMessage = {
+ id: "evt-91",
+ timestamp: "2026-05-01T10:00:00Z",
+ source: "user",
+ llm_message: { role: "user", content: "hi" },
+ };
+ useEventStore.setState({
+ events: [],
+ uiEvents: [renderedMessage as never],
+ });
+ mockSwitchProfile.mockResolvedValueOnce(undefined);
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model gpt-5"));
+
+ await waitFor(() => expect(entries()).toHaveLength(1));
+ expect(entries()[0].anchorEventId).toBe("evt-91");
+ expect(entries()[0].switchedTo).toBe("gpt-5");
+ });
+
+ it("does not record a switch entry when switchProfile rejects", async () => {
+ mockSwitchProfile.mockRejectedValueOnce({
+ response: { data: { detail: "Profile 'ghost' not found" } },
+ });
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model ghost"));
+
+ await waitFor(() => expect(mockDisplayErrorToast).toHaveBeenCalled());
+ expect(entries()).toEqual([]);
+ });
+
+ it("invalidates the active conversation query after a successful switch", async () => {
+ mockSwitchProfile.mockResolvedValueOnce(undefined);
+ const { result, queryClient } = renderInterceptor(CONV, vi.fn());
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+
+ act(() => result.current("/model gpt-5"));
+
+ await waitFor(() =>
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: ["user", "conversation", CONV],
+ }),
+ );
+ });
+
+ it("falls back to the i18n switch-failed key when no error detail is present", async () => {
+ mockSwitchProfile.mockRejectedValueOnce({});
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model gpt-5"));
+
+ await waitFor(() =>
+ expect(mockDisplayErrorToast).toHaveBeenCalledWith("MODEL$SWITCH_FAILED"),
+ );
+ });
+
+ it("falls back to the i18n list-failed key when listProfiles rejects without a message", async () => {
+ mockListProfiles.mockRejectedValueOnce({});
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model"));
+
+ await waitFor(() =>
+ expect(mockDisplayErrorToast).toHaveBeenCalledWith("MODEL$LIST_FAILED"),
+ );
+ });
+
+ it("surfaces backend detail when switchProfile rejects", async () => {
+ mockSwitchProfile.mockRejectedValueOnce({
+ response: { data: { detail: "Profile 'ghost' not found" } },
+ });
+ const { result } = renderInterceptor(CONV, vi.fn());
+
+ act(() => result.current("/model ghost"));
+
+ await waitFor(() =>
+ expect(mockDisplayErrorToast).toHaveBeenCalledWith(
+ "Profile 'ghost' not found",
+ ),
+ );
+ });
+
+ it("falls through when conversationId is null (feature off for V0)", () => {
+ const onSubmit = vi.fn();
+ const { result } = renderInterceptor(null, onSubmit);
+ act(() => result.current("/model"));
+ expect(onSubmit).toHaveBeenCalledWith("/model");
+ expect(mockListProfiles).not.toHaveBeenCalled();
+ expect(mockSwitchProfile).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/__tests__/stores/model-store.test.ts b/frontend/__tests__/stores/model-store.test.ts
new file mode 100644
index 0000000000..6a43bc7b36
--- /dev/null
+++ b/frontend/__tests__/stores/model-store.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { useModelStore } from "#/stores/model-store";
+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";
+
+const CONV_A = "conv-a";
+const CONV_B = "conv-b";
+
+const profile = (name: string): LlmProfileSummary => ({
+ name,
+ model: "anthropic/claude-sonnet-4-6",
+ base_url: null,
+ api_key_set: true,
+});
+
+const entriesFor = (conv: string) =>
+ useModelStore.getState().entriesByConversation[conv] ?? [];
+
+describe("model store", () => {
+ beforeEach(() => {
+ useModelStore.setState({ entriesByConversation: {} });
+ });
+
+ it("show appends an entry scoped to the given conversation", () => {
+ useModelStore.getState().show(CONV_A, null, [profile("default")]);
+ expect(entriesFor(CONV_A)).toHaveLength(1);
+ expect(entriesFor(CONV_A)[0]).toMatchObject({
+ anchorEventId: null,
+ profiles: [profile("default")],
+ });
+ expect(entriesFor(CONV_B)).toEqual([]);
+ });
+
+ it("show stacks multiple entries in invocation order, preserving anchors", () => {
+ useModelStore.getState().show(CONV_A, null, [profile("a")]);
+ useModelStore.getState().show(CONV_A, "evt-42", [profile("b")]);
+ expect(entriesFor(CONV_A)).toHaveLength(2);
+ expect(entriesFor(CONV_A)[0]).toMatchObject({
+ anchorEventId: null,
+ profiles: [profile("a")],
+ });
+ expect(entriesFor(CONV_A)[1]).toMatchObject({
+ anchorEventId: "evt-42",
+ profiles: [profile("b")],
+ });
+ });
+
+ it("show keeps entries scoped per conversation", () => {
+ useModelStore.getState().show(CONV_A, null, [profile("a")]);
+ useModelStore.getState().show(CONV_B, null, [profile("b")]);
+ expect(entriesFor(CONV_A)).toHaveLength(1);
+ expect(entriesFor(CONV_B)).toHaveLength(1);
+ expect(entriesFor(CONV_A)[0].profiles[0].name).toBe("a");
+ expect(entriesFor(CONV_B)[0].profiles[0].name).toBe("b");
+ });
+
+ it("recordSwitch appends a switch entry tagged with switchedTo", () => {
+ useModelStore.getState().recordSwitch(CONV_A, "evt-7", "gpt-5");
+ expect(entriesFor(CONV_A)).toHaveLength(1);
+ expect(entriesFor(CONV_A)[0]).toMatchObject({
+ anchorEventId: "evt-7",
+ profiles: [],
+ switchedTo: "gpt-5",
+ });
+ expect(entriesFor(CONV_B)).toEqual([]);
+ });
+
+ it("recordSwitch and show stack into the same list in invocation order", () => {
+ useModelStore.getState().show(CONV_A, "evt-1", [profile("default")]);
+ useModelStore.getState().recordSwitch(CONV_A, "evt-2", "gpt-5");
+ expect(entriesFor(CONV_A)).toHaveLength(2);
+ expect(entriesFor(CONV_A)[0].switchedTo).toBeUndefined();
+ expect(entriesFor(CONV_A)[0].profiles).toEqual([profile("default")]);
+ expect(entriesFor(CONV_A)[1].switchedTo).toBe("gpt-5");
+ expect(entriesFor(CONV_A)[1].profiles).toEqual([]);
+ });
+});
diff --git a/frontend/src/api/conversation-service/v1-conversation-service.api.ts b/frontend/src/api/conversation-service/v1-conversation-service.api.ts
index 47f60a4b96..d9ccdbae49 100644
--- a/frontend/src/api/conversation-service/v1-conversation-service.api.ts
+++ b/frontend/src/api/conversation-service/v1-conversation-service.api.ts
@@ -234,6 +234,22 @@ class V1ConversationService {
return data;
}
+ /**
+ * Switch the running conversation's LLM to a saved profile.
+ * Goes through the app-server proxy, which loads the profile from user
+ * settings (with api_key) and hands the LLM to the agent-server's
+ * `switch_llm` endpoint.
+ */
+ static async switchProfile(
+ conversationId: string,
+ profileName: string,
+ ): Promise<void> {
+ await openHands.post(
+ `/api/v1/app-conversations/${conversationId}/switch_profile`,
+ { profile_name: profileName },
+ );
+ }
+
/**
* Resume a V1 conversation
* Uses the custom runtime URL from the conversation
diff --git a/frontend/src/components/features/chat/chat-interface.tsx b/frontend/src/components/features/chat/chat-interface.tsx
index 40722c2aaf..d07a2e76a9 100644
--- a/frontend/src/components/features/chat/chat-interface.tsx
+++ b/frontend/src/components/features/chat/chat-interface.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { convertImageToBase64 } from "#/utils/convert-image-to-base-64";
import { createChatMessage } from "#/services/chat-service";
import { BtwMessages } from "./btw-messages";
+import { ModelMessages } from "./model-messages";
import { InteractiveChatBox } from "./interactive-chat-box";
import { AgentState } from "#/types/agent-state";
import { useFilteredEvents } from "#/hooks/use-filtered-events";
@@ -34,6 +35,7 @@ import { getStatusColor, getStatusText } from "#/utils/utils";
import { useNewConversationCommand } from "#/hooks/mutation/use-new-conversation-command";
import { I18nKey } from "#/i18n/declaration";
import { ArchivedBanner } from "./archived-banner";
+import { useModelStore } from "#/stores/model-store";
export function ChatInterface() {
const { setMessageToSend } = useConversationStore();
@@ -104,6 +106,14 @@ export function ChatInterface() {
const { mutateAsync: uploadFiles } = useUnifiedUploadFiles();
const optimisticUserMessage = getOptimisticUserMessage();
+ const modelEntriesByConversation = useModelStore(
+ (s) => s.entriesByConversation,
+ );
+ const modelEntriesCount =
+ (params.conversationId &&
+ modelEntriesByConversation[params.conversationId]?.length) ||
+ 0;
+ const hasModelEntries = modelEntriesCount > 0;
// Show V1 messages immediately if events exist in store (e.g., remount),
// or once loading completes. This replaces the old transition-observation
@@ -191,6 +201,7 @@ export function ChatInterface() {
v1UiEvents.length,
v0Events.length,
optimisticUserMessage,
+ modelEntriesCount,
scrollDomToBottom,
]);
@@ -236,7 +247,8 @@ export function ChatInterface() {
{!hasSubstantiveAgentActions &&
!optimisticUserMessage &&
!userEventsExist &&
- !isChatLoading && (
+ !isChatLoading &&
+ !hasModelEntries && (
<ChatSuggestions
onSuggestionsClick={(message) => setMessageToSend(message)}
/>
@@ -258,6 +270,10 @@ export function ChatInterface() {
</div>
)}
+ <ModelMessages
+ conversationId={params.conversationId}
+ anchorEventId={null}
+ />
{showV1Messages && v1UserEventsExist && (
<V1Messages messages={v1UiEvents} allEvents={v1FullEvents} />
)}
diff --git a/frontend/src/components/features/chat/interactive-chat-box.tsx b/frontend/src/components/features/chat/interactive-chat-box.tsx
index eaa8532776..22919cf9c7 100644
--- a/frontend/src/components/features/chat/interactive-chat-box.tsx
+++ b/frontend/src/components/features/chat/interactive-chat-box.tsx
@@ -3,6 +3,7 @@ import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { validateFiles } from "#/utils/file-validation";
import { CustomChatInput } from "./custom-chat-input";
import { useBtwInterceptor } from "#/hooks/chat/use-btw-interceptor";
+import { useModelInterceptor } from "#/hooks/chat/use-model-interceptor";
import { AgentState } from "#/types/agent-state";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { GitControlBar } from "./git-control-bar";
@@ -138,13 +139,13 @@ export function InteractiveChatBox({
}
};
- const handleSubmit = useBtwInterceptor(
- conversation?.id ?? null,
- (message) => {
- onSubmit(message, images, files);
- clearAllFiles();
- },
- );
+ const conversationId = conversation?.id ?? null;
+ const submitWithFiles = (message: string) => {
+ onSubmit(message, images, files);
+ clearAllFiles();
+ };
+ const handleAfterModel = useBtwInterceptor(conversationId, submitWithFiles);
+ const handleSubmit = useModelInterceptor(conversationId, handleAfterModel);
const handleSuggestionsClick = (suggestion: string) => {
handleSubmit(suggestion);
diff --git a/frontend/src/components/features/chat/model-messages.tsx b/frontend/src/components/features/chat/model-messages.tsx
new file mode 100644
index 0000000000..783220354d
--- /dev/null
+++ b/frontend/src/components/features/chat/model-messages.tsx
@@ -0,0 +1,119 @@
+import React from "react";
+import { Trans, useTranslation } from "react-i18next";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { useModelStore } from "#/stores/model-store";
+import { Typography } from "#/ui/typography";
+import { I18nKey } from "#/i18n/declaration";
+import { GenericEventMessage } from "./generic-event-message";
+import { MonoComponent } from "./mono-component";
+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";
+
+interface ProfileRowProps {
+ profile: LlmProfileSummary;
+}
+
+function ProfileRow({ profile }: ProfileRowProps) {
+ const [expanded, setExpanded] = React.useState(false);
+
+ return (
+ <div className="border border-neutral-700 rounded-md overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="w-full py-1.5 px-2 text-left flex items-center gap-2 hover:bg-neutral-700 transition-colors cursor-pointer"
+ >
+ <Typography.Text className="text-neutral-300">
+ {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ </Typography.Text>
+ <Typography.Text className="font-semibold text-neutral-200 text-sm">
+ {profile.name}
+ </Typography.Text>
+ </button>
+ {expanded && (
+ <>
+ <hr className="border-neutral-700" />
+ <div className="px-3 py-2 text-xs text-neutral-300 font-mono whitespace-pre-wrap">
+ {`model: ${profile.model ?? "—"}\n` +
+ `base_url: ${profile.base_url ?? "—"}\n` +
+ `api_key: ${profile.api_key_set ? "set" : "not set"}`}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+export interface ModelMessagesProps {
+ conversationId: string | null | undefined;
+ /**
+ * Render only entries anchored to this event id. Use `null` to render the
+ * "no events at the time of /model" entries (top of the chat history).
+ */
+ anchorEventId: string | null;
+}
+
+export function ModelMessages({
+ conversationId,
+ anchorEventId,
+}: ModelMessagesProps) {
+ const { t } = useTranslation();
+ const entriesById = useModelStore((s) => s.entriesByConversation);
+ const allEntries = conversationId ? (entriesById[conversationId] ?? []) : [];
+ const entries = allEntries.filter((e) => e.anchorEventId === anchorEventId);
+
+ if (!conversationId || entries.length === 0) return null;
+
+ return (
+ <div data-testid="model-messages" className="flex flex-col w-full">
+ {entries.map((entry) => {
+ if (entry.switchedTo) {
+ return (
+ <GenericEventMessage
+ key={entry.id}
+ title={
+ <span>
+ <Trans
+ i18nKey={I18nKey.MODEL$SWITCHED_TO_PROFILE}
+ values={{ name: entry.switchedTo }}
+ components={{ cmd: <MonoComponent /> }}
+ />
+ </span>
+ }
+ details={null}
+ />
+ );
+ }
+
+ const isEmpty = entry.profiles.length === 0;
+ return (
+ <GenericEventMessage
+ key={entry.id}
+ title={
+ <span>
+ {isEmpty
+ ? t(I18nKey.MODEL$NO_SAVED_PROFILES)
+ : t(I18nKey.MODEL$AVAILABLE_PROFILES, {
+ count: entry.profiles.length,
+ })}
+ </span>
+ }
+ details={
+ isEmpty ? (
+ <Typography.Text className="text-neutral-300 text-sm px-2 py-1">
+ {t(I18nKey.MODEL$NO_PROFILES_HINT)}
+ </Typography.Text>
+ ) : (
+ <div className="flex flex-col gap-1 mt-1">
+ {entry.profiles.map((p) => (
+ <ProfileRow key={p.name} profile={p} />
+ ))}
+ </div>
+ )
+ }
+ initiallyExpanded={isEmpty}
+ />
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts b/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
index 24a185b111..065ea9a035 100644
--- a/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
+++ b/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
@@ -1,3 +1,4 @@
+import { OpenHandsParsedEvent } from "#/types/core";
import { OpenHandsEvent } from "#/types/v1/core";
import {
isActionEvent,
@@ -7,6 +8,7 @@ import {
isConversationStateUpdateEvent,
isHookExecutionEvent,
isACPToolCallEvent,
+ isV1Event,
} from "#/types/v1/type-guards";
export const shouldRenderEvent = (event: OpenHandsEvent) => {
@@ -68,3 +70,14 @@ export const shouldRenderEvent = (event: OpenHandsEvent) => {
export const hasUserEvent = (events: OpenHandsEvent[]) =>
events.some((event) => event.source === "user");
+
+/**
+ * Narrow a mixed V0/V1 event list to V1 events that actually render in chat.
+ * Single source of truth: callers (e.g. `useFilteredEvents`, slash-command
+ * interceptors that anchor to the latest visible event) MUST use this rather
+ * than re-implementing `isV1Event` + `shouldRenderEvent` chains, so updates
+ * to the rendering rules are picked up everywhere.
+ */
+export const getRenderedV1Events = (
+ events: ReadonlyArray<OpenHandsEvent | OpenHandsParsedEvent>,
+): OpenHandsEvent[] => events.filter(isV1Event).filter(shouldRenderEvent);
diff --git a/frontend/src/components/v1/chat/index.ts b/frontend/src/components/v1/chat/index.ts
index bce6a75795..d3edeb3b8f 100644
--- a/frontend/src/components/v1/chat/index.ts
+++ b/frontend/src/components/v1/chat/index.ts
@@ -5,4 +5,5 @@ export { getEventContent } from "./event-content-helpers/get-event-content";
export {
shouldRenderEvent,
hasUserEvent,
+ getRenderedV1Events,
} from "./event-content-helpers/should-render-event";
diff --git a/frontend/src/components/v1/chat/messages.tsx b/frontend/src/components/v1/chat/messages.tsx
index b0a4450282..aa8fb102c1 100644
--- a/frontend/src/components/v1/chat/messages.tsx
+++ b/frontend/src/components/v1/chat/messages.tsx
@@ -1,8 +1,11 @@
import React from "react";
+import { useParams } from "react-router";
import { OpenHandsEvent } from "#/types/v1/core";
import { EventMessage } from "./event-message";
import { ChatMessage } from "../../features/chat/chat-message";
+import { ModelMessages } from "../../features/chat/model-messages";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
+import { useModelStore } from "#/stores/model-store";
import { usePlanPreviewEvents } from "./hooks/use-plan-preview-events";
// TODO: Implement microagent functionality for V1 when APIs support V1 event IDs
// import { AgentState } from "#/types/agent-state";
@@ -16,6 +19,8 @@ interface MessagesProps {
export const Messages: React.FC<MessagesProps> = React.memo(
({ messages, allEvents }) => {
const { getOptimisticUserMessage } = useOptimisticUserMessageStore();
+ const params = useParams();
+ const conversationId = params.conversationId ?? null;
const optimisticUserMessage = getOptimisticUserMessage();
@@ -23,26 +28,51 @@ export const Messages: React.FC<MessagesProps> = React.memo(
// This ensures only one preview per user message "phase"
const planPreviewEventIds = usePlanPreviewEvents(allEvents);
+ // Compute the set of event ids that have a /model entry anchored to them,
+ // so we only mount <ModelMessages> for events that actually need one
+ // instead of one-per-event with an early-return null.
+ const modelEntries = useModelStore((s) =>
+ conversationId ? s.entriesByConversation[conversationId] : undefined,
+ );
+ const modelAnchorIds = React.useMemo(() => {
+ if (!modelEntries || modelEntries.length === 0) return null;
+ const ids = new Set<string>();
+ for (const entry of modelEntries) {
+ if (entry.anchorEventId !== null) ids.add(entry.anchorEventId);
+ }
+ return ids.size > 0 ? ids : null;
+ }, [modelEntries]);
+
// TODO: Implement microagent functionality for V1 if needed
// For now, we'll skip microagent features
return (
<>
- {messages.map((message, index) => (
- <EventMessage
- key={message.id}
- event={message}
- messages={allEvents}
- isLastMessage={messages.length - 1 === index}
- isInLast10Actions={messages.length - 1 - index < 10}
- planPreviewEventIds={planPreviewEventIds}
- // Microagent props - not implemented yet for V1
- // microagentStatus={undefined}
- // microagentConversationId={undefined}
- // microagentPRUrl={undefined}
- // actions={undefined}
- />
- ))}
+ {messages.map((message, index) => {
+ const messageId = String(message.id);
+ return (
+ <React.Fragment key={message.id}>
+ <EventMessage
+ event={message}
+ messages={allEvents}
+ isLastMessage={messages.length - 1 === index}
+ isInLast10Actions={messages.length - 1 - index < 10}
+ planPreviewEventIds={planPreviewEventIds}
+ // Microagent props - not implemented yet for V1
+ // microagentStatus={undefined}
+ // microagentConversationId={undefined}
+ // microagentPRUrl={undefined}
+ // actions={undefined}
+ />
+ {modelAnchorIds?.has(messageId) && (
+ <ModelMessages
+ conversationId={conversationId}
+ anchorEventId={messageId}
+ />
+ )}
+ </React.Fragment>
+ );
+ })}
{optimisticUserMessage && (
<ChatMessage type="user" message={optimisticUserMessage} />
diff --git a/frontend/src/hooks/chat/use-model-interceptor.ts b/frontend/src/hooks/chat/use-model-interceptor.ts
new file mode 100644
index 0000000000..d69f6000cb
--- /dev/null
+++ b/frontend/src/hooks/chat/use-model-interceptor.ts
@@ -0,0 +1,105 @@
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { useQueryClient } from "@tanstack/react-query";
+import ProfilesService from "#/api/settings-service/profiles-service.api";
+import { getRenderedV1Events } from "#/components/v1/chat";
+import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";
+import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";
+import { I18nKey } from "#/i18n/declaration";
+import { useEventStore } from "#/stores/use-event-store";
+import { useModelStore } from "#/stores/model-store";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { MODEL_COMMAND } from "#/utils/constants";
+
+const MODEL_PREFIX = `${MODEL_COMMAND} `;
+
+/**
+ * Intercepts "/model" submissions:
+ * - "/model" → render an inline list of saved profiles in the chat
+ * - "/model <name>" → switch the running conversation's LLM profile
+ * Anything else (including /model on a V0 conversation) falls through.
+ */
+export const useModelInterceptor = (
+ conversationId: string | null | undefined,
+ onSubmit: (message: string) => void,
+) => {
+ const showProfiles = useModelStore((s) => s.show);
+ const recordSwitch = useModelStore((s) => s.recordSwitch);
+ const queryClient = useQueryClient();
+ const { mutate: switchLlmProfile } = useSwitchLlmProfile();
+ const { t } = useTranslation();
+
+ return useCallback(
+ (message: string) => {
+ const trimmed = message.trim();
+ const isModel =
+ trimmed === MODEL_COMMAND || trimmed.startsWith(MODEL_PREFIX);
+ if (!conversationId || !isModel) {
+ onSubmit(message);
+ return;
+ }
+
+ const arg = trimmed.slice(MODEL_COMMAND.length).trim();
+
+ // Anchor entries to the latest v1 event so they render inline at the
+ // chat position where the user typed /model, instead of always at the
+ // bottom of the chat history. Use the shared `getRenderedV1Events` so
+ // we only anchor to events that are actually rendered — anchoring to a
+ // hidden event (e.g. ConversationStateUpdate) would leave the entry
+ // with no slot to mount in.
+ const renderedEvents = getRenderedV1Events(
+ useEventStore.getState().uiEvents,
+ );
+ const anchorEventId =
+ renderedEvents.length > 0
+ ? String(renderedEvents[renderedEvents.length - 1].id)
+ : null;
+
+ if (!arg) {
+ // Imperative fetch through the query cache so the result populates
+ // the same key `useLlmProfiles` reads, and a recently-fetched list
+ // is reused. `staleTime: 0` forces a fresh fetch each time the user
+ // explicitly asks via /model.
+ queryClient
+ .fetchQuery({
+ queryKey: [LLM_PROFILES_QUERY_KEY],
+ queryFn: ProfilesService.listProfiles,
+ staleTime: 0,
+ })
+ .then(({ profiles }) =>
+ showProfiles(conversationId, anchorEventId, profiles),
+ )
+ .catch((err) =>
+ displayErrorToast(err?.message ?? t(I18nKey.MODEL$LIST_FAILED)),
+ );
+ return;
+ }
+
+ switchLlmProfile(
+ { conversationId, profileName: arg },
+ {
+ onSuccess: () => recordSwitch(conversationId, anchorEventId, arg),
+ onError: (err: unknown) => {
+ const e = err as
+ | { response?: { data?: { detail?: string } }; message?: string }
+ | undefined;
+ displayErrorToast(
+ e?.response?.data?.detail ??
+ e?.message ??
+ t(I18nKey.MODEL$SWITCH_FAILED, { name: arg }),
+ );
+ },
+ },
+ );
+ },
+ [
+ conversationId,
+ onSubmit,
+ showProfiles,
+ recordSwitch,
+ queryClient,
+ switchLlmProfile,
+ t,
+ ],
+ );
+};
diff --git a/frontend/src/hooks/mutation/use-switch-llm-profile.ts b/frontend/src/hooks/mutation/use-switch-llm-profile.ts
new file mode 100644
index 0000000000..d04a9e830a
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-switch-llm-profile.ts
@@ -0,0 +1,25 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
+
+interface SwitchLlmProfileVars {
+ conversationId: string;
+ profileName: string;
+}
+
+export const useSwitchLlmProfile = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ conversationId, profileName }: SwitchLlmProfileVars) =>
+ V1ConversationService.switchProfile(conversationId, profileName),
+ onSuccess: (_data, { conversationId }) => {
+ // Refetch the conversation so the chat header (and anything else
+ // reading `conversation.llm_model`) picks up the new model. The
+ // backend persisted it as part of the switch.
+ queryClient.invalidateQueries({
+ queryKey: ["user", "conversation", conversationId],
+ });
+ },
+ meta: { disableToast: true },
+ });
+};
diff --git a/frontend/src/hooks/use-filtered-events.ts b/frontend/src/hooks/use-filtered-events.ts
index cfc8026016..ac4daa69e4 100644
--- a/frontend/src/hooks/use-filtered-events.ts
+++ b/frontend/src/hooks/use-filtered-events.ts
@@ -6,7 +6,7 @@ import {
hasUserEvent,
} from "#/components/features/chat/event-content-helpers/should-render-event";
import {
- shouldRenderEvent as shouldRenderV1Event,
+ getRenderedV1Events,
hasUserEvent as hasV1UserEvent,
} from "#/components/v1/chat";
import {
@@ -42,7 +42,7 @@ export function useFilteredEvents() {
// Filter V1 events - use uiEvents for rendering (actions replaced by observations)
const v1UiEvents = React.useMemo(
- () => uiEvents.filter(isV1Event).filter(shouldRenderV1Event),
+ () => getRenderedV1Events(uiEvents),
[uiEvents],
);
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index fb4ef76858..c86c40992b 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -936,6 +936,12 @@ export enum I18nKey {
SECRETS$SECRET_ALREADY_EXISTS = "SECRETS$SECRET_ALREADY_EXISTS",
SECRETS$API_KEY_EXAMPLE = "SECRETS$API_KEY_EXAMPLE",
MODEL$CUSTOM_MODEL = "MODEL$CUSTOM_MODEL",
+ MODEL$AVAILABLE_PROFILES = "MODEL$AVAILABLE_PROFILES",
+ MODEL$NO_SAVED_PROFILES = "MODEL$NO_SAVED_PROFILES",
+ MODEL$NO_PROFILES_HINT = "MODEL$NO_PROFILES_HINT",
+ MODEL$SWITCHED_TO_PROFILE = "MODEL$SWITCHED_TO_PROFILE",
+ MODEL$LIST_FAILED = "MODEL$LIST_FAILED",
+ MODEL$SWITCH_FAILED = "MODEL$SWITCH_FAILED",
SECURITY$SELECT_RISK_SEVERITY = "SECURITY$SELECT_RISK_SEVERITY",
SECURITY$DONT_ASK_CONFIRMATION = "SECURITY$DONT_ASK_CONFIRMATION",
SETTINGS$MAXIMUM_BUDGET_USD = "SETTINGS$MAXIMUM_BUDGET_USD",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index dda9c190db..cc90ef79a1 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -15911,6 +15911,108 @@
"uk": "Користувацька модель",
"ca": "Model personalitzat"
},
+ "MODEL$AVAILABLE_PROFILES": {
+ "en": "Available profiles ({{count}})",
+ "ja": "利用可能なプロファイル ({{count}})",
+ "zh-CN": "可用配置文件 ({{count}})",
+ "zh-TW": "可用設定檔 ({{count}})",
+ "ko-KR": "사용 가능한 프로필 ({{count}})",
+ "no": "Tilgjengelige profiler ({{count}})",
+ "it": "Profili disponibili ({{count}})",
+ "pt": "Perfis disponíveis ({{count}})",
+ "es": "Perfiles disponibles ({{count}})",
+ "ar": "الملفات الشخصية المتاحة ({{count}})",
+ "fr": "Profils disponibles ({{count}})",
+ "tr": "Kullanılabilir profiller ({{count}})",
+ "de": "Verfügbare Profile ({{count}})",
+ "uk": "Доступні профілі ({{count}})",
+ "ca": "Perfils disponibles ({{count}})"
+ },
+ "MODEL$NO_SAVED_PROFILES": {
+ "en": "No saved profiles",
+ "ja": "保存されたプロファイルはありません",
+ "zh-CN": "没有已保存的配置文件",
+ "zh-TW": "沒有已儲存的設定檔",
+ "ko-KR": "저장된 프로필 없음",
+ "no": "Ingen lagrede profiler",
+ "it": "Nessun profilo salvato",
+ "pt": "Nenhum perfil salvo",
+ "es": "No hay perfiles guardados",
+ "ar": "لا توجد ملفات شخصية محفوظة",
+ "fr": "Aucun profil enregistré",
+ "tr": "Kaydedilmiş profil yok",
+ "de": "Keine gespeicherten Profile",
+ "uk": "Немає збережених профілів",
+ "ca": "No hi ha perfils desats"
+ },
+ "MODEL$NO_PROFILES_HINT": {
+ "en": "Use the LLM settings page to create a profile, then run /model <name> to switch.",
+ "ja": "LLM設定ページでプロファイルを作成し、/model <name> を実行して切り替えてください。",
+ "zh-CN": "请前往 LLM 设置页面创建配置文件,然后运行 /model <name> 进行切换。",
+ "zh-TW": "請前往 LLM 設定頁面建立設定檔,然後執行 /model <name> 進行切換。",
+ "ko-KR": "LLM 설정 페이지에서 프로필을 만든 다음, /model <name>을 실행하여 전환하세요.",
+ "no": "Bruk LLM-innstillingssiden for å opprette en profil, og kjør deretter /model <name> for å bytte.",
+ "it": "Usa la pagina delle impostazioni LLM per creare un profilo, poi esegui /model <name> per cambiarlo.",
+ "pt": "Use a página de configurações de LLM para criar um perfil e, em seguida, execute /model <name> para alternar.",
+ "es": "Usa la página de configuración de LLM para crear un perfil y luego ejecuta /model <name> para cambiar.",
+ "ar": "استخدم صفحة إعدادات LLM لإنشاء ملف شخصي، ثم نفّذ /model <name> للتبديل.",
+ "fr": "Utilisez la page des paramètres LLM pour créer un profil, puis exécutez /model <name> pour changer.",
+ "tr": "Bir profil oluşturmak için LLM ayarları sayfasını kullanın, ardından geçiş yapmak için /model <name> komutunu çalıştırın.",
+ "de": "Erstelle ein Profil über die LLM-Einstellungsseite und führe dann /model <name> aus, um zu wechseln.",
+ "uk": "Створіть профіль на сторінці налаштувань LLM, а потім виконайте /model <name>, щоб переключитися.",
+ "ca": "Utilitza la pàgina de configuració de LLM per crear un perfil i, a continuació, executa /model <name> per canviar."
+ },
+ "MODEL$SWITCHED_TO_PROFILE": {
+ "en": "ℹ️ Switched to profile <cmd>{{name}}</cmd>",
+ "ja": "ℹ️ プロファイル <cmd>{{name}}</cmd> に切り替えました",
+ "zh-CN": "ℹ️ 已切换到配置文件 <cmd>{{name}}</cmd>",
+ "zh-TW": "ℹ️ 已切換到設定檔 <cmd>{{name}}</cmd>",
+ "ko-KR": "ℹ️ 프로필 <cmd>{{name}}</cmd>(으)로 전환되었습니다",
+ "no": "ℹ️ Byttet til profil <cmd>{{name}}</cmd>",
+ "it": "ℹ️ Passato al profilo <cmd>{{name}}</cmd>",
+ "pt": "ℹ️ Alternado para o perfil <cmd>{{name}}</cmd>",
+ "es": "ℹ️ Cambiado al perfil <cmd>{{name}}</cmd>",
+ "ar": "ℹ️ تم التبديل إلى الملف الشخصي <cmd>{{name}}</cmd>",
+ "fr": "ℹ️ Basculé vers le profil <cmd>{{name}}</cmd>",
+ "tr": "ℹ️ <cmd>{{name}}</cmd> profiline geçildi",
+ "de": "ℹ️ Zu Profil <cmd>{{name}}</cmd> gewechselt",
+ "uk": "ℹ️ Перемкнуто на профіль <cmd>{{name}}</cmd>",
+ "ca": "ℹ️ S'ha canviat al perfil <cmd>{{name}}</cmd>"
+ },
+ "MODEL$LIST_FAILED": {
+ "en": "Failed to list LLM profiles",
+ "ja": "LLMプロファイルの一覧取得に失敗しました",
+ "zh-CN": "获取 LLM 配置文件列表失败",
+ "zh-TW": "取得 LLM 設定檔清單失敗",
+ "ko-KR": "LLM 프로필 목록을 가져오지 못했습니다",
+ "no": "Kunne ikke hente LLM-profiler",
+ "it": "Impossibile elencare i profili LLM",
+ "pt": "Falha ao listar perfis de LLM",
+ "es": "Error al listar perfiles de LLM",
+ "ar": "فشل سرد ملفات LLM الشخصية",
+ "fr": "Échec de la liste des profils LLM",
+ "tr": "LLM profilleri listelenemedi",
+ "de": "LLM-Profile konnten nicht aufgelistet werden",
+ "uk": "Не вдалося отримати список LLM-профілів",
+ "ca": "No s'han pogut llistar els perfils d'LLM"
+ },
+ "MODEL$SWITCH_FAILED": {
+ "en": "Failed to switch to profile '{{name}}'",
+ "ja": "プロファイル '{{name}}' への切り替えに失敗しました",
+ "zh-CN": "切换到配置文件 '{{name}}' 失败",
+ "zh-TW": "切換到設定檔 '{{name}}' 失敗",
+ "ko-KR": "프로필 '{{name}}'(으)로 전환하지 못했습니다",
+ "no": "Kunne ikke bytte til profil '{{name}}'",
+ "it": "Impossibile passare al profilo '{{name}}'",
+ "pt": "Falha ao alternar para o perfil '{{name}}'",
+ "es": "Error al cambiar al perfil '{{name}}'",
+ "ar": "فشل التبديل إلى الملف الشخصي '{{name}}'",
+ "fr": "Échec du basculement vers le profil '{{name}}'",
+ "tr": "'{{name}}' profiline geçilemedi",
+ "de": "Wechsel zu Profil '{{name}}' fehlgeschlagen",
+ "uk": "Не вдалося перемкнутися на профіль '{{name}}'",
+ "ca": "No s'ha pogut canviar al perfil '{{name}}'"
+ },
"SECURITY$SELECT_RISK_SEVERITY": {
"en": "Select risk severity",
"ja": "リスクの重要度を選択",
diff --git a/frontend/src/stores/model-store.ts b/frontend/src/stores/model-store.ts
new file mode 100644
index 0000000000..a47e87a533
--- /dev/null
+++ b/frontend/src/stores/model-store.ts
@@ -0,0 +1,67 @@
+import { create } from "zustand";
+import { devtools } from "zustand/middleware";
+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";
+
+export interface ModelListEntry {
+ id: string;
+ /**
+ * Id of the chat event after which this entry should render, or `null` to
+ * pin it to the top of the chat history (no events at the time of /model).
+ */
+ anchorEventId: string | null;
+ profiles: LlmProfileSummary[];
+ switchedTo?: string;
+}
+
+interface ModelState {
+ entriesByConversation: Record<string, ModelListEntry[]>;
+}
+
+interface ModelActions {
+ show: (
+ conversationId: string,
+ anchorEventId: string | null,
+ profiles: LlmProfileSummary[],
+ ) => void;
+ recordSwitch: (
+ conversationId: string,
+ anchorEventId: string | null,
+ profileName: string,
+ ) => void;
+}
+
+type ModelStore = ModelState & ModelActions;
+
+export const useModelStore = create<ModelStore>()(
+ devtools(
+ (set) => ({
+ entriesByConversation: {},
+ show: (conversationId, anchorEventId, profiles) =>
+ set((s) => ({
+ entriesByConversation: {
+ ...s.entriesByConversation,
+ [conversationId]: [
+ ...(s.entriesByConversation[conversationId] ?? []),
+ { id: crypto.randomUUID(), anchorEventId, profiles },
+ ],
+ },
+ })),
+ recordSwitch: (conversationId, anchorEventId, profileName) =>
+ set((s) => ({
+ entriesByConversation: {
+ ...s.entriesByConversation,
+ [conversationId]: [
+ ...(s.entriesByConversation[conversationId] ?? []),
+ {
+ id: crypto.randomUUID(),
+ anchorEventId,
+ profiles: [],
+ switchedTo: profileName,
+ },
+ ],
+ },
+ })),
+ }),
+ { name: "ModelStore" },
+ ),
+);
diff --git a/frontend/src/utils/constants.ts b/frontend/src/utils/constants.ts
index 5593f6bb0a..d4a7fa0330 100644
--- a/frontend/src/utils/constants.ts
+++ b/frontend/src/utils/constants.ts
@@ -76,6 +76,9 @@ export const EPS = 1.5; // px tolerance for "near min" height comparisons
/** The /btw slash command — asks a side question via the ask_agent endpoint. */
export const BTW_COMMAND = "/btw";
+/** The /model slash command — lists or switches the conversation's LLM profile. */
+export const MODEL_COMMAND = "/model";
+
/** Built-in slash commands surfaced in the menu for V1 conversations. */
export const BUILT_IN_COMMANDS: SlashCommandItem[] = [
{
@@ -96,6 +99,16 @@ export const BUILT_IN_COMMANDS: SlashCommandItem[] = [
},
command: BTW_COMMAND,
},
+ {
+ skill: {
+ name: "model",
+ type: "agentskills",
+ content:
+ "List saved LLM profiles, or switch the conversation LLM profile with /model <name>",
+ triggers: [MODEL_COMMAND],
+ },
+ command: MODEL_COMMAND,
+ },
];
// Skill content metadata prefixes
diff --git a/openhands/app_server/app_conversation/app_conversation_models.py b/openhands/app_server/app_conversation/app_conversation_models.py
index 1d23294476..f52efccb41 100644
--- a/openhands/app_server/app_conversation/app_conversation_models.py
+++ b/openhands/app_server/app_conversation/app_conversation_models.py
@@ -330,6 +330,16 @@ class AppSendMessageRequest(BaseModel):
)
+class SwitchProfileRequest(BaseModel):
+ """Request to switch a running conversation's LLM to a saved profile."""
+
+ profile_name: str = Field(
+ ...,
+ description='Name of a profile previously saved via /api/v1/settings/profiles.',
+ min_length=1,
+ )
+
+
class AppSendMessageResponse(BaseModel):
"""Response from sending a message to a conversation."""
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.py
index c6d8529286..bd6a33f80b 100644
--- a/openhands/app_server/app_conversation/app_conversation_router.py
+++ b/openhands/app_server/app_conversation/app_conversation_router.py
@@ -1,6 +1,8 @@
"""Sandboxed Conversation router for OpenHands App Server."""
import asyncio
+import hashlib
+import json
import logging
import os
import sys
@@ -11,7 +13,7 @@ from typing import Annotated, AsyncGenerator, Literal
from uuid import UUID
import httpx
-from fastapi import APIRouter, HTTPException, Query, Request, Response, status
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from fastapi.responses import JSONResponse, StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
@@ -36,6 +38,7 @@ from openhands.app_server.app_conversation.app_conversation_models import (
HookEventResponse,
HookMatcherResponse,
SkillResponse,
+ SwitchProfileRequest,
)
from openhands.app_server.app_conversation.app_conversation_service import (
AppConversationService,
@@ -71,12 +74,16 @@ from openhands.app_server.services.httpx_client_injector import (
set_httpx_client_keep_open,
)
from openhands.app_server.services.injector import InjectorState
+from openhands.app_server.settings.settings_models import Settings
+from openhands.app_server.settings.settings_router import LITE_LLM_API_URL
from openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTR
from openhands.app_server.user.user_context import UserContext
+from openhands.app_server.user_auth import get_user_settings
from openhands.app_server.utils.dependencies import get_dependencies
from openhands.app_server.utils.docker_utils import (
replace_localhost_hostname_for_docker,
)
+from openhands.app_server.utils.llm import resolve_llm_base_url
from openhands.sdk.skills import KeywordTrigger, TaskTrigger
from openhands.sdk.workspace.remote.async_remote_workspace import AsyncRemoteWorkspace
@@ -579,6 +586,173 @@ async def send_message_to_conversation(
)
+ '/{conversation_id}/switch_profile',
+ responses={
+ 404: {'description': 'Conversation, sandbox, or profile not found'},
+ 409: {'description': 'Sandbox is not running'},
+ 502: {'description': 'Agent server returned an error'},
+ },
+)
+async def switch_conversation_profile(
+ conversation_id: UUID,
+ request: SwitchProfileRequest,
+ user_settings: Settings | None = Depends(get_user_settings),
+ app_conversation_service: AppConversationService = (
+ app_conversation_service_dependency
+ ),
+ app_conversation_info_service: AppConversationInfoService = (
+ app_conversation_info_service_dependency
+ ),
+ sandbox_service: SandboxService = sandbox_service_dependency,
+ sandbox_spec_service: SandboxSpecService = sandbox_spec_service_dependency,
+ httpx_client: httpx.AsyncClient = httpx_client_dependency,
+) -> Success:
+ """Switch the running conversation's LLM to a saved profile.
+
+ Profiles live in the app-server's user settings, not on the sandbox FS,
+ so we resolve the profile here and hand the LLM directly to the
+ agent-server's ``switch_llm`` endpoint.
+ """
+ if user_settings is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='Settings not found',
+ )
+
+ profile_llm = user_settings.llm_profiles.get(request.profile_name)
+ if profile_llm is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Profile '{request.profile_name}' not found",
+ )
+
+ # Mirror the activate_profile fixup so a profile with an empty base_url
+ # picks up the provider default (e.g. the OpenHands LiteLLM proxy).
+ profile_llm = profile_llm.model_copy(
+ update={
+ 'base_url': resolve_llm_base_url(
+ model=profile_llm.model,
+ base_url=profile_llm.base_url,
+ managed_proxy_url=LITE_LLM_API_URL,
+ ),
+ }
+ )
+
+ # The agent-server's LLM registry is first-write-wins by ``usage_id``:
+ # ``switch_llm`` returns the cached entry under that key and silently
+ # drops the incoming LLM. So:
+ # - Two saved profiles that share the default ``usage_id="default"``
+ # would no-op after the first switch (the second profile is dropped
+ # and the agent keeps using the first).
+ # - Editing a profile (e.g. swapping its model) wouldn't take effect
+ # on subsequent switches because the registry still holds the
+ # pre-edit LLM under the old slot.
+ # Both manifest as "I switched profiles but the request still goes out
+ # with the old model" (often surfacing as upstream "Invalid model name"
+ # errors when the cached model has been removed from the user's quota).
+ #
+ # Derive ``usage_id`` from the profile name + a hash of the resolved
+ # LLM payload. Identical snapshots dedupe in the registry; any change
+ # (model, base_url, api_key, etc.) produces a fresh slot so the swap
+ # actually lands.
+ fingerprint = profile_llm.model_dump(
+ mode='json',
+ exclude={'usage_id'},
+ exclude_none=True,
+ context={'expose_secrets': True},
+ )
+ content_hash = hashlib.sha1(
+ json.dumps(fingerprint, sort_keys=True, default=str).encode('utf-8'),
+ ).hexdigest()[:12]
+ profile_llm = profile_llm.model_copy(
+ update={'usage_id': f'profile:{request.profile_name}:{content_hash}'},
+ )
+
+ ctx = await _get_agent_server_context(
+ conversation_id,
+ app_conversation_service,
+ sandbox_service,
+ sandbox_spec_service,
+ )
+ if isinstance(ctx, JSONResponse):
+ # Helper already framed a 404 response; mirror its status code.
+ raise HTTPException(
+ status_code=ctx.status_code,
+ detail=f'Conversation {conversation_id} is not reachable',
+ )
+ if ctx is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail='Sandbox is paused; resume it before switching profiles.',
+ )
+
+ llm_payload = profile_llm.model_dump(
+ mode='json',
+ exclude_none=True,
+ context={'expose_secrets': True},
+ )
+ headers = {'X-Session-API-Key': ctx.session_api_key} if ctx.session_api_key else {}
+
+ try:
+ switch_response = await httpx_client.post(
+ f'{ctx.agent_server_url}/api/conversations/{conversation_id}/switch_llm',
+ json={'llm': llm_payload},
+ headers=headers,
+ timeout=30.0,
+ )
+ switch_response.raise_for_status()
+ # Surface a success line so operators can confirm the swap landed
+ # without grepping for the absence of an error. ``usage_id`` is the
+ # registry key — different value across calls means the cache was
+ # busted and a fresh LLM is in use; identical value means a cache
+ # hit (intended for unchanged profiles).
+ logger.info(
+ 'Switched conversation %s to profile %r '
+ '(model=%s, base_url=%s, usage_id=%s)',
+ conversation_id,
+ request.profile_name,
+ profile_llm.model,
+ profile_llm.base_url,
+ profile_llm.usage_id,
+ )
+ except httpx.HTTPStatusError as e:
+ logger.error(
+ 'Agent server returned error during switch_llm: '
+ f'{e.response.status_code} - {e.response.text}'
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f'Agent server error: {e.response.status_code}',
+ )
+ except httpx.RequestError as e:
+ logger.error(f'Failed to reach agent server during switch_llm: {e}')
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail='Failed to reach agent server.',
+ )
+
+ # Persist the new model on the conversation record so the chat header
+ # (and other callers that read ``conversation.llm_model``) reflect the
+ # swap on the next fetch. Best-effort: a save failure is logged but
+ # does not undo the switch the agent-server already accepted.
+ try:
+ info = await app_conversation_info_service.get_app_conversation_info(
+ conversation_id,
+ )
+ if info is not None and info.llm_model != profile_llm.model:
+ info.llm_model = profile_llm.model
+ await app_conversation_info_service.save_app_conversation_info(info)
+ except Exception:
+ logger.exception(
+ 'Failed to persist new llm_model on conversation %s after profile '
+ 'switch — header may be stale until the next refresh.',
+ conversation_id,
+ )
+
+ return Success()
+
+
async def _finalize_sandbox_delete(
sandbox_service: SandboxService,
app_conversation_info_service: AppConversationInfoService,
diff --git a/tests/unit/app_server/test_app_conversation_router.py b/tests/unit/app_server/test_app_conversation_router.py
index c655d4b422..29cc5a6e54 100644
--- a/tests/unit/app_server/test_app_conversation_router.py
+++ b/tests/unit/app_server/test_app_conversation_router.py
@@ -4,22 +4,31 @@ This module tests the batch_get_app_conversations endpoint,
focusing on UUID string parsing, validation, and error handling.
"""
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
+import httpx
import pytest
from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
from openhands.app_server.app_conversation.app_conversation_models import (
AppConversation,
+ AppConversationInfo,
AppConversationPage,
+ SwitchProfileRequest,
)
from openhands.app_server.app_conversation.app_conversation_router import (
+ AgentServerContext,
batch_get_app_conversations,
count_app_conversations,
search_app_conversations,
+ switch_conversation_profile,
)
from openhands.app_server.sandbox.sandbox_models import SandboxStatus
+from openhands.app_server.settings.llm_profiles import LLMProfiles
+from openhands.app_server.settings.settings_models import Settings
+from openhands.sdk.llm import LLM
def _make_mock_app_conversation(
@@ -374,3 +383,328 @@ class TestCountAppConversations:
assert call_kwargs.get('sandbox_id__eq') == sandbox_id
assert call_kwargs.get('title__contains') == 'test'
assert result == 3
+
+
+# ─── switch_conversation_profile ────────────────────────────────────────────
+
+
+def _make_settings_with_profile(
+ profile_name: str = 'gpt-5',
+ model: str = 'openai/gpt-5',
+ api_key: str = 'sk-test',
+) -> Settings:
+ """Build a Settings instance carrying one named LLM profile."""
+ llm = LLM(model=model, api_key=api_key)
+ return Settings(llm_profiles=LLMProfiles(profiles={profile_name: llm}))
+
+
+def _make_agent_server_context(
+ conversation_id, llm_model: str | None = 'openai/old-model'
+) -> AgentServerContext:
+ """Build a minimal AgentServerContext for the success path tests."""
+ info = AppConversationInfo(
+ id=conversation_id,
+ created_by_user_id='test-user',
+ sandbox_id=str(uuid4()),
+ llm_model=llm_model,
+ )
+ return AgentServerContext(
+ conversation=info,
+ sandbox=MagicMock(status=SandboxStatus.RUNNING),
+ sandbox_spec=MagicMock(),
+ agent_server_url='http://agent.test',
+ session_api_key='sess-key',
+ )
+
+
+def _make_httpx_client(post_return=None, post_side_effect=None) -> AsyncMock:
+ client = AsyncMock(spec=httpx.AsyncClient)
+ if post_side_effect is not None:
+ client.post = AsyncMock(side_effect=post_side_effect)
+ else:
+ response = post_return or MagicMock()
+ client.post = AsyncMock(return_value=response)
+ return client
+
+
+class TestSwitchConversationProfile:
+ """Test suite for the /switch_profile endpoint."""
+
+ async def test_returns_404_when_user_settings_missing(self):
+ """No user_settings → 404 (precondition for profile lookup)."""
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=uuid4(),
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=None,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+ assert 'Settings not found' in exc_info.value.detail
+
+ async def test_returns_404_when_profile_not_found(self):
+ """Unknown profile name → 404 with the offending name in detail."""
+ settings = _make_settings_with_profile(profile_name='default')
+
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=uuid4(),
+ request=SwitchProfileRequest(profile_name='ghost'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+ assert "'ghost'" in exc_info.value.detail
+
+ async def test_returns_409_when_sandbox_paused(self):
+ """_get_agent_server_context returns None for paused sandboxes → 409."""
+ settings = _make_settings_with_profile()
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=None),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=uuid4(),
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_409_CONFLICT
+ assert 'paused' in exc_info.value.detail.lower()
+
+ async def test_propagates_status_when_conversation_not_reachable(self):
+ """A JSONResponse from the helper is mirrored as an HTTPException."""
+ settings = _make_settings_with_profile()
+ helper_response = JSONResponse(
+ status_code=status.HTTP_404_NOT_FOUND,
+ content={'error': 'Conversation not found'},
+ )
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=helper_response),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=uuid4(),
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=_make_httpx_client(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+
+ async def test_returns_502_when_agent_server_returns_http_error(self):
+ """A 4xx/5xx from switch_llm is folded into a 502."""
+ conv_id = uuid4()
+ settings = _make_settings_with_profile()
+ ctx = _make_agent_server_context(conv_id)
+ bad_response = MagicMock()
+ bad_response.status_code = 500
+ bad_response.text = 'agent crashed'
+ bad_response.raise_for_status = MagicMock(
+ side_effect=httpx.HTTPStatusError(
+ 'boom', request=MagicMock(), response=bad_response
+ ),
+ )
+ client = _make_httpx_client(post_return=bad_response)
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=conv_id,
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert '500' in exc_info.value.detail
+
+ async def test_returns_502_when_agent_server_unreachable(self):
+ """A network-level RequestError is folded into a 502."""
+ conv_id = uuid4()
+ settings = _make_settings_with_profile()
+ ctx = _make_agent_server_context(conv_id)
+ client = _make_httpx_client(
+ post_side_effect=httpx.RequestError('connection refused'),
+ )
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await switch_conversation_profile(
+ conversation_id=conv_id,
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=MagicMock(),
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert 'reach agent server' in exc_info.value.detail.lower()
+
+ async def test_success_persists_new_llm_model_on_conversation(self):
+ """Happy path: agent-server returns 200, llm_model is saved."""
+ conv_id = uuid4()
+ new_model = 'openai/gpt-5'
+ settings = _make_settings_with_profile(model=new_model)
+ ctx = _make_agent_server_context(conv_id, llm_model='openai/old-model')
+
+ ok_response = MagicMock()
+ ok_response.status_code = 200
+ ok_response.raise_for_status = MagicMock()
+ client = _make_httpx_client(post_return=ok_response)
+
+ info_for_persist = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id='test-user',
+ sandbox_id=str(uuid4()),
+ llm_model='openai/old-model',
+ )
+ info_service = MagicMock()
+ info_service.get_app_conversation_info = AsyncMock(
+ return_value=info_for_persist,
+ )
+ info_service.save_app_conversation_info = AsyncMock()
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ await switch_conversation_profile(
+ conversation_id=conv_id,
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=info_service,
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ info_service.save_app_conversation_info.assert_awaited_once()
+ saved_info = info_service.save_app_conversation_info.await_args[0][0]
+ assert saved_info.llm_model == new_model
+
+ # The agent-server payload carries the new profile's LLM under the
+ # `llm` key, with a usage_id derived from the profile name.
+ client.post.assert_awaited_once()
+ post_kwargs = client.post.await_args.kwargs
+ assert post_kwargs['json']['llm']['model'] == new_model
+ assert post_kwargs['json']['llm']['usage_id'].startswith('profile:gpt-5:')
+
+ async def test_success_skips_persist_when_model_unchanged(self):
+ """If the conversation already records the new model, save is skipped."""
+ conv_id = uuid4()
+ same_model = 'openai/gpt-5'
+ settings = _make_settings_with_profile(model=same_model)
+ ctx = _make_agent_server_context(conv_id)
+
+ ok_response = MagicMock()
+ ok_response.status_code = 200
+ ok_response.raise_for_status = MagicMock()
+ client = _make_httpx_client(post_return=ok_response)
+
+ info_already_correct = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id='test-user',
+ sandbox_id=str(uuid4()),
+ llm_model=same_model,
+ )
+ info_service = MagicMock()
+ info_service.get_app_conversation_info = AsyncMock(
+ return_value=info_already_correct,
+ )
+ info_service.save_app_conversation_info = AsyncMock()
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ await switch_conversation_profile(
+ conversation_id=conv_id,
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=info_service,
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )
+
+ info_service.save_app_conversation_info.assert_not_awaited()
+
+ async def test_success_swallows_persistence_failures(self):
+ """A save failure is logged but does not fail the request."""
+ conv_id = uuid4()
+ settings = _make_settings_with_profile(model='openai/gpt-5')
+ ctx = _make_agent_server_context(conv_id, llm_model='openai/old-model')
+
+ ok_response = MagicMock()
+ ok_response.status_code = 200
+ ok_response.raise_for_status = MagicMock()
+ client = _make_httpx_client(post_return=ok_response)
+
+ info_service = MagicMock()
+ info_service.get_app_conversation_info = AsyncMock(
+ side_effect=RuntimeError('db down'),
+ )
+ info_service.save_app_conversation_info = AsyncMock()
+
+ with patch(
+ 'openhands.app_server.app_conversation.app_conversation_router.'
+ '_get_agent_server_context',
+ new=AsyncMock(return_value=ctx),
+ ):
+ # Must not raise — the agent-server already accepted the swap.
+ await switch_conversation_profile(
+ conversation_id=conv_id,
+ request=SwitchProfileRequest(profile_name='gpt-5'),
+ user_settings=settings,
+ app_conversation_service=MagicMock(),
+ app_conversation_info_service=info_service,
+ sandbox_service=MagicMock(),
+ sandbox_spec_service=MagicMock(),
+ httpx_client=client,
+ )