🙌 OpenHands: AI-Driven Development
feat(frontend/chat): add inline LLM profile switcher button (#14301)
Vasco Schiavo3ec19e0887ff
diff --git a/frontend/__tests__/components/features/chat/switch-profile-button.test.tsx b/frontend/__tests__/components/features/chat/switch-profile-button.test.tsxnew file mode 100644index 0000000000..0f62d6a434--- /dev/null+++ b/frontend/__tests__/components/features/chat/switch-profile-button.test.tsx@@ -0,0 +1,164 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MemoryRouter } from "react-router";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import React from "react";+import { SwitchProfileButton } from "#/components/features/chat/switch-profile-button";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";++// `useTranslation` and `useParams` are mocked globally in vitest.setup.ts.+// We mock the data hooks here to drive the component's branches directly.++const mockUseLlmProfiles = vi.hoisted(() => vi.fn());+const mockUseActiveConversation = vi.hoisted(() => vi.fn());+const mockSwitchAndLog = vi.hoisted(() => vi.fn());++vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => mockUseLlmProfiles(),+ LLM_PROFILES_QUERY_KEY: "llm-profiles",+}));++vi.mock("#/hooks/query/use-active-conversation", () => ({+ useActiveConversation: () => mockUseActiveConversation(),+}));++vi.mock("#/hooks/mutation/use-switch-llm-profile-and-log", () => ({+ useSwitchLlmProfileAndLog: () => ({+ switchAndLog: mockSwitchAndLog,+ isPending: false,+ }),+}));++vi.mock("#/hooks/use-conversation-id", () => ({+ useConversationId: () => ({ conversationId: "conv-1" }),+}));++const PROFILES: LlmProfileSummary[] = [+ {+ name: "default",+ model: "anthropic/claude-sonnet-4-6",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "gpt-5",+ model: "openai/gpt-5",+ base_url: null,+ api_key_set: true,+ },+];++const renderButton = () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <MemoryRouter>+ <QueryClientProvider client={queryClient}>+ <SwitchProfileButton />+ </QueryClientProvider>+ </MemoryRouter>,+ );+};++const setupHooks = (+ options: {+ profiles?: LlmProfileSummary[];+ activeProfile?: string | null;+ conversationModel?: string | null;+ } = {},+) => {+ mockUseLlmProfiles.mockReturnValue({+ data: {+ profiles: options.profiles ?? PROFILES,+ active_profile: options.activeProfile ?? null,+ },+ });+ mockUseActiveConversation.mockReturnValue({+ data: { llm_model: options.conversationModel ?? null },+ });+};++describe("SwitchProfileButton", () => {+ beforeEach(() => {+ mockSwitchAndLog.mockReset();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("renders nothing when there are no profiles", () => {+ setupHooks({ profiles: [] });+ renderButton();+ expect(screen.queryByTestId("switch-profile-button")).toBeNull();+ });++ it("shows the matching profile name when conversation.llm_model maps to a profile", () => {+ setupHooks({ conversationModel: "openai/gpt-5" });+ renderButton();+ expect(screen.getByTestId("switch-profile-button")).toHaveTextContent(+ "gpt-5",+ );+ });++ it("falls back to the placeholder when llm_model is set but no profile matches", () => {+ setupHooks({+ conversationModel: "deleted/orphan-model",+ activeProfile: "default",+ });+ renderButton();+ // Should NOT show the user-level default ("default") here — that would+ // misrepresent the running model. Placeholder key is rendered instead.+ const button = screen.getByTestId("switch-profile-button");+ expect(button).toHaveTextContent("LLM$SELECT_MODEL_PLACEHOLDER");+ expect(button).not.toHaveTextContent("default");+ });++ it("uses the user-level active_profile when the conversation has no llm_model yet", () => {+ setupHooks({ conversationModel: null, activeProfile: "default" });+ renderButton();+ expect(screen.getByTestId("switch-profile-button")).toHaveTextContent(+ "default",+ );+ });++ it("toggles the menu open and closed on click", async () => {+ const user = userEvent.setup();+ setupHooks({ conversationModel: "openai/gpt-5" });+ renderButton();+ const button = screen.getByTestId("switch-profile-button");++ expect(button).toHaveAttribute("aria-haspopup", "menu");+ expect(button).toHaveAttribute("aria-expanded", "false");+ expect(screen.queryByTestId("switch-profile-context-menu")).toBeNull();++ await user.click(button);+ expect(button).toHaveAttribute("aria-expanded", "true");+ expect(+ screen.getByTestId("switch-profile-context-menu"),+ ).toBeInTheDocument();++ await user.click(button);+ expect(button).toHaveAttribute("aria-expanded", "false");+ });++ it("calls switchAndLog when a non-active profile is selected", async () => {+ const user = userEvent.setup();+ setupHooks({ conversationModel: "openai/gpt-5" }); // gpt-5 is active+ renderButton();+ await user.click(screen.getByTestId("switch-profile-button"));+ await user.click(screen.getByTestId("switch-profile-option-default"));+ expect(mockSwitchAndLog).toHaveBeenCalledWith("conv-1", "default");+ });++ it("does not call switchAndLog when the already-active profile is selected", async () => {+ const user = userEvent.setup();+ setupHooks({ conversationModel: "openai/gpt-5" }); // gpt-5 is active+ renderButton();+ await user.click(screen.getByTestId("switch-profile-button"));+ await user.click(screen.getByTestId("switch-profile-option-gpt-5"));+ expect(mockSwitchAndLog).not.toHaveBeenCalled();+ });+});diff --git a/frontend/__tests__/components/features/chat/switch-profile-context-menu.test.tsx b/frontend/__tests__/components/features/chat/switch-profile-context-menu.test.tsxnew file mode 100644index 0000000000..a38926a60c--- /dev/null+++ b/frontend/__tests__/components/features/chat/switch-profile-context-menu.test.tsx@@ -0,0 +1,105 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { MemoryRouter } from "react-router";+import { SwitchProfileContextMenu } from "#/components/features/chat/switch-profile-context-menu";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";++// `useTranslation` is mocked globally in vitest.setup.ts to return keys as+// labels, so assertions below check for the raw I18n key strings.++const PROFILES: LlmProfileSummary[] = [+ {+ name: "default",+ model: "anthropic/claude-sonnet-4-6",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "gpt-5",+ model: "openai/gpt-5",+ base_url: null,+ api_key_set: true,+ },+];++const renderMenu = (+ overrides: Partial<+ React.ComponentProps<typeof SwitchProfileContextMenu>+ > = {},+) => {+ const profiles = overrides.profiles ?? PROFILES;+ const activeProfileName =+ overrides.activeProfileName !== undefined+ ? overrides.activeProfileName+ : "default";+ const onSelect = overrides.onSelect ?? vi.fn();+ const onClose = overrides.onClose ?? vi.fn();+ render(+ <MemoryRouter>+ <SwitchProfileContextMenu+ profiles={profiles}+ activeProfileName={activeProfileName}+ onSelect={onSelect}+ onClose={onClose}+ />+ </MemoryRouter>,+ );+ return { profiles, activeProfileName, onSelect, onClose };+};++describe("SwitchProfileContextMenu", () => {+ it("renders the i18n header and one row per profile", () => {+ renderMenu();+ expect(+ screen.getByText("SETTINGS$AVAILABLE_PROFILES"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("switch-profile-option-default"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("switch-profile-option-gpt-5"),+ ).toBeInTheDocument();+ });++ it("marks the active profile with aria-current=true and others without", () => {+ renderMenu({ activeProfileName: "gpt-5" });+ expect(screen.getByTestId("switch-profile-option-gpt-5")).toHaveAttribute(+ "aria-current",+ "true",+ );+ expect(+ screen.getByTestId("switch-profile-option-default"),+ ).not.toHaveAttribute("aria-current");+ });++ it("calls onSelect with the profile name and then onClose when a row is clicked", async () => {+ const user = userEvent.setup();+ const props = renderMenu();+ await user.click(screen.getByTestId("switch-profile-option-gpt-5"));+ expect(props.onSelect).toHaveBeenCalledWith("gpt-5");+ expect(props.onClose).toHaveBeenCalled();+ });++ it("renders the Settings entry as a Link to /settings (cmd-click friendly)", () => {+ renderMenu();+ const settings = screen.getByTestId("switch-profile-open-settings");+ expect(settings.tagName).toBe("A");+ expect(settings).toHaveAttribute("href", "/settings");+ expect(settings).toHaveTextContent("MODEL$OPEN_SETTINGS");+ });++ it("calls onClose when clicking the Settings link", async () => {+ const user = userEvent.setup();+ const props = renderMenu();+ await user.click(screen.getByTestId("switch-profile-open-settings"));+ expect(props.onClose).toHaveBeenCalled();+ });++ it("closes the menu when Escape is pressed", async () => {+ const user = userEvent.setup();+ const props = renderMenu();+ await user.keyboard("{Escape}");+ expect(props.onClose).toHaveBeenCalled();+ });+});diff --git a/frontend/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.ts b/frontend/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.tsnew file mode 100644index 0000000000..217343c00d--- /dev/null+++ b/frontend/__tests__/hooks/mutation/use-switch-llm-profile-and-log.test.ts@@ -0,0 +1,108 @@+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 { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";+import { useEventStore } from "#/stores/use-event-store";+import { useModelStore } from "#/stores/model-store";++const mockSwitchProfile = vi.hoisted(() =>+ vi.fn<(id: string, name: string) => Promise<void>>(),+);+const mockDisplayErrorToast = vi.hoisted(() => vi.fn<(msg: string) => void>());++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: vi.fn(),+}));++const renderTestHook = () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ const wrapper = ({ children }: { children: React.ReactNode }) =>+ React.createElement(QueryClientProvider, { client: queryClient }, children);+ return renderHook(() => useSwitchLlmProfileAndLog(), { wrapper });+};++const CONV = "conv-1";+const entries = () =>+ useModelStore.getState().entriesByConversation[CONV] ?? [];++describe("useSwitchLlmProfileAndLog", () => {+ beforeEach(() => {+ useModelStore.setState({ entriesByConversation: {} });+ useEventStore.setState({ events: [], uiEvents: [] });+ mockSwitchProfile.mockReset();+ mockDisplayErrorToast.mockReset();+ });++ it("calls V1ConversationService.switchProfile with the conversation id and name", async () => {+ mockSwitchProfile.mockResolvedValueOnce(undefined);+ const { result } = renderTestHook();+ act(() => result.current.switchAndLog(CONV, "gpt-5"));+ await waitFor(() =>+ expect(mockSwitchProfile).toHaveBeenCalledWith(CONV, "gpt-5"),+ );+ });++ it("records a switch entry on success, anchored to the latest rendered v1 event", async () => {+ useEventStore.setState({+ events: [],+ uiEvents: [+ {+ id: "evt-7",+ timestamp: "2026-05-01T10:00:00Z",+ source: "user",+ llm_message: { role: "user", content: "hi" },+ } as never,+ ],+ });+ mockSwitchProfile.mockResolvedValueOnce(undefined);+ const { result } = renderTestHook();+ act(() => result.current.switchAndLog(CONV, "gpt-5"));+ await waitFor(() => expect(entries()).toHaveLength(1));+ expect(entries()[0]).toMatchObject({+ anchorEventId: "evt-7",+ profiles: [],+ switchedTo: "gpt-5",+ });+ });++ it("anchors to null when there are no rendered events yet", async () => {+ mockSwitchProfile.mockResolvedValueOnce(undefined);+ const { result } = renderTestHook();+ act(() => result.current.switchAndLog(CONV, "gpt-5"));+ await waitFor(() => expect(entries()).toHaveLength(1));+ expect(entries()[0].anchorEventId).toBeNull();+ });++ it("does not record an entry when switchProfile rejects, and surfaces backend detail", async () => {+ mockSwitchProfile.mockRejectedValueOnce({+ response: { data: { detail: "Profile 'ghost' not found" } },+ });+ const { result } = renderTestHook();+ act(() => result.current.switchAndLog(CONV, "ghost"));+ await waitFor(() =>+ expect(mockDisplayErrorToast).toHaveBeenCalledWith(+ "Profile 'ghost' not found",+ ),+ );+ expect(entries()).toEqual([]);+ });++ it("falls back to the i18n switch-failed key when no error detail is present", async () => {+ mockSwitchProfile.mockRejectedValueOnce({});+ const { result } = renderTestHook();+ act(() => result.current.switchAndLog(CONV, "gpt-5"));+ await waitFor(() =>+ expect(mockDisplayErrorToast).toHaveBeenCalledWith("MODEL$SWITCH_FAILED"),+ );+ });+});diff --git a/frontend/src/components/features/chat/components/chat-input-actions.tsx b/frontend/src/components/features/chat/components/chat-input-actions.tsxindex b674f735cf..dd1785ae8f 100644--- a/frontend/src/components/features/chat/components/chat-input-actions.tsx+++ b/frontend/src/components/features/chat/components/chat-input-actions.tsx@@ -5,6 +5,7 @@ import { useConversationId } from "#/hooks/use-conversation-id";import { useV1PauseConversation } from "#/hooks/mutation/use-v1-pause-conversation";import { useV1ResumeConversation } from "#/hooks/mutation/use-v1-resume-conversation";import { ChangeAgentButton } from "../change-agent-button";+import { SwitchProfileButton } from "../switch-profile-button";interface ChatInputActionsProps {disabled: boolean;@@ -36,6 +37,7 @@ export function ChatInputActions({ disabled }: ChatInputActionsProps) {<div className="flex items-center gap-4"><Tools /><ChangeAgentButton />+ <SwitchProfileButton /></div></div><AgentStatusdiff --git a/frontend/src/components/features/chat/switch-profile-button.tsx b/frontend/src/components/features/chat/switch-profile-button.tsxnew file mode 100644index 0000000000..940dca5034--- /dev/null+++ b/frontend/src/components/features/chat/switch-profile-button.tsx@@ -0,0 +1,83 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { Typography } from "#/ui/typography";+import { I18nKey } from "#/i18n/declaration";+import ChevronDownSmallIcon from "#/icons/chevron-down-small.svg?react";+import CircuitIcon from "#/icons/u-circuit.svg?react";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";+import { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";+import { useActiveConversation } from "#/hooks/query/use-active-conversation";+import { useConversationId } from "#/hooks/use-conversation-id";+import { SwitchProfileContextMenu } from "./switch-profile-context-menu";++export function SwitchProfileButton() {+ const { t } = useTranslation();+ const [contextMenuOpen, setContextMenuOpen] = React.useState(false);+ const { conversationId } = useConversationId();+ const { data } = useLlmProfiles();+ const { data: conversation } = useActiveConversation();+ const { switchAndLog, isPending } = useSwitchLlmProfileAndLog();++ const profiles = data?.profiles ?? [];+ const conversationModel = conversation?.llm_model ?? null;++ // Match the running model first; only fall back to the user-level default+ // when the conversation has no model yet — otherwise we'd misrepresent the+ // running model after a per-conversation /model switch.+ const activeProfileName = conversationModel+ ? (profiles.find((p) => p.model === conversationModel)?.name ?? null)+ : (data?.active_profile ?? null);++ if (profiles.length === 0) {+ return null;+ }++ const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {+ event.preventDefault();+ event.stopPropagation();+ setContextMenuOpen((open) => !open);+ };++ const handleSelect = (profileName: string) => {+ if (profileName === activeProfileName) return;+ switchAndLog(conversationId, profileName);+ };++ return (+ <div className="relative">+ <button+ type="button"+ onClick={handleClick}+ disabled={isPending}+ data-testid="switch-profile-button"+ aria-haspopup="menu"+ aria-expanded={contextMenuOpen}+ className="flex items-center gap-1 border border-[#4B505F] rounded-[100px] transition-opacity cursor-pointer hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed pl-2 max-w-[200px]"+ >+ <CircuitIcon+ width={16}+ height={16}+ color="#ffffff"+ className="shrink-0"+ />+ <Typography.Text className="text-white text-2.75 not-italic font-normal leading-5 truncate">+ {activeProfileName ?? t(I18nKey.LLM$SELECT_MODEL_PLACEHOLDER)}+ </Typography.Text>+ <ChevronDownSmallIcon+ width={24}+ height={24}+ color="#ffffff"+ className="shrink-0"+ />+ </button>+ {contextMenuOpen && (+ <SwitchProfileContextMenu+ profiles={profiles}+ activeProfileName={activeProfileName}+ onSelect={handleSelect}+ onClose={() => setContextMenuOpen(false)}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/components/features/chat/switch-profile-context-menu.tsx b/frontend/src/components/features/chat/switch-profile-context-menu.tsxnew file mode 100644index 0000000000..e5b5d2fadf--- /dev/null+++ b/frontend/src/components/features/chat/switch-profile-context-menu.tsx@@ -0,0 +1,106 @@+import React from "react";+import { Link } from "react-router";+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import { ContextMenu } from "#/ui/context-menu";+import { ContextMenuListItem } from "../context-menu/context-menu-list-item";+import { Divider } from "#/ui/divider";+import { SettingsNavHeader } from "../settings/settings-nav-header";+import { ToolsContextMenuIconText } from "../controls/tools-context-menu-icon-text";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import CircuitIcon from "#/icons/u-circuit.svg?react";+import SettingsIcon from "#/icons/settings.svg?react";+import CheckIcon from "#/icons/checkmark.svg?react";+import { cn } from "#/utils/utils";+import { CONTEXT_MENU_ICON_TEXT_CLASSNAME } from "#/utils/constants";+import type { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";++const itemClassName = cn(+ "cursor-pointer p-0 h-auto hover:bg-transparent",+ CONTEXT_MENU_ICON_TEXT_CLASSNAME,+);++interface SwitchProfileContextMenuProps {+ profiles: LlmProfileSummary[];+ activeProfileName: string | null;+ onSelect: (profileName: string) => void;+ onClose: () => void;+}++export function SwitchProfileContextMenu({+ profiles,+ activeProfileName,+ onSelect,+ onClose,+}: SwitchProfileContextMenuProps) {+ const { t } = useTranslation();+ const ref = useClickOutsideElement<HTMLUListElement>(onClose);++ React.useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [onClose]);++ const handleSelect = (+ event: React.MouseEvent<HTMLButtonElement>,+ name: string,+ ) => {+ event.preventDefault();+ event.stopPropagation();+ onSelect(name);+ onClose();+ };++ return (+ <ContextMenu+ ref={ref}+ testId="switch-profile-context-menu"+ position="top"+ alignment="left"+ className="left-0 mb-2 bottom-full min-w-[220px] max-h-[60vh] overflow-y-auto"+ >+ <SettingsNavHeader+ text={I18nKey.SETTINGS$AVAILABLE_PROFILES}+ className="px-2 pt-1 pb-1"+ />+ {profiles.map((profile) => {+ const isActive = profile.name === activeProfileName;+ return (+ <ContextMenuListItem+ key={profile.name}+ testId={`switch-profile-option-${profile.name}`}+ onClick={(event) => handleSelect(event, profile.name)}+ className={itemClassName}+ ariaCurrent={isActive ? "true" : undefined}+ >+ <ToolsContextMenuIconText+ icon={<CircuitIcon width={16} height={16} />}+ text={profile.name}+ rightIcon={+ isActive ? <CheckIcon width={14} height={14} /> : undefined+ }+ className={cn(+ CONTEXT_MENU_ICON_TEXT_CLASSNAME,+ isActive && "bg-[#5C5D62]",+ )}+ />+ </ContextMenuListItem>+ );+ })}+ <Divider />+ <Link+ to="/settings"+ onClick={onClose}+ data-testid="switch-profile-open-settings"+ className={cn("block", itemClassName)}+ >+ <ToolsContextMenuIconText+ icon={<SettingsIcon width={16} height={16} />}+ text={t(I18nKey.MODEL$OPEN_SETTINGS)}+ className={CONTEXT_MENU_ICON_TEXT_CLASSNAME}+ />+ </Link>+ </ContextMenu>+ );+}diff --git a/frontend/src/components/features/context-menu/context-menu-list-item.tsx b/frontend/src/components/features/context-menu/context-menu-list-item.tsxindex 8c9d9006a6..5f92e26ad3 100644--- a/frontend/src/components/features/context-menu/context-menu-list-item.tsx+++ b/frontend/src/components/features/context-menu/context-menu-list-item.tsx@@ -5,6 +5,7 @@ interface ContextMenuListItemProps {onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;isDisabled?: boolean;className?: string;+ ariaCurrent?: React.AriaAttributes["aria-current"];}export function ContextMenuListItem({@@ -13,6 +14,7 @@ export function ContextMenuListItem({onClick,isDisabled,className,+ ariaCurrent,}: React.PropsWithChildren<ContextMenuListItemProps>) {return (<button@@ -20,6 +22,7 @@ export function ContextMenuListItem({type="button"onClick={onClick}disabled={isDisabled}+ aria-current={ariaCurrent}className={cn("text-sm px-4 h-10 w-full text-start hover:bg-white/10 cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent text-nowrap",diff --git a/frontend/src/hooks/chat/use-model-interceptor.ts b/frontend/src/hooks/chat/use-model-interceptor.tsindex d69f6000cb..701c9ea4aa 100644--- a/frontend/src/hooks/chat/use-model-interceptor.ts+++ b/frontend/src/hooks/chat/use-model-interceptor.ts@@ -3,7 +3,7 @@ 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 { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";import { LLM_PROFILES_QUERY_KEY } from "#/hooks/query/use-llm-profiles";import { I18nKey } from "#/i18n/declaration";import { useEventStore } from "#/stores/use-event-store";@@ -24,9 +24,8 @@ export const useModelInterceptor = (onSubmit: (message: string) => void,) => {const showProfiles = useModelStore((s) => s.show);- const recordSwitch = useModelStore((s) => s.recordSwitch);const queryClient = useQueryClient();- const { mutate: switchLlmProfile } = useSwitchLlmProfile();+ const { switchAndLog } = useSwitchLlmProfileAndLog();const { t } = useTranslation();return useCallback(@@ -41,65 +40,35 @@ export const useModelInterceptor = (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)),- );+ if (arg) {+ switchAndLog(conversationId, arg);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 }),- );- },- },+ // Skip events filtered out by shouldRenderEvent (e.g.+ // ConversationStateUpdate) so the entry mounts where the user typed.+ const last = getRenderedV1Events(useEventStore.getState().uiEvents).at(+ -1,);+ const anchorEventId = last ? String(last.id) : null;++ // 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)),+ );},- [- conversationId,- onSubmit,- showProfiles,- recordSwitch,- queryClient,- switchLlmProfile,- t,- ],+ [conversationId, onSubmit, showProfiles, queryClient, switchAndLog, t],);};diff --git a/frontend/src/hooks/mutation/use-switch-llm-profile-and-log.ts b/frontend/src/hooks/mutation/use-switch-llm-profile-and-log.tsnew file mode 100644index 0000000000..3f70068641--- /dev/null+++ b/frontend/src/hooks/mutation/use-switch-llm-profile-and-log.ts@@ -0,0 +1,44 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";+import { useModelStore } from "#/stores/model-store";+import { useEventStore } from "#/stores/use-event-store";+import { getRenderedV1Events } from "#/components/v1/chat";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { extractErrorMessage } from "#/utils/extract-error-message";+import { I18nKey } from "#/i18n/declaration";++/** Switch the conversation's LLM profile and render the result inline (same UX as `/model <name>`). */+export function useSwitchLlmProfileAndLog() {+ const { mutate, isPending } = useSwitchLlmProfile();+ const recordSwitch = useModelStore((s) => s.recordSwitch);+ const { t } = useTranslation();++ // Stable identity so the /model interceptor's outer useCallback doesn't bust each render.+ const switchAndLog = useCallback(+ (conversationId: string, profileName: string) => {+ const last = getRenderedV1Events(useEventStore.getState().uiEvents).at(+ -1,+ );+ const anchorEventId = last ? String(last.id) : null;++ mutate(+ { conversationId, profileName },+ {+ onSuccess: () =>+ recordSwitch(conversationId, anchorEventId, profileName),+ onError: (err) =>+ displayErrorToast(+ extractErrorMessage(+ err,+ t(I18nKey.MODEL$SWITCH_FAILED, { name: profileName }),+ ),+ ),+ },+ );+ },+ [mutate, recordSwitch, t],+ );++ return { switchAndLog, isPending };+}diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex c86c40992b..3e01fabfff 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -942,6 +942,7 @@ export enum I18nKey {MODEL$SWITCHED_TO_PROFILE = "MODEL$SWITCHED_TO_PROFILE",MODEL$LIST_FAILED = "MODEL$LIST_FAILED",MODEL$SWITCH_FAILED = "MODEL$SWITCH_FAILED",+ MODEL$OPEN_SETTINGS = "MODEL$OPEN_SETTINGS",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.jsonindex cc90ef79a1..92f95ca9fd 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -16013,6 +16013,23 @@"uk": "Не вдалося перемкнутися на профіль '{{name}}'","ca": "No s'ha pogut canviar al perfil '{{name}}'"},+ "MODEL$OPEN_SETTINGS": {+ "en": "Model Settings",+ "ja": "モデル設定",+ "zh-CN": "模型设置",+ "zh-TW": "模型設定",+ "ko-KR": "모델 설정",+ "no": "Modellinnstillinger",+ "it": "Impostazioni modello",+ "pt": "Configurações do modelo",+ "es": "Configuración del modelo",+ "ar": "إعدادات النموذج",+ "fr": "Paramètres du modèle",+ "tr": "Model ayarları",+ "de": "Modelleinstellungen",+ "uk": "Налаштування моделі",+ "ca": "Configuració del model"+ },"SECURITY$SELECT_RISK_SEVERITY": {"en": "Select risk severity","ja": "リスクの重要度を選択",