🙌 OpenHands: AI-Driven Development
feat(chat): add /model slash command for LLM profiles (#418)
Vasco Schiavoed216c38aab7
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex e7852a11ec..82dcc29b70 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -22,6 +22,7 @@ const {mockConversationClient,mockFileClient,mockSettingsClient,+ mockSwitchProfile,mockGetSettings,mockGetSettingsForConversation,} = vi.hoisted(() => ({@@ -31,6 +32,7 @@ const {mockConversationClient: vi.fn(),mockFileClient: vi.fn(),mockSettingsClient: vi.fn(),+ mockSwitchProfile: vi.fn(),mockGetSettings: vi.fn(),mockGetSettingsForConversation: vi.fn(),}));@@ -106,6 +108,7 @@ describe("AgentServerConversationService", () => {getConversation: vi.fn(),sendEvent: vi.fn(),updateConversation: vi.fn(),+ switchProfile: mockSwitchProfile,});mockFileClient.mockReturnValue({downloadTextFile: async (path: string) => {@@ -409,6 +412,50 @@ describe("AgentServerConversationService", () => {});});+ describe("switchProfile", () => {+ beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ });++ afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ });++ it("switches profiles through the local agent-server client", async () => {+ mockSwitchProfile.mockResolvedValue(undefined);++ await AgentServerConversationService.switchProfile("conv-1", "haiku");++ expect(mockSwitchProfile).toHaveBeenCalledWith("conv-1", "haiku");+ expect(ConversationClient).toHaveBeenCalledWith({+ host: "http://localhost:54928",+ apiKey: "test-api-key",+ workingDir: "/workspace/project/agent-canvas",+ });+ });++ it("rejects profile switching on cloud backends before creating a client", async () => {+ const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-token",+ kind: "cloud",+ };+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ await expect(+ AgentServerConversationService.switchProfile("conv-1", "haiku"),+ ).rejects.toThrow(+ "LLM profile switching is only supported for local agent-server backends.",+ );+ expect(mockSwitchProfile).not.toHaveBeenCalled();+ });+ });+describe("cloud branches", () => {const cloudBackend: Backend = {id: "prod",diff --git a/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsxnew file mode 100644index 0000000000..50eb92bb70--- /dev/null+++ b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx@@ -0,0 +1,54 @@+import { screen } from "@testing-library/react";+import { beforeEach, describe, expect, it } from "vitest";+import { renderWithProviders } from "test-utils";+import { Messages } from "#/components/conversation-events/chat/messages";+import { useModelStore } from "#/stores/model-store";+import { ActionEvent, SecurityRisk } from "#/types/agent-server/core";+import { ExecuteBashAction } from "#/types/agent-server/core/base/action";++const CONVERSATION_ID = "test-conversation-id";++const makeBashAction = (id: string): ActionEvent<ExecuteBashAction> => ({+ id,+ timestamp: new Date().toISOString(),+ source: "agent",+ thought: [],+ thinking_blocks: [],+ action: {+ kind: "ExecuteBashAction",+ command: `echo ${id}`,+ is_input: false,+ timeout: null,+ reset: false,+ },+ tool_name: "execute_bash",+ tool_call_id: `call_${id}`,+ tool_call: {+ id: `call_${id}`,+ type: "function",+ function: {+ name: "execute_bash",+ arguments: JSON.stringify({ command: `echo ${id}` }),+ },+ },+ llm_response_id: `response_${id}`,+ security_risk: SecurityRisk.UNKNOWN,+});++describe("Messages model entries", () => {+ beforeEach(() => {+ useModelStore.setState({ entriesByConversation: {} });+ });++ it("renders model entries anchored to non-last events inside grouped runs", () => {+ const first = makeBashAction("action-1");+ const second = makeBashAction("action-2");+ useModelStore.getState().show(CONVERSATION_ID, first.id, []);++ renderWithProviders(+ <Messages messages={[first, second]} allEvents={[first, second]} />,+ );++ expect(screen.getByTestId("model-messages")).toBeInTheDocument();+ });+});diff --git a/__tests__/components/features/chat/model-messages.test.tsx b/__tests__/components/features/chat/model-messages.test.tsxnew file mode 100644index 0000000000..221d8c9bf4--- /dev/null+++ b/__tests__/components/features/chat/model-messages.test.tsx@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, it } from "vitest";+import { screen } from "@testing-library/react";+import i18n from "i18next";+import userEvent from "@testing-library/user-event";+import { renderWithProviders } from "test-utils";+import { ModelMessages } from "#/components/features/chat/model-messages";+import { useModelStore } from "#/stores/model-store";+import type { ProfileInfo } from "#/api/profiles-service/profiles-service.api";++const CONVERSATION_ID = "conv-1";++const profiles: ProfileInfo[] = [+ {+ name: "haiku",+ model: "anthropic/claude-haiku-4-5",+ base_url: "https://llm.example.test",+ api_key_set: true,+ },+ {+ name: "gpt",+ model: "openai/gpt-5.1",+ base_url: null,+ api_key_set: false,+ },+];++describe("ModelMessages", () => {+ beforeEach(() => {+ const resources = {+ MODEL$AVAILABLE_PROFILES: "Available profiles ({{count}})",+ MODEL$NO_SAVED_PROFILES: "No saved profiles",+ MODEL$NO_PROFILES_HINT:+ "Use the LLM settings page to create a profile, then run /model <name> to switch.",+ MODEL$SWITCHED_TO_PROFILE: "ℹ️ Switched to profile <cmd>{{name}}</cmd>",+ };+ i18n.addResourceBundle("en", "translation", resources, true, true);+ i18n.addResourceBundle("en", "openhands", resources, true, true);+ useModelStore.setState({ entriesByConversation: {} });+ });++ it("renders only entries anchored to the requested event", async () => {+ const user = userEvent.setup();+ useModelStore.getState().show(CONVERSATION_ID, "event-1", [profiles[0]]);+ useModelStore.getState().show(CONVERSATION_ID, "event-2", [profiles[1]]);++ renderWithProviders(+ <ModelMessages+ conversationId={CONVERSATION_ID}+ anchorEventId="event-1"+ />,+ );++ expect(screen.getByTestId("model-messages")).toBeInTheDocument();+ expect(screen.getByText("Available profiles (1)")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Expand" }));++ const profileToggle = screen.getByRole("button", {+ name: "Toggle details for haiku",+ });+ expect(profileToggle).toHaveAttribute("aria-expanded", "false");+ expect(+ screen.queryByRole("button", { name: "Toggle details for gpt" }),+ ).not.toBeInTheDocument();++ await user.click(profileToggle);+ expect(profileToggle).toHaveAttribute("aria-expanded", "true");++ expect(+ screen.getByText(/model:\s+anthropic\/claude-haiku-4-5/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/base_url:\s+https:\/\/llm\.example\.test/),+ ).toBeInTheDocument();+ expect(screen.getByText(/api_key:\s+set/)).toBeInTheDocument();+ });++ it("renders empty-profile hints expanded by default", () => {+ useModelStore.getState().show(CONVERSATION_ID, null, []);++ renderWithProviders(+ <ModelMessages conversationId={CONVERSATION_ID} anchorEventId={null} />,+ );++ expect(screen.getByText("No saved profiles")).toBeInTheDocument();+ expect(+ screen.getByText(+ "Use the LLM settings page to create a profile, then run /model <name> to switch.",+ ),+ ).toBeInTheDocument();+ });++ it("renders switch confirmations for the matching anchor", () => {+ useModelStore.getState().recordSwitch(CONVERSATION_ID, "event-1", "haiku");++ renderWithProviders(+ <ModelMessages+ conversationId={CONVERSATION_ID}+ anchorEventId="event-1"+ />,+ );++ expect(screen.getByTestId("model-messages")).toHaveTextContent(+ "ℹ️ Switched to profile haiku",+ );+ });+});diff --git a/__tests__/hooks/chat/model-command-event-anchor.test.ts b/__tests__/hooks/chat/model-command-event-anchor.test.tsnew file mode 100644index 0000000000..c3e2f1d609--- /dev/null+++ b/__tests__/hooks/chat/model-command-event-anchor.test.ts@@ -0,0 +1,32 @@+import { beforeEach, describe, expect, it } from "vitest";+import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-anchor";+import { useEventStore } from "#/stores/use-event-store";+import {+ createOtherActionEvent,+ createPlanningFileEditorActionEvent,+ createUserMessageEvent,+} from "test-utils";++describe("getLastRenderableEventId", () => {+ beforeEach(() => {+ useEventStore.getState().clearEvents();+ });++ it("returns null when no renderable events exist", () => {+ useEventStore+ .getState()+ .addEvent(createPlanningFileEditorActionEvent("plan"));++ expect(getLastRenderableEventId()).toBeNull();+ });++ it("returns the latest renderable UI event id as a string", () => {+ useEventStore.getState().addEvent(createUserMessageEvent("message-1"));+ useEventStore+ .getState()+ .addEvent(createPlanningFileEditorActionEvent("plan"));+ useEventStore.getState().addEvent(createOtherActionEvent("action-1"));++ expect(getLastRenderableEventId()).toBe("action-1");+ });+});diff --git a/__tests__/hooks/chat/use-model-interceptor.test.tsx b/__tests__/hooks/chat/use-model-interceptor.test.tsxnew file mode 100644index 0000000000..b0878ef4ff--- /dev/null+++ b/__tests__/hooks/chat/use-model-interceptor.test.tsx@@ -0,0 +1,185 @@+import React from "react";+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import { useModelInterceptor } from "#/hooks/chat/use-model-interceptor";+import { useEventStore } from "#/stores/use-event-store";+import { useModelStore } from "#/stores/model-store";++const { mockSwitchAndLog, mockDisplayErrorToast } = vi.hoisted(() => ({+ mockSwitchAndLog: vi.fn(),+ mockDisplayErrorToast: vi.fn(),+}));++vi.mock("#/hooks/mutation/use-switch-llm-profile-and-log", () => ({+ useSwitchLlmProfileAndLog: () => mockSwitchAndLog,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock("#/utils/custom-toast-handlers", () => ({+ displayErrorToast: mockDisplayErrorToast,+}));++const CONVERSATION_ID = "conv-1";++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-token",+ kind: "cloud",+};++const createUserMessageEvent = (id: string) => ({+ id,+ timestamp: new Date().toISOString(),+ source: "user" as const,+ llm_message: {+ role: "user" as const,+ content: [{ type: "text" as const, text: "User message" }],+ },+ activated_microagents: [],+ extended_content: [],+});++const makeWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });++ return function Wrapper({ children }: { children: React.ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ );+ };+};++describe("useModelInterceptor", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ window.localStorage.clear();+ vi.spyOn(ProfilesService, "listProfiles").mockResolvedValue({+ profiles: [],+ active_profile: null,+ });+ __resetActiveStoreForTests();+ useEventStore.getState().clearEvents();+ useModelStore.setState({ entriesByConversation: {} });+ });++ it("lists profiles inline for bare /model submissions", async () => {+ vi.mocked(ProfilesService.listProfiles).mockResolvedValueOnce({+ profiles: [+ {+ name: "haiku",+ model: "anthropic/claude-haiku-4-5",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: "haiku",+ });+ useEventStore.getState().addEvent(createUserMessageEvent("message-1"));+ const onSubmit = vi.fn();++ const { result } = renderHook(+ () => useModelInterceptor(CONVERSATION_ID, onSubmit),+ { wrapper: makeWrapper() },+ );++ act(() => result.current(" /model "));++ await waitFor(() => {+ expect(+ useModelStore.getState().entriesByConversation[CONVERSATION_ID],+ ).toEqual([+ expect.objectContaining({+ anchorEventId: "message-1",+ profiles: [expect.objectContaining({ name: "haiku" })],+ }),+ ]);+ });+ expect(onSubmit).not.toHaveBeenCalled();+ expect(mockSwitchAndLog).not.toHaveBeenCalled();+ });++ it("switches profiles for /model <name> submissions", () => {+ const onSubmit = vi.fn();+ const { result } = renderHook(+ () => useModelInterceptor(CONVERSATION_ID, onSubmit),+ { wrapper: makeWrapper() },+ );++ act(() => result.current("/model haiku"));++ expect(mockSwitchAndLog).toHaveBeenCalledWith(CONVERSATION_ID, "haiku");+ expect(onSubmit).not.toHaveBeenCalled();+ expect(ProfilesService.listProfiles).not.toHaveBeenCalled();+ });++ it("falls through for non-model messages", () => {+ const onSubmit = vi.fn();+ const { result } = renderHook(+ () => useModelInterceptor(CONVERSATION_ID, onSubmit),+ { wrapper: makeWrapper() },+ );++ act(() => result.current("hello /model haiku"));++ expect(onSubmit).toHaveBeenCalledWith("hello /model haiku");+ expect(mockSwitchAndLog).not.toHaveBeenCalled();+ });++ it("falls through on cloud backends", () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });+ const onSubmit = vi.fn();++ const { result } = renderHook(+ () => useModelInterceptor(CONVERSATION_ID, onSubmit),+ { wrapper: makeWrapper() },+ );++ act(() => result.current("/model haiku"));++ expect(onSubmit).toHaveBeenCalledWith("/model haiku");+ expect(mockSwitchAndLog).not.toHaveBeenCalled();+ });++ it("shows an error toast when listing profiles fails", async () => {+ vi.mocked(ProfilesService.listProfiles).mockRejectedValue(+ new Error("Network error"),+ );+ const onSubmit = vi.fn();++ const { result } = renderHook(+ () => useModelInterceptor(CONVERSATION_ID, onSubmit),+ { wrapper: makeWrapper() },+ );++ act(() => result.current("/model"));++ await waitFor(() => {+ expect(mockDisplayErrorToast).toHaveBeenCalledWith("Network error");+ });+ expect(onSubmit).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/hooks/chat/use-slash-command.test.ts b/__tests__/hooks/chat/use-slash-command.test.tsindex 51bafbf008..99a69b9e63 100644--- a/__tests__/hooks/chat/use-slash-command.test.ts+++ b/__tests__/hooks/chat/use-slash-command.test.ts@@ -1,5 +1,5 @@import React from "react";-import { renderHook } from "@testing-library/react";+import { act, renderHook } from "@testing-library/react";import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { useSlashCommand } from "#/hooks/chat/use-slash-command";import { ActiveBackendProvider } from "#/contexts/active-backend-context";@@ -19,10 +19,29 @@ const mockConversation = vi.hoisted(() => ({data: undefined as { conversation_version?: "V0" | "V1" } | undefined,}));+const mockLlmProfiles = vi.hoisted(() => ({+ data: undefined as+ | {+ profiles: Array<{+ name: string;+ model: string | null;+ base_url: string | null;+ api_key_set: boolean;+ }>;+ active_profile: string | null;+ }+ | undefined,+ isLoading: false,+}));+vi.mock("#/hooks/query/use-conversation-skills", () => ({useConversationSkills: () => mockSkills,}));+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => mockLlmProfiles,+}));+vi.mock("#/hooks/query/use-active-conversation", () => ({useActiveConversation: () => mockConversation,}));@@ -39,6 +58,22 @@ function makeChatInputRef() {return { current: document.createElement("div") };}+function setInputText(element: HTMLDivElement, text: string) {+ element.textContent = text;+ element.innerText = text;+ document.body.appendChild(element);++ const textNode = element.firstChild;+ if (!textNode) return;++ const range = document.createRange();+ const selection = window.getSelection();+ range.setStart(textNode, text.length);+ range.collapse(true);+ selection?.removeAllRanges();+ selection?.addRange(range);+}+const cloudBackend: Backend = {id: "prod",name: "Production",@@ -52,11 +87,14 @@ describe("useSlashCommand", () => {vi.clearAllMocks();mockSkills.data = undefined;mockSkills.isLoading = false;+ mockLlmProfiles.data = undefined;+ mockLlmProfiles.isLoading = false;mockConversation.data = undefined;});afterEach(() => {- window.localStorage.clear();+ document.body.innerHTML = "";+ window.localStorage.clear?.();__resetActiveStoreForTests();});@@ -93,4 +131,72 @@ describe("useSlashCommand", () => {const commands = result.current.filteredItems.map((i) => i.command);expect(commands).toContain("/new");});++ it("suggests saved LLM profiles after /model on a local backend", () => {+ // The active backend store is reset before each test, which restores the default local backend.++ mockSkills.data = [];+ mockLlmProfiles.data = {+ profiles: [+ {+ name: "haiku",+ model: "anthropic/claude-haiku-4-5",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "gpt",+ model: "openai/gpt-5.1",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: "haiku",+ };++ const ref = makeChatInputRef();+ setInputText(ref.current, "/model");++ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(true);+ expect(result.current.filteredItems.map((i) => i.command)).toEqual([+ "/model haiku",+ "/model gpt",+ ]);+ });++ it("filters saved LLM profile suggestions by profile name or model", () => {+ mockSkills.data = [];+ mockLlmProfiles.data = {+ profiles: [+ {+ name: "haiku",+ model: "anthropic/claude-haiku-4-5",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "gpt",+ model: "openai/gpt-5.1",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: null,+ };++ const ref = makeChatInputRef();+ setInputText(ref.current, "/model claude");++ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.filteredItems.map((i) => i.command)).toEqual([+ "/model haiku",+ ]);+ });});diff --git a/__tests__/stores/model-store.test.ts b/__tests__/stores/model-store.test.tsnew file mode 100644index 0000000000..731c1b3161--- /dev/null+++ b/__tests__/stores/model-store.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it } from "vitest";+import { useModelStore } from "#/stores/model-store";+import type { ProfileInfo } from "#/api/profiles-service/profiles-service.api";++const CONV_A = "conv-a";+const CONV_B = "conv-b";++const entriesFor = (conversationId: string) =>+ useModelStore.getState().entriesByConversation[conversationId] ?? [];++const profile: ProfileInfo = {+ name: "haiku",+ model: "anthropic/claude-haiku-4-5",+ base_url: null,+ api_key_set: true,+};++describe("model store", () => {+ beforeEach(() => {+ useModelStore.setState({ entriesByConversation: {} });+ });++ it("adds profile-list entries scoped to the conversation", () => {+ useModelStore.getState().show(CONV_A, "event-1", [profile]);++ expect(entriesFor(CONV_A)).toEqual([+ expect.objectContaining({+ id: expect.any(String),+ anchorEventId: "event-1",+ profiles: [profile],+ }),+ ]);+ expect(entriesFor(CONV_B)).toEqual([]);+ });++ it("records profile switches without mutating previous list entries", () => {+ useModelStore.getState().show(CONV_A, null, [profile]);+ useModelStore.getState().recordSwitch(CONV_A, "event-2", "gpt");++ expect(entriesFor(CONV_A)).toEqual([+ expect.objectContaining({+ anchorEventId: null,+ profiles: [profile],+ }),+ expect.objectContaining({+ anchorEventId: "event-2",+ profiles: [],+ switchedTo: "gpt",+ }),+ ]);+ });++ it("clears entries for one conversation or all conversations", () => {+ useModelStore.getState().show(CONV_A, "event-1", [profile]);+ useModelStore.getState().recordSwitch(CONV_B, "event-2", "gpt");++ useModelStore.getState().clear(CONV_A);++ expect(entriesFor(CONV_A)).toEqual([]);+ expect(entriesFor(CONV_B)).toHaveLength(1);++ useModelStore.getState().clearAll();++ expect(entriesFor(CONV_B)).toEqual([]);+ });+});diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex ef2c78870a..a1de3cf855 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -566,6 +566,22 @@ class AgentServerConversationService {]);return requireAppConversation(conversation, conversationId);}++ static async switchProfile(+ conversationId: string,+ profileName: string,+ ): Promise<void> {+ if (getActiveBackend().backend.kind === "cloud") {+ throw new Error(+ "LLM profile switching is only supported for local agent-server backends.",+ );+ }++ await new ConversationClient(getAgentServerClientOptions()).switchProfile(+ conversationId,+ profileName,+ );+ }}export default AgentServerConversationService;diff --git a/src/components/conversation-events/chat/messages.tsx b/src/components/conversation-events/chat/messages.tsxindex dfd5dcb465..b18e00e317 100644--- a/src/components/conversation-events/chat/messages.tsx+++ b/src/components/conversation-events/chat/messages.tsx@@ -5,6 +5,9 @@ import { usePlanPreviewEvents } from "./hooks/use-plan-preview-events";import { groupEvents } from "./group-events";import { EventGroup } from "./event-message-components/event-group";import { ThoughtEventMessage } from "./event-message-components/thought-event-message";+import { useModelStore } from "#/stores/model-store";+import { ModelMessages } from "#/components/features/chat/model-messages";+import { useOptionalConversationId } from "#/hooks/use-conversation-id";// TODO: Implement microagent functionality for V1 when APIs support V1 event IDs// import { AgentState } from "#/types/agent-state";// import MemoryIcon from "#/icons/memory_icon.svg?react";@@ -18,10 +21,35 @@ const getLastEventId = (events: OpenHandsEvent[]) => events.at(-1)?.id;export const Messages: React.FC<MessagesProps> = React.memo(({ messages, allEvents }) => {+ const { conversationId } = useOptionalConversationId();// Get the set of event IDs that should render PlanPreview// This ensures only one preview per user message "phase"const planPreviewEventIds = usePlanPreviewEvents(allEvents);+ // Set of event ids that have a /model entry anchored to them — used to+ // avoid mounting <ModelMessages> for every event (the component would+ // otherwise 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]);++ const maybeRenderModelMessages = (eventId: string | number | undefined) => {+ if (!modelAnchorIds || eventId === undefined) return null;+ const key = String(eventId);+ if (!modelAnchorIds.has(key)) return null;+ return (+ <ModelMessages conversationId={conversationId} anchorEventId={key} />+ );+ };+// Fold consecutive action/observation events into collapsible groups so a// long sequence of tool calls doesn't dominate the chat scroll. Items that// can't be grouped (or that fall in a short run) are still rendered one by@@ -53,17 +81,23 @@ export const Messages: React.FC<MessagesProps> = React.memo(<>{renderedItems.map((item, itemIndex) => {if (item.kind === "single") {- // Thoughts for singles are also hoisted as their own "thought"- // item, so suppress the inline render to avoid duplication.- return renderEventMessage(item.event, item.index, true);+ return (+ <React.Fragment key={`single-${item.event.id}`}>+ {/* Thoughts for singles are also hoisted as their own+ "thought" item, so suppress the inline render to avoid+ duplication. */}+ {renderEventMessage(item.event, item.index, true)}+ {maybeRenderModelMessages(item.event.id)}+ </React.Fragment>+ );}if (item.kind === "thought") {return (- <ThoughtEventMessage- key={`thought-${item.action.id}`}- event={item.action}- />+ <React.Fragment key={`thought-${item.action.id}`}>+ <ThoughtEventMessage event={item.action} />+ {maybeRenderModelMessages(item.action.id)}+ </React.Fragment>);}@@ -74,16 +108,22 @@ export const Messages: React.FC<MessagesProps> = React.memo(const isFinalized = itemIndex < renderedItems.length - 1;const groupKey = item.events[0]?.id ?? `group-${item.startIndex}`;return (- <EventGroup- key={groupKey}- events={item.events}- allEvents={allEvents}- isFinalized={isFinalized}- >- {item.events.map((event, offset) =>- renderEventMessage(event, item.startIndex + offset, true),- )}- </EventGroup>+ <React.Fragment key={`group-${groupKey}`}>+ <EventGroup+ events={item.events}+ allEvents={allEvents}+ isFinalized={isFinalized}+ >+ {item.events.map((event, offset) =>+ renderEventMessage(event, item.startIndex + offset, true),+ )}+ </EventGroup>+ {item.events.map((event) => (+ <React.Fragment key={`model-${event.id}`}>+ {maybeRenderModelMessages(event.id)}+ </React.Fragment>+ ))}+ </React.Fragment>);})}</>diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsxindex 97ddbf87e3..8df463602c 100644--- a/src/components/features/chat/chat-interface.tsx+++ b/src/components/features/chat/chat-interface.tsx@@ -4,6 +4,8 @@ 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 { useModelStore } from "#/stores/model-store";import { InteractiveChatBox } from "./interactive-chat-box";import { AgentState } from "#/types/agent-state";import { useFilteredEvents } from "#/hooks/use-filtered-events";@@ -202,6 +204,17 @@ export function ChatInterface() {const isHistoryLoading = !showConversationMessages;const isChatLoading = isHistoryLoading && !isTask;+ // The empty-state ChatSuggestions overlay is absolutely positioned with+ // `pointer-events-auto`, so it would block clicks on any /model entry+ // rendered behind it. Once the user has run /model, the conversation is+ // no longer logically empty — hide suggestions so the profile list is+ // interactive.+ const hasModelEntries = useModelStore((s) =>+ conversationId+ ? (s.entriesByConversation[conversationId]?.length ?? 0) > 0+ : false,+ );+const handleSendMessage = async (content: string,originalImages: File[],@@ -391,6 +404,7 @@ export function ChatInterface() {{!hasSubstantiveAgentActions &&!hasPendingUserMessages &&!userEventsExist &&+ !hasModelEntries &&!isChatLoading && (<ChatSuggestionsonSuggestionsClick={(message) => setMessageToSend(message)}@@ -437,6 +451,10 @@ export function ChatInterface() {* keeps its own gate (`!userEventsExist && !hasSubstantiveAgentActions`)* so brand-new conversations show suggestions, not an empty chat.*/}+ {/* /model entries created before any event is rendered are+ anchored to `null` and live above the message list. */}+ <ModelMessages conversationId={conversationId} anchorEventId={null} />+{showConversationMessages && renderableEvents.length > 0 && (<Messagesmessages={renderableEvents}diff --git a/src/components/features/chat/interactive-chat-box.tsx b/src/components/features/chat/interactive-chat-box.tsxindex a17075b4df..13292a830b 100644--- a/src/components/features/chat/interactive-chat-box.tsx+++ b/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";@@ -139,7 +140,7 @@ export function InteractiveChatBox({}};- const handleSubmit = useBtwInterceptor(+ const handleAfterModel = useBtwInterceptor(conversation?.id ?? null,(message) => {// When the user opts in via the "upload as file" checkbox, route@@ -153,6 +154,10 @@ export function InteractiveChatBox({clearAllFiles();},);+ const handleSubmit = useModelInterceptor(+ conversation?.id ?? null,+ handleAfterModel,+ );const handleSuggestionsClick = (suggestion: string) => {handleSubmit(suggestion);diff --git a/src/components/features/chat/model-messages.tsx b/src/components/features/chat/model-messages.tsxnew file mode 100644index 0000000000..50bd1d9a65--- /dev/null+++ b/src/components/features/chat/model-messages.tsx@@ -0,0 +1,125 @@+import React from "react";+import { Trans } from "react-i18next";+import { ChevronDown, ChevronRight } from "lucide-react";+import { useModelStore } from "#/stores/model-store";+import { I18nKey } from "#/i18n/declaration";+import type { ProfileInfo } from "#/api/profiles-service/profiles-service.api";+import { GenericEventMessage } from "./generic-event-message";++interface ProfileRowProps {+ profile: ProfileInfo;+}++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)}+ aria-expanded={expanded}+ aria-label={`Toggle details for ${profile.name}`}+ className="w-full py-1.5 px-2 text-left flex items-center gap-2 hover:bg-neutral-700 transition-colors cursor-pointer"+ >+ <span className="text-neutral-300">+ {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </span>+ <span className="font-semibold text-neutral-200 text-sm">+ {profile.name}+ </span>+ </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 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: (+ <span className="font-mono text-neutral-200 bg-neutral-800 px-1 rounded" />+ ),+ }}+ />+ </span>+ }+ details=""+ />+ );+ }++ const isEmpty = entry.profiles.length === 0;+ return (+ <GenericEventMessage+ key={entry.id}+ title={+ <span>+ {isEmpty ? (+ <Trans i18nKey={I18nKey.MODEL$NO_SAVED_PROFILES} />+ ) : (+ <Trans+ i18nKey={I18nKey.MODEL$AVAILABLE_PROFILES}+ values={{ count: entry.profiles.length }}+ />+ )}+ </span>+ }+ details={+ isEmpty ? (+ <span className="text-neutral-300 text-sm px-2 py-1 block">+ <Trans i18nKey={I18nKey.MODEL$NO_PROFILES_HINT} />+ </span>+ ) : (+ <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/src/hooks/chat/model-command-event-anchor.ts b/src/hooks/chat/model-command-event-anchor.tsnew file mode 100644index 0000000000..9bd75b7bd1--- /dev/null+++ b/src/hooks/chat/model-command-event-anchor.ts@@ -0,0 +1,13 @@+import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";+import { useEventStore } from "#/stores/use-event-store";++export const getLastRenderableEventId = (): string | null => {+ const { uiEvents } = useEventStore.getState();++ for (let index = uiEvents.length - 1; index >= 0; index -= 1) {+ const event = uiEvents[index];+ if (shouldRenderEvent(event)) return String(event.id);+ }++ return null;+};diff --git a/src/hooks/chat/use-model-interceptor.ts b/src/hooks/chat/use-model-interceptor.tsnew file mode 100644index 0000000000..6a545a3210--- /dev/null+++ b/src/hooks/chat/use-model-interceptor.ts@@ -0,0 +1,88 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import { useSwitchLlmProfileAndLog } from "#/hooks/mutation/use-switch-llm-profile-and-log";+import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-anchor";+import { LLM_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";+import { I18nKey } from "#/i18n/declaration";+import { useActiveBackend } from "#/contexts/active-backend-context";+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 (or when on a cloud backend, which doesn't support profiles)+ * falls through to `onSubmit`.+ */+export const useModelInterceptor = (+ conversationId: string | null | undefined,+ onSubmit: (message: string) => void,+) => {+ const showProfiles = useModelStore((s) => s.show);+ const queryClient = useQueryClient();+ const switchAndLog = useSwitchLlmProfileAndLog();+ const { backend, orgId } = useActiveBackend();+ const isLocal = backend.kind === "local";+ const { t } = useTranslation();++ return useCallback(+ (message: string) => {+ const trimmed = message.trim();+ const isModel =+ trimmed === MODEL_COMMAND || trimmed.startsWith(MODEL_PREFIX);+ if (!conversationId || !isLocal || !isModel) {+ onSubmit(message);+ return;+ }++ const arg = trimmed.slice(MODEL_COMMAND.length).trim();++ if (arg) {+ switchAndLog(conversationId, arg);+ return;+ }++ const anchorEventId = getLastRenderableEventId();++ // Imperative fetch through the query cache so the result lands on the+ // same key `useLlmProfiles` reads. `staleTime: 0` forces a fresh fetch+ // each time the user types /model.+ // Multiple rapid /model submissions intentionally append multiple chat+ // entries, matching normal command history behavior rather than replacing+ // earlier results.++ queryClient+ .fetchQuery({+ queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backend.id, orgId],+ queryFn: ProfilesService.listProfiles,+ staleTime: 0,+ })+ .then(({ profiles }) =>+ showProfiles(conversationId, anchorEventId, profiles),+ )+ .catch((err: unknown) => {+ const fallback = t(I18nKey.MODEL$LIST_FAILED);+ const messageText =+ err instanceof Error && err.message ? err.message : fallback;+ displayErrorToast(messageText);+ });+ },+ [+ conversationId,+ isLocal,+ onSubmit,+ showProfiles,+ queryClient,+ switchAndLog,+ backend.id,+ orgId,+ t,+ ],+ );+};diff --git a/src/hooks/chat/use-slash-command.ts b/src/hooks/chat/use-slash-command.tsindex 273357d494..5b8fa6dd5c 100644--- a/src/hooks/chat/use-slash-command.ts+++ b/src/hooks/chat/use-slash-command.ts@@ -2,8 +2,9 @@ import { useState, useCallback, useEffect, useMemo, useRef } from "react";import { useConversationSkills } from "#/hooks/query/use-conversation-skills";import { Skill } from "#/api/conversation-service/agent-server-conversation-service.types";import { Microagent } from "#/api/open-hands.types";-import { BUILT_IN_COMMANDS } from "#/utils/constants";+import { BUILT_IN_COMMANDS, MODEL_COMMAND } from "#/utils/constants";import { useActiveBackend } from "#/contexts/active-backend-context";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";export type SlashCommandSkill = Skill | Microagent;@@ -13,6 +14,8 @@ export interface SlashCommandItem {command: string;}+type SlashCompletionKind = "command" | "model-profile";+/** Get the cursor's character offset within a contentEditable element. */function getCursorOffset(element: HTMLElement): number {const selection = window.getSelection();@@ -34,19 +37,27 @@ export const useSlashCommand = () => {const { data: skills, isLoading: isSkillsLoading } = useConversationSkills();const isCloud = useActiveBackend().backend.kind === "cloud";+ const { data: profilesData, isLoading: isProfilesLoading } = useLlmProfiles({+ enabled: !isCloud,+ });const [isMenuOpen, setIsMenuOpen] = useState(false);const [filterText, setFilterText] = useState("");+ const [completionKind, setCompletionKind] =+ useState<SlashCompletionKind>("command");const [selectedIndex, setSelectedIndex] = useState(0);// Build slash command items from built-in commands + skills:// - Built-in commands (like /new) are included for V1 conversations// - /new is cloud-only — local backends don't surface it+ // - /model is local-only — cloud backends don't have profiles// - Skills with explicit "/" triggers use those triggers// - AgentSkills without "/" triggers get a derived "/<name>" commandconst slashItems = useMemo(() => {- const items: SlashCommandItem[] = BUILT_IN_COMMANDS.filter(- (cmd) => isCloud || cmd.command !== "/new",- );+ const items: SlashCommandItem[] = BUILT_IN_COMMANDS.filter((cmd) => {+ if (cmd.command === "/new") return isCloud;+ if (cmd.command === MODEL_COMMAND) return !isCloud;+ return true;+ });// Wait for skills to finish initial load so all commands appear togetherif (isSkillsLoading) return items;@@ -69,16 +80,38 @@ export const useSlashCommand = (return items;}, [skills, isSkillsLoading, isCloud]);+ const modelProfileItems = useMemo<SlashCommandItem[]>(() => {+ if (isCloud) return [];++ return (profilesData?.profiles ?? []).map((profile) => {+ const command = `${MODEL_COMMAND} ${profile.name}`;+ return {+ command,+ skill: {+ name: profile.name,+ type: "agentskills",+ content: profile.model+ ? `Switch to ${profile.model}`+ : "Switch to this LLM profile",+ triggers: [command],+ },+ };+ });+ }, [profilesData?.profiles, isCloud]);+// Filter items based on user input after "/"const filteredItems = useMemo(() => {- if (!filterText) return slashItems;+ const sourceItems =+ completionKind === "model-profile" ? modelProfileItems : slashItems;+ if (!filterText) return sourceItems;const lower = filterText.toLowerCase();- return slashItems.filter(+ return sourceItems.filter((item) =>- item.command.slice(1).toLowerCase().includes(lower) ||- item.skill.name.toLowerCase().includes(lower),+ item.command.toLowerCase().includes(lower) ||+ item.skill.name.toLowerCase().includes(lower) ||+ item.skill.content?.toLowerCase().includes(lower),);- }, [slashItems, filterText]);+ }, [completionKind, modelProfileItems, slashItems, filterText]);// Keep refs in sync so handleSlashKeyDown always reads the latest values,// avoiding stale closures from React's batched state updates.@@ -102,6 +135,7 @@ export const useSlashCommand = (// Returns the filter text (characters after "/") and the range of the// slash word within the full input text, or null if no slash word found.const getSlashText = useCallback((): {+ kind: SlashCompletionKind;text: string;start: number;end: number;@@ -116,6 +150,23 @@ export const useSlashCommand = (if (cursor < 0) return null;const textBeforeCursor = text.slice(0, cursor);++ const modelMatch = textBeforeCursor.match(/(^|\s)(\/model(?:\s+\S*)?)$/);+ if (modelMatch) {+ const modelCommand = modelMatch[2];+ const start = textBeforeCursor.length - modelCommand.length;+ const afterCursor = text.slice(cursor);+ const trailing = afterCursor.match(/^\S*/);+ const end = cursor + (trailing ? trailing[0].length : 0);++ return {+ kind: "model-profile",+ text: modelCommand.replace(/^\/model(?:\s+)?/, ""),+ start,+ end,+ };+ }+// Match a "/" preceded by whitespace or at position 0, followed by// non-whitespace characters, ending right at the cursor.const match = textBeforeCursor.match(/(^|\s)(\/\S*)$/);@@ -130,22 +181,34 @@ export const useSlashCommand = (const trailing = afterCursor.match(/^\S*/);const end = cursor + (trailing ? trailing[0].length : 0);- return { text: slashWord.slice(1), start, end }; // strip leading "/"+ return { kind: "command", text: slashWord.slice(1), start, end }; // strip leading "/"}, [chatInputRef]);// Update the menu state based on current inputconst updateSlashMenu = useCallback(() => {const result = getSlashText();- if (result !== null && slashItems.length > 0) {+ const hasItems =+ result?.kind === "model-profile"+ ? modelProfileItems.length > 0 || isProfilesLoading+ : slashItems.length > 0;++ if (result !== null && hasItems) {+ setCompletionKind(result.kind);setFilterText(result.text);slashRangeRef.current = { start: result.start, end: result.end };setIsMenuOpen(true);} else {setIsMenuOpen(false);setFilterText("");+ setCompletionKind("command");slashRangeRef.current = null;}- }, [getSlashText, slashItems.length]);+ }, [+ getSlashText,+ isProfilesLoading,+ modelProfileItems.length,+ slashItems.length,+ ]);// Select an item and replace only the slash word with the commandconst selectItem = useCallback(@@ -189,6 +252,7 @@ export const useSlashCommand = (setIsMenuOpen(false);setFilterText("");+ setCompletionKind("command");setSelectedIndex(0);slashRangeRef.current = null;diff --git a/src/hooks/mutation/use-switch-llm-profile-and-log.ts b/src/hooks/mutation/use-switch-llm-profile-and-log.tsnew file mode 100644index 0000000000..502899bb95--- /dev/null+++ b/src/hooks/mutation/use-switch-llm-profile-and-log.ts@@ -0,0 +1,42 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { getLastRenderableEventId } from "#/hooks/chat/model-command-event-anchor";+import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";+import { useModelStore } from "#/stores/model-store";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { I18nKey } from "#/i18n/declaration";++/**+ * Switch the conversation's LLM profile and render the result inline (same+ * UX as `/model <name>`). On success the switch is recorded against the+ * last rendered event so the confirmation lines up with where the user+ * issued the command.+ */+export function useSwitchLlmProfileAndLog() {+ const { mutate } = useSwitchLlmProfile();+ const recordSwitch = useModelStore((s) => s.recordSwitch);+ const { t } = useTranslation();++ return useCallback(+ (conversationId: string, profileName: string) => {+ const anchorEventId = getLastRenderableEventId();++ mutate(+ { conversationId, profileName },+ {+ onSuccess: () =>+ recordSwitch(conversationId, anchorEventId, profileName),+ onError: (err: unknown) => {+ const fallback = t(I18nKey.MODEL$SWITCH_FAILED, {+ name: profileName,+ });+ const message =+ err instanceof Error && err.message ? err.message : fallback;+ displayErrorToast(message);+ },+ },+ );+ },+ [mutate, recordSwitch, t],+ );+}diff --git a/src/hooks/mutation/use-switch-llm-profile.ts b/src/hooks/mutation/use-switch-llm-profile.tsnew file mode 100644index 0000000000..cf422be5a9--- /dev/null+++ b/src/hooks/mutation/use-switch-llm-profile.ts@@ -0,0 +1,28 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";++interface SwitchLlmProfileVars {+ conversationId: string;+ profileName: string;+}++/**+ * Switches the conversation's active LLM profile via the backend.+ * Invalidates the conversation query so anything reading the model picks up+ * the new value.+ */+export const useSwitchLlmProfile = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({ conversationId, profileName }: SwitchLlmProfileVars) =>+ AgentServerConversationService.switchProfile(conversationId, profileName),+ onSuccess: (_data, { conversationId }) => {+ queryClient.invalidateQueries({+ queryKey: ["user", "conversation", conversationId],+ });+ },+ // Caller renders an inline message + handles error toast manually.+ meta: { disableToast: true },+ });+};diff --git a/src/hooks/query/use-llm-profiles.ts b/src/hooks/query/use-llm-profiles.tsindex cb88e9c709..46e9367a19 100644--- a/src/hooks/query/use-llm-profiles.ts+++ b/src/hooks/query/use-llm-profiles.ts@@ -5,7 +5,11 @@ import { CONFIG_CACHE_OPTIONS, LLM_PROFILES_QUERY_KEYS } from "./query-keys";export { LLM_PROFILES_QUERY_KEYS };-export function useLlmProfiles() {+interface UseLlmProfilesOptions {+ enabled?: boolean;+}++export function useLlmProfiles(options: UseLlmProfilesOptions = {}) {const { backend, orgId } = useActiveBackend();return useQuery({@@ -13,6 +17,7 @@ export function useLlmProfiles() {queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backend.id, orgId],queryFn: ProfilesService.listProfiles,...CONFIG_CACHE_OPTIONS,+ enabled: options.enabled ?? true,meta: { disableToast: true },});}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 844e3543a4..091b5ca5de 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -8261,6 +8261,108 @@"uk": "Команди","ca": "Comandes"},+ "MODEL$AVAILABLE_PROFILES": {+ "en": "Available profiles ({{count}})",+ "ja": "利用可能なプロファイル ({{count}})",+ "zh-CN": "可用配置文件 ({{count}})",+ "zh-TW": "可用設定檔 ({{count}})",+ "ko-KR": "사용 가능한 프로필 ({{count}})",+ "no": "Tilgjengelige profiler ({{count}})",+ "ar": "الملفات الشخصية المتاحة ({{count}})",+ "de": "Verfügbare Profile ({{count}})",+ "fr": "Profils disponibles ({{count}})",+ "it": "Profili disponibili ({{count}})",+ "pt": "Perfis disponíveis ({{count}})",+ "es": "Perfiles disponibles ({{count}})",+ "ca": "Perfils disponibles ({{count}})",+ "tr": "Kullanılabilir profiller ({{count}})",+ "uk": "Доступні профілі ({{count}})"+ },+ "MODEL$NO_SAVED_PROFILES": {+ "en": "No saved profiles",+ "ja": "保存済みプロファイルはありません",+ "zh-CN": "没有已保存的配置文件",+ "zh-TW": "沒有已儲存的設定檔",+ "ko-KR": "저장된 프로필이 없습니다",+ "no": "Ingen lagrede profiler",+ "ar": "لا توجد ملفات شخصية محفوظة",+ "de": "Keine gespeicherten Profile",+ "fr": "Aucun profil enregistré",+ "it": "Nessun profilo salvato",+ "pt": "Nenhum perfil salvo",+ "es": "No hay perfiles guardados",+ "ca": "No hi ha perfils desats",+ "tr": "Kaydedilmiş profil yok",+ "uk": "Немає збережених профілів"+ },+ "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 til å opprette en profil, og kjør deretter /model <name> for å bytte.",+ "ar": "استخدم صفحة إعدادات LLM لإنشاء ملف شخصي، ثم شغّل /model <name> للتبديل.",+ "de": "Erstelle ein Profil auf der LLM-Einstellungsseite und führe dann /model <name> aus, um zu wechseln.",+ "fr": "Utilisez la page des paramètres LLM pour créer un profil, puis exécutez /model <name> pour changer.",+ "it": "Usa la pagina delle impostazioni LLM per creare un profilo, poi esegui /model <name> per cambiare.",+ "pt": "Use a página de configurações de LLM para criar um perfil e execute /model <name> para trocar.",+ "es": "Usa la página de configuración de LLM para crear un perfil y luego ejecuta /model <name> para cambiar.",+ "ca": "Fes servir la pàgina de configuració de LLM per crear un perfil i després executa /model <name> per canviar.",+ "tr": "Bir profil oluşturmak için LLM ayarları sayfasını kullanın, ardından geçiş yapmak için /model <name> çalıştırın.",+ "uk": "Скористайтеся сторінкою налаштувань LLM, щоб створити профіль, а потім виконайте /model <name> для перемикання."+ },+ "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 profilen <cmd>{{name}}</cmd>",+ "ar": "ℹ️ تم التبديل إلى الملف الشخصي <cmd>{{name}}</cmd>",+ "de": "ℹ️ Zu Profil <cmd>{{name}}</cmd> gewechselt",+ "fr": "ℹ️ Passage au 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>",+ "ca": "ℹ️ S'ha canviat al perfil <cmd>{{name}}</cmd>",+ "tr": "ℹ️ <cmd>{{name}}</cmd> profiline geçildi",+ "uk": "ℹ️ Перемкнено на профіль <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 liste LLM-profiler",+ "ar": "فشل في عرض ملفات LLM الشخصية",+ "de": "LLM-Profile konnten nicht aufgelistet werden",+ "fr": "Impossible de lister les profils LLM",+ "it": "Impossibile elencare i profili LLM",+ "pt": "Falha ao listar perfis de LLM",+ "es": "No se pudieron listar los perfiles LLM",+ "ca": "No s'han pogut llistar els perfils LLM",+ "tr": "LLM profilleri listelenemedi",+ "uk": "Не вдалося отримати список профілів 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 profilen '{{name}}'",+ "ar": "فشل في التبديل إلى الملف الشخصي '{{name}}'",+ "de": "Wechsel zu Profil '{{name}}' fehlgeschlagen",+ "fr": "Impossible de passer au profil '{{name}}'",+ "it": "Impossibile passare al profilo '{{name}}'",+ "pt": "Falha ao alternar para o perfil '{{name}}'",+ "es": "No se pudo cambiar al perfil '{{name}}'",+ "ca": "No s'ha pogut canviar al perfil '{{name}}'",+ "tr": "'{{name}}' profiline geçilemedi",+ "uk": "Не вдалося перемкнутися на профіль '{{name}}'"+ },"CHAT_INTERFACE$CONNECTING": {"en": "Connecting... (this may take 1-2 minutes)","ja": "接続中...(1-2分かかる場合があります)",diff --git a/src/stores/model-store.ts b/src/stores/model-store.tsnew file mode 100644index 0000000000..7b95799238--- /dev/null+++ b/src/stores/model-store.ts@@ -0,0 +1,84 @@+import { create } from "zustand";+import { devtools } from "zustand/middleware";+import { v4 as uuidv4 } from "uuid";+import type { ProfileInfo } from "#/api/profiles-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 rendered events at the time+ * of /model).+ */+ anchorEventId: string | null;+ profiles: ProfileInfo[];+ switchedTo?: string;+}++interface ModelState {+ entriesByConversation: Record<string, ModelListEntry[]>;+}++interface ModelActions {+ show: (+ conversationId: string,+ anchorEventId: string | null,+ profiles: ProfileInfo[],+ ) => void;+ recordSwitch: (+ conversationId: string,+ anchorEventId: string | null,+ profileName: string,+ ) => void;+ clear: (conversationId: string) => void;+ clearAll: () => void;+}++type ModelStore = ModelState & ModelActions;++const appendEntry = (+ state: ModelState,+ conversationId: string,+ entry: ModelListEntry,+): Pick<ModelState, "entriesByConversation"> => ({+ entriesByConversation: {+ ...state.entriesByConversation,+ [conversationId]: [+ ...(state.entriesByConversation[conversationId] ?? []),+ entry,+ ],+ },+});++export const useModelStore = create<ModelStore>()(+ devtools(+ (set) => ({+ entriesByConversation: {},+ show: (conversationId, anchorEventId, profiles) =>+ set((s) =>+ appendEntry(s, conversationId, {+ id: uuidv4(),+ anchorEventId,+ profiles,+ }),+ ),+ recordSwitch: (conversationId, anchorEventId, profileName) =>+ set((s) =>+ appendEntry(s, conversationId, {+ id: uuidv4(),+ anchorEventId,+ profiles: [],+ switchedTo: profileName,+ }),+ ),+ clear: (conversationId) =>+ set((s) => {+ const entriesByConversation = { ...s.entriesByConversation };+ delete entriesByConversation[conversationId];+ return { entriesByConversation };+ }),+ clearAll: () => set({ entriesByConversation: {} }),+ }),+ { name: "ModelStore" },+ ),+);diff --git a/src/utils/constants.ts b/src/utils/constants.tsindex 8eb6825730..fbbf582dba 100644--- a/src/utils/constants.ts+++ b/src/utils/constants.ts@@ -74,6 +74,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[] = [{@@ -94,6 +97,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