Skip to content

🙌 OpenHands: AI-Driven Development

feat: add direct-prompt Model Router settings (#16147)

Juan Pedro Michelini Jorge94e156a8c7b7
diff --git a/__tests__/api/cloud/meta-profiles-service.test.ts b/__tests__/api/cloud/meta-profiles-service.test.ts
new file mode 100644
index 0000000000..067f2e4d40
--- /dev/null
+++ b/__tests__/api/cloud/meta-profiles-service.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import MetaProfilesService, {
+ type MetaProfile,
+} from "#/api/meta-profiles-service/meta-profiles-service.api";
+import {
+ getFetchCall,
+ getJsonBody,
+ mockJsonResponse,
+} from "./fetch-test-utils";
+
+const backend: Backend = {
+ id: "prod",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-token",
+ kind: "cloud",
+};
+const orgId = "org-1";
+const base = `${backend.host}/api/organizations/${orgId}/meta-profiles`;
+const config: MetaProfile = {
+ classifier_model: "classifier",
+ prompt_template: "Route {{ instance_text }}",
+ model_table: null,
+};
+const originalFetch = global.fetch;
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ setRegisteredBackends([backend]);
+ setActiveSelection({ backendId: backend.id, orgId });
+ fetchMock.mockReset();
+ global.fetch = fetchMock as typeof fetch;
+});
+
+afterEach(() => {
+ global.fetch = originalFetch;
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+});
+
+describe("MetaProfilesService against a cloud org", () => {
+ it("routes list and detail reads through the org API", async () => {
+ fetchMock
+ .mockResolvedValueOnce(
+ mockJsonResponse({ meta_profiles: [], active_meta_profile: null }),
+ )
+ .mockResolvedValueOnce(mockJsonResponse({ name: "pareto", config }));
+
+ await MetaProfilesService.listMetaProfiles();
+ expect(getFetchCall(fetchMock)[0]).toBe(base);
+ await MetaProfilesService.getMetaProfile("pareto");
+ expect(getFetchCall(fetchMock, 1)[0]).toBe(`${base}/pareto`);
+ });
+
+ it("routes save, activation, and delete through the org API", async () => {
+ fetchMock.mockImplementation(() =>
+ Promise.resolve(mockJsonResponse({ name: "pareto", message: "ok" })),
+ );
+
+ await MetaProfilesService.saveMetaProfile("pareto", config);
+ let [url, init] = getFetchCall(fetchMock);
+ expect(url).toBe(`${base}/pareto`);
+ expect(init.method).toBe("POST");
+ expect(getJsonBody(init)).toEqual(config);
+
+ await MetaProfilesService.activateMetaProfile("pareto");
+ [url, init] = getFetchCall(fetchMock, 1);
+ expect(url).toBe(`${base}/pareto/activate`);
+ expect(init.method).toBe("POST");
+
+ await MetaProfilesService.deleteMetaProfile("pareto");
+ [url, init] = getFetchCall(fetchMock, 2);
+ expect(url).toBe(`${base}/pareto`);
+ expect(init.method).toBe("DELETE");
+ });
+});
+
+it("rejects a cloud backend without an organization", async () => {
+ setActiveSelection({ backendId: backend.id });
+ await expect(MetaProfilesService.listMetaProfiles()).rejects.toThrow(
+ /organization-bound/i,
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+});
diff --git a/__tests__/api/conversation-service.test.ts b/__tests__/api/conversation-service.test.ts
index 30e99a1553..25b58002d6 100644
--- a/__tests__/api/conversation-service.test.ts
+++ b/__tests__/api/conversation-service.test.ts
@@ -4,8 +4,18 @@ import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-w
import ConversationService from "#/api/conversation-service/conversation-service.api";
import { clearAgentServerHomeDirCache } from "#/api/agent-server-home";
-const fileUploadMock = vi.fn();
-const getHomeMock = vi.fn();
+const { fileUploadMock, getHomeMock, getVSCodeUrlMock, vscodeClientMock } =
+ vi.hoisted(() => {
+ const getVSCodeUrlMock = vi.fn();
+ return {
+ fileUploadMock: vi.fn(),
+ getHomeMock: vi.fn(),
+ getVSCodeUrlMock,
+ vscodeClientMock: vi.fn(function VSCodeClientMock() {
+ return { getUrl: getVSCodeUrlMock };
+ }),
+ };
+ });
vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({
RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {
@@ -17,6 +27,7 @@ vi.mock("@openhands/typescript-client/clients", () => ({
FileClient: vi.fn(function FileClientMock() {
return { getHome: getHomeMock };
}),
+ VSCodeClient: vscodeClientMock,
}));
function makeFile(name: string) {
@@ -140,4 +151,28 @@ describe("ConversationService", () => {
expect(result.skipped_files).toEqual([]);
});
});
+
+ describe("getVSCodeUrl", () => {
+ it("targets the current conversation runtime URL and session key", async () => {
+ ConversationService.setCurrentConversation({
+ id: "conv-1",
+ conversation_url:
+ "https://runtime.example.com/api/conversations/conv-1",
+ session_api_key: "runtime-session-key",
+ workspace: { working_dir: "/workspace/project/conv-1" },
+ } as never);
+ getVSCodeUrlMock.mockResolvedValue("https://runtime.example.com/vscode");
+
+ await expect(ConversationService.getVSCodeUrl("conv-1")).resolves.toEqual(
+ { vscode_url: "https://runtime.example.com/vscode" },
+ );
+
+ expect(vscodeClientMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: "https://runtime.example.com",
+ apiKey: "runtime-session-key",
+ }),
+ );
+ });
+ });
});
diff --git a/__tests__/components/features/settings/integrations-settings-link.test.tsx b/__tests__/components/features/settings/integrations-settings-link.test.tsx
index 1a9cf99b24..b5ae28c473 100644
--- a/__tests__/components/features/settings/integrations-settings-link.test.tsx
+++ b/__tests__/components/features/settings/integrations-settings-link.test.tsx
@@ -75,9 +75,9 @@ describe("IntegrationsSettingsLink", () => {
);
});
- it("renders nothing when the canvas is locked to a Cloud host", () => {
+ it("renders a direct Integrations shortcut when the canvas is locked to a Cloud host", () => {
// Arrange — SaaS / self-hosted OHE serve the canvas with `--lock-to-cloud`;
- // the OHE settings shell already exposes Integrations.
+ // keep Integrations visible beside the broader All Cloud Settings link.
vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
@@ -86,6 +86,9 @@ describe("IntegrationsSettingsLink", () => {
renderWithProviders();
// Assert
- expect(screen.queryByTestId("settings-integrations-link")).toBeNull();
+ expect(screen.getByTestId("settings-integrations-link")).toHaveAttribute(
+ "href",
+ "https://app.all-hands.dev/settings/integrations",
+ );
});
});
diff --git a/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx b/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx
new file mode 100644
index 0000000000..01255d42fc
--- /dev/null
+++ b/__tests__/components/settings/meta-llm-profiles/meta-llm-settings-view.test.tsx
@@ -0,0 +1,417 @@
+import { describe, expect, it, vi, beforeEach, type Mock } from "vitest";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { HttpError } from "@openhands/typescript-client";
+import { renderWithProviders } from "test-utils";
+import { MetaLlmSettingsView } from "#/components/features/settings/meta-llm-profiles";
+import * as useMetaProfilesHook from "#/hooks/query/use-meta-profiles";
+import * as useLlmProfilesHook from "#/hooks/query/use-llm-profiles";
+import * as useProviderConnectionsHook from "#/hooks/query/use-provider-connections";
+import * as useSaveMetaProfileHook from "#/hooks/mutation/use-save-meta-profile";
+import * as useActivateMetaProfileHook from "#/hooks/mutation/use-activate-meta-profile";
+import * as useDeleteMetaProfileHook from "#/hooks/mutation/use-delete-meta-profile";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import {
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_NAME,
+} from "#/components/features/settings/meta-llm-profiles/default-meta-profile";
+import { collectRequiredRouterModelNames } from "#/components/features/settings/meta-llm-profiles/router-profiles";
+
+vi.mock("#/hooks/query/use-meta-profiles");
+vi.mock("#/hooks/query/use-llm-profiles");
+vi.mock("#/hooks/query/use-provider-connections");
+vi.mock("#/hooks/mutation/use-save-meta-profile");
+vi.mock("#/hooks/mutation/use-activate-meta-profile");
+vi.mock("#/hooks/mutation/use-delete-meta-profile");
+vi.mock("#/api/meta-profiles-service/meta-profiles-service.api");
+vi.mock("#/api/profiles-service/profiles-service.api");
+vi.mock("#/utils/custom-toast-handlers");
+
+const mockMetaProfiles = [
+ {
+ name: "balanced",
+ classifier_model: "minimax",
+ num_classes: 0,
+ },
+ {
+ name: "cheap",
+ classifier_model: "minimax",
+ num_classes: 0,
+ },
+];
+
+const mockLlmProfiles = [
+ { name: "minimax", model: "m", base_url: null, api_key_set: true },
+ { name: "gpt", model: "g", base_url: null, api_key_set: true },
+ { name: "deepseek", model: "d", base_url: null, api_key_set: true },
+];
+
+const mockProviderConnections = [
+ {
+ id: "conn-openhands",
+ display_name: "OpenHands",
+ provider: "openhands",
+ base_url: null,
+ created_at: 0,
+ updated_at: 0,
+ api_key_set: true,
+ },
+];
+
+function mockMutation<T>(mutateAsync: Mock, overrides: Partial<T> = {}): T {
+ return {
+ mutateAsync,
+ mutate: vi.fn(),
+ isPending: false,
+ isError: false,
+ isSuccess: false,
+ error: null,
+ data: undefined,
+ reset: vi.fn(),
+ status: "idle",
+ isIdle: true,
+ ...overrides,
+ } as T;
+}
+
+describe("MetaLlmSettingsView", () => {
+ const activateMutateAsync = vi.fn();
+ const saveMutateAsync = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: {
+ meta_profiles: mockMetaProfiles,
+ active_meta_profile: "balanced",
+ },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+
+ vi.mocked(useLlmProfilesHook.useLlmProfiles).mockReturnValue({
+ data: { profiles: mockLlmProfiles, active_profile: "minimax" },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useLlmProfilesHook.useLlmProfiles>);
+
+ vi.mocked(
+ useProviderConnectionsHook.useProviderConnections,
+ ).mockReturnValue({
+ data: mockProviderConnections,
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<
+ typeof useProviderConnectionsHook.useProviderConnections
+ >);
+
+ vi.mocked(useSaveMetaProfileHook.useSaveMetaProfile).mockReturnValue(
+ mockMutation(saveMutateAsync),
+ );
+ vi.mocked(
+ useActivateMetaProfileHook.useActivateMetaProfile,
+ ).mockReturnValue(mockMutation(activateMutateAsync));
+ // The delete hook is consumed by the modal that is always mounted.
+ vi.mocked(useDeleteMetaProfileHook.useDeleteMetaProfile).mockReturnValue(
+ mockMutation(vi.fn()),
+ );
+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({
+ name: "minimax",
+ api_key_set: true,
+ config: {
+ model: "litellm_proxy/template",
+ base_url: "https://llm-proxy.example",
+ api_key: "gAAAA_encrypted",
+ },
+ });
+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue({
+ name: "created-profile",
+ message: "Profile saved",
+ });
+ });
+
+ it("renders the list of meta-profiles with an active badge", () => {
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(screen.getByTestId("meta-profile-row-balanced")).toBeInTheDocument();
+ expect(screen.getByTestId("meta-profile-row-cheap")).toBeInTheDocument();
+ // Only the active one shows the badge
+ expect(screen.getAllByTestId("meta-profile-active-badge")).toHaveLength(1);
+ });
+
+ it("shows the empty state when there are no meta-profiles", () => {
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: { meta_profiles: [], active_meta_profile: null },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(screen.getByTestId("meta-profile-empty")).toBeInTheDocument();
+ });
+
+ it("hints when there are no LLM profiles to route between", () => {
+ vi.mocked(useLlmProfilesHook.useLlmProfiles).mockReturnValue({
+ data: { profiles: [], active_profile: null },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useLlmProfilesHook.useLlmProfiles>);
+
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(
+ screen.getByTestId("meta-profile-no-llm-profiles"),
+ ).toBeInTheDocument();
+ });
+
+ const openMaxScoreTemplate = async (
+ user: ReturnType<typeof userEvent.setup>,
+ ) => {
+ await user.click(screen.getByTestId("add-meta-profile"));
+ await user.click(screen.getByTestId("meta-profile-template-max-score"));
+ };
+
+ it("opens the template chooser when clicking Add Model Router", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("add-meta-profile"));
+
+ expect(
+ screen.getByTestId("meta-profile-template-modal"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("meta-profile-template-max-score")).toBeEnabled();
+ expect(screen.getByTestId("meta-profile-template-min-cost")).toBeEnabled();
+ expect(screen.getByTestId("meta-profile-template-custom")).toBeEnabled();
+ });
+
+ it("opens the max-score default editor from the template chooser", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await openMaxScoreTemplate(user);
+
+ expect(screen.getByTestId("meta-profile-editor")).toBeInTheDocument();
+ expect(screen.getByTestId("meta-profile-name-input")).toHaveValue(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ );
+ });
+
+ it("opens the min-cost default editor from the template chooser", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("add-meta-profile"));
+ await user.click(screen.getByTestId("meta-profile-template-min-cost"));
+
+ expect(screen.getByTestId("meta-profile-name-input")).toHaveValue(
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_NAME,
+ );
+ expect(screen.getByTestId("meta-profile-prompt-template")).toHaveValue(
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT.prompt_template,
+ );
+ expect(screen.getByTestId("meta-profile-model-table")).toHaveValue(
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT.model_table,
+ );
+ // The built-in templates pre-select the first provider connection so the
+ // router's LLM profiles are created on save.
+ expect(screen.getByTestId("meta-profile-router-connection")).toHaveValue(
+ "OpenHands (openhands)",
+ );
+ });
+
+ it("opens a blank custom editor from the template chooser", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("add-meta-profile"));
+ await user.click(screen.getByTestId("meta-profile-template-custom"));
+
+ expect(screen.getByTestId("meta-profile-name-input")).toHaveValue("");
+ expect(screen.getByTestId("meta-profile-classifier-input")).toHaveValue("");
+ expect(screen.getByTestId("meta-profile-prompt-template")).toHaveValue("");
+ expect(screen.getByTestId("meta-profile-model-table")).toHaveValue("");
+ // Custom profiles default to "don't create profiles".
+ expect(
+ screen.getByTestId("meta-profile-router-connection"),
+ ).not.toHaveValue("OpenHands (openhands)");
+ });
+
+ it("creates missing router LLM profiles linked to the selected provider connection", async () => {
+ const user = userEvent.setup();
+ saveMutateAsync.mockResolvedValue({ name: "default-max-score-pareto" });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await openMaxScoreTemplate(user);
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ // Every model in the built-in table (plus the classifier) that is not
+ // already a saved profile is created, linked to the connection.
+ const expectedNames = collectRequiredRouterModelNames(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ ).filter((n) => !["minimax", "gpt", "deepseek"].includes(n.toLowerCase()));
+
+ await waitFor(() =>
+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("gpt-5.4", {
+ llm: {
+ model: "openhands/gpt-5.4",
+ usage_id: "gpt-5.4",
+ provider_connection_id: "conn-openhands",
+ },
+ include_secrets: true,
+ }),
+ );
+ expect(ProfilesService.saveProfile).toHaveBeenCalledTimes(
+ expectedNames.length,
+ );
+ // Router profiles reuse shared credentials via the connection, so they
+ // must not clone an active profile's key.
+ expect(ProfilesService.getProfile).not.toHaveBeenCalled();
+ await waitFor(() => expect(saveMutateAsync).toHaveBeenCalled());
+ });
+
+ it("activates the first meta-profile after creating it", async () => {
+ const user = userEvent.setup();
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: { meta_profiles: [], active_meta_profile: null },
+ isLoading: false,
+ error: null,
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+ saveMutateAsync.mockResolvedValue({ name: "pareto" });
+ activateMutateAsync.mockResolvedValue({ name: "pareto" });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await openMaxScoreTemplate(user);
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "pareto");
+ fireEvent.change(screen.getByTestId("meta-profile-classifier-input"), {
+ target: { value: "minimax" },
+ });
+ fireEvent.change(screen.getByTestId("meta-profile-prompt-template"), {
+ target: { value: "Task:\n{{ instance_text }}" },
+ });
+ fireEvent.change(screen.getByTestId("meta-profile-model-table"), {
+ target: { value: "" },
+ });
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ await waitFor(() =>
+ expect(saveMutateAsync).toHaveBeenCalledWith({
+ name: "pareto",
+ config: {
+ classifier_model: "minimax",
+ classes: [],
+ prompt_template: "Task:\n{{ instance_text }}",
+ model_table: null,
+ },
+ }),
+ );
+ await waitFor(() =>
+ expect(activateMutateAsync).toHaveBeenCalledWith("pareto"),
+ );
+ });
+
+ it("does not auto-activate a newly-created meta-profile when one is already active", async () => {
+ const user = userEvent.setup();
+ saveMutateAsync.mockResolvedValue({ name: "pareto" });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await openMaxScoreTemplate(user);
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "pareto");
+ fireEvent.change(screen.getByTestId("meta-profile-classifier-input"), {
+ target: { value: "minimax" },
+ });
+ fireEvent.change(screen.getByTestId("meta-profile-prompt-template"), {
+ target: { value: "Task:\n{{ instance_text }}" },
+ });
+ fireEvent.change(screen.getByTestId("meta-profile-model-table"), {
+ target: { value: "" },
+ });
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ await waitFor(() => expect(saveMutateAsync).toHaveBeenCalled());
+ expect(activateMutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("activates a meta-profile via the actions menu", async () => {
+ const user = userEvent.setup();
+ activateMutateAsync.mockResolvedValue({ name: "cheap" });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("meta-profile-menu-trigger-cheap"));
+ await user.click(screen.getByTestId("meta-profile-set-active"));
+
+ await waitFor(() =>
+ expect(activateMutateAsync).toHaveBeenCalledWith("cheap"),
+ );
+ });
+
+ it("loads the config and opens the editor via the actions menu", async () => {
+ const user = userEvent.setup();
+ vi.mocked(MetaProfilesService.getMetaProfile).mockResolvedValue({
+ name: "balanced",
+ config: {
+ classifier_model: "minimax",
+ classes: [],
+ prompt_template: "Route this task.\n{{ instance_text }}",
+ model_table: "- GPT-5.4",
+ },
+ });
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("meta-profile-menu-trigger-balanced"));
+ await user.click(screen.getByTestId("meta-profile-edit"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("meta-profile-editor")).toBeInTheDocument(),
+ );
+ expect(MetaProfilesService.getMetaProfile).toHaveBeenCalledWith("balanced");
+ });
+
+ it("shows an explicit unsupported-backend message when the API is missing (404)", () => {
+ // Older backends (pre software-agent-sdk #3744) have no /api/meta-profiles
+ // endpoint and return 404; the page must explain that instead of a dead
+ // generic error, and must not offer Add.
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ error: new HttpError(404, "Not Found"),
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(screen.getByTestId("meta-profile-unsupported")).toBeInTheDocument();
+ expect(screen.queryByTestId("add-meta-profile")).not.toBeInTheDocument();
+ });
+
+ it("shows the generic error for non-404 failures", () => {
+ vi.mocked(useMetaProfilesHook.useMetaProfiles).mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ error: new HttpError(500, "Internal Server Error"),
+ } as unknown as ReturnType<typeof useMetaProfilesHook.useMetaProfiles>);
+
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ expect(
+ screen.queryByTestId("meta-profile-unsupported"),
+ ).not.toBeInTheDocument();
+ // The Add affordance remains for transient/server errors.
+ expect(screen.getByTestId("add-meta-profile")).toBeInTheDocument();
+ });
+
+ it("disables Set active in the menu for the already-active profile", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(<MetaLlmSettingsView />);
+
+ await user.click(screen.getByTestId("meta-profile-menu-trigger-balanced"));
+
+ expect(screen.getByTestId("meta-profile-set-active")).toBeDisabled();
+ });
+});
diff --git a/__tests__/components/settings/meta-llm-profiles/meta-profile-editor.test.tsx b/__tests__/components/settings/meta-llm-profiles/meta-profile-editor.test.tsx
new file mode 100644
index 0000000000..2280943ca4
--- /dev/null
+++ b/__tests__/components/settings/meta-llm-profiles/meta-profile-editor.test.tsx
@@ -0,0 +1,268 @@
+import { describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { renderWithProviders } from "test-utils";
+import { MetaProfileEditor } from "#/components/features/settings/meta-llm-profiles";
+import type { MetaProfile } from "#/api/meta-profiles-service/meta-profiles-service.api";
+import {
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+} from "#/components/features/settings/meta-llm-profiles/default-meta-profile";
+
+const AVAILABLE = ["minimax", "minimax-m3", "gpt", "deepseek"];
+
+const CONNECTIONS = [
+ {
+ id: "conn-openhands",
+ display_name: "OpenHands",
+ provider: "openhands",
+ base_url: null,
+ created_at: 0,
+ updated_at: 0,
+ api_key_set: true,
+ },
+];
+
+const FILLED: MetaProfile = {
+ classifier_model: "minimax",
+ classes: [],
+ prompt_template:
+ "Return JSON with the best model.\n{{ model_table }}\nTask:\n{{ instance_text }}",
+ model_table: "- GPT-5.4\n- MiniMax-M3",
+};
+
+describe("MetaProfileEditor", () => {
+ it("prefills create mode with the max-score Pareto router", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ providerConnections={CONNECTIONS}
+ selectRouterConnectionByDefault
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId("meta-profile-name-input")).toHaveValue(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ );
+ expect(screen.getByTestId("meta-profile-classifier-input")).toHaveValue(
+ "minimax-m3",
+ );
+ expect(screen.getByTestId("meta-profile-prompt-template")).toHaveValue(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT.prompt_template,
+ );
+ expect(screen.getByTestId("meta-profile-model-table")).toHaveValue(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT.model_table,
+ );
+ expect(screen.getByTestId("meta-profile-router-connection")).toHaveValue(
+ "OpenHands (openhands)",
+ );
+
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ expect(onSave).toHaveBeenCalledWith(
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ "conn-openhands",
+ );
+ });
+
+ it("enables Save in edit mode with a complete config and saves it", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="edit"
+ initialName="balanced"
+ initialConfig={FILLED}
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ const save = screen.getByTestId("meta-profile-save");
+ expect(save).toBeEnabled();
+
+ await user.click(save);
+
+ expect(onSave).toHaveBeenCalledWith("balanced", FILLED, null);
+ });
+
+ it("disables the name field in edit mode", () => {
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="edit"
+ initialName="balanced"
+ initialConfig={FILLED}
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId("meta-profile-name-input")).toBeDisabled();
+ });
+
+ it("requires the prompt template to include the instance_text placeholder", () => {
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="edit"
+ initialName="balanced"
+ initialConfig={{
+ ...FILLED,
+ prompt_template: "Return JSON with the best model.",
+ }}
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId("meta-profile-save")).toBeDisabled();
+ });
+
+ it("rejects a duplicate name in create mode and blocks Save", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ initialConfig={FILLED}
+ availableProfiles={AVAILABLE}
+ existingNames={["balanced"]}
+ isSaving={false}
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "balanced");
+
+ expect(screen.getByTestId("meta-profile-name-taken")).toBeInTheDocument();
+ const save = screen.getByTestId("meta-profile-save");
+ expect(save).toBeDisabled();
+
+ await user.click(save);
+ expect(onSave).not.toHaveBeenCalled();
+ });
+
+ it("accepts a unique name in create mode", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ initialConfig={FILLED}
+ providerConnections={CONNECTIONS}
+ selectRouterConnectionByDefault
+ availableProfiles={AVAILABLE}
+ existingNames={["balanced"]}
+ isSaving={false}
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "fast");
+
+ expect(
+ screen.queryByTestId("meta-profile-name-taken"),
+ ).not.toBeInTheDocument();
+ const save = screen.getByTestId("meta-profile-save");
+ expect(save).toBeEnabled();
+
+ await user.click(save);
+ expect(onSave).toHaveBeenCalledWith("fast", FILLED, "conn-openhands");
+ });
+
+ it("shows provider connection controls even before connections exist", () => {
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(
+ screen.getByTestId("meta-profile-router-connection"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("meta-profile-add-provider-connection"),
+ ).toBeInTheDocument();
+ });
+
+ it("returns no connection when the picker is set to don't create", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ initialConfig={FILLED}
+ providerConnections={CONNECTIONS}
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={onSave}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ await user.clear(screen.getByTestId("meta-profile-name-input"));
+ await user.type(screen.getByTestId("meta-profile-name-input"), "fast");
+ // Without selectRouterConnectionByDefault the picker starts on "don't
+ // create", so no provider connection is returned.
+ await user.click(screen.getByTestId("meta-profile-save"));
+
+ expect(onSave).toHaveBeenCalledWith("fast", FILLED, null);
+ });
+
+ it("allows the existing name in edit mode (no duplicate warning)", () => {
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="edit"
+ initialName="balanced"
+ initialConfig={FILLED}
+ availableProfiles={AVAILABLE}
+ existingNames={["balanced"]}
+ isSaving={false}
+ onSave={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(
+ screen.queryByTestId("meta-profile-name-taken"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTestId("meta-profile-save")).toBeEnabled();
+ });
+
+ it("calls onCancel when Cancel is clicked", async () => {
+ const user = userEvent.setup();
+ const onCancel = vi.fn();
+ renderWithProviders(
+ <MetaProfileEditor
+ mode="create"
+ availableProfiles={AVAILABLE}
+ isSaving={false}
+ onSave={vi.fn()}
+ onCancel={onCancel}
+ />,
+ );
+
+ await user.click(screen.getByTestId("meta-profile-cancel"));
+ expect(onCancel).toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/components/settings/meta-llm-profiles/router-profiles.test.ts b/__tests__/components/settings/meta-llm-profiles/router-profiles.test.ts
new file mode 100644
index 0000000000..796386852e
--- /dev/null
+++ b/__tests__/components/settings/meta-llm-profiles/router-profiles.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildRouterModel,
+ collectRequiredRouterModelNames,
+ parseModelTableNames,
+} from "#/components/features/settings/meta-llm-profiles/router-profiles";
+
+describe("parseModelTableNames", () => {
+ it("extracts the leading token of each list row and ignores descriptions", () => {
+ const table = [
+ "- GPT-5.4: swe-bench: 75.60%/$0.63; gaia: 82.40%",
+ "- MiniMax-M3 efficient fallback",
+ "not a list line",
+ "- claude-opus-4-8",
+ ].join("\n");
+ expect(parseModelTableNames(table)).toEqual([
+ "GPT-5.4",
+ "MiniMax-M3",
+ "claude-opus-4-8",
+ ]);
+ });
+
+ it("de-duplicates while preserving first-seen order", () => {
+ expect(parseModelTableNames("- a x\n- b y\n- a z")).toEqual(["a", "b"]);
+ });
+
+ it("de-duplicates case-insensitively while preserving the first spelling", () => {
+ expect(parseModelTableNames("- MiniMax-M3 x\n- minimax-m3 y")).toEqual([
+ "MiniMax-M3",
+ ]);
+ });
+
+ it("returns an empty list for empty or missing tables", () => {
+ expect(parseModelTableNames("")).toEqual([]);
+ expect(parseModelTableNames(null)).toEqual([]);
+ expect(parseModelTableNames(undefined)).toEqual([]);
+ });
+});
+
+describe("buildRouterModel", () => {
+ it("lower-cases the provider and prefixes the model name", () => {
+ expect(buildRouterModel("OpenHands", "GPT-5.4")).toBe("openhands/GPT-5.4");
+ expect(buildRouterModel("anthropic", "claude-opus-4-8")).toBe(
+ "anthropic/claude-opus-4-8",
+ );
+ });
+});
+
+describe("collectRequiredRouterModelNames", () => {
+ it("combines table names with the classifier, de-duplicated", () => {
+ expect(
+ collectRequiredRouterModelNames({
+ classifier_model: "MiniMax-M3",
+ model_table: "- GPT-5.4 stats\n- MiniMax-M3 stats",
+ }),
+ ).toEqual(["GPT-5.4", "MiniMax-M3"]);
+ });
+
+ it("de-duplicates the classifier against table names case-insensitively", () => {
+ expect(
+ collectRequiredRouterModelNames({
+ classifier_model: "minimax-m3",
+ model_table: "- MiniMax-M3 stats",
+ }),
+ ).toEqual(["MiniMax-M3"]);
+ });
+
+ it("ignores a blank classifier and empty tables", () => {
+ expect(
+ collectRequiredRouterModelNames({
+ classifier_model: "",
+ model_table: null,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx b/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx
new file mode 100644
index 0000000000..333d769f68
--- /dev/null
+++ b/__tests__/hooks/mutation/use-delete-meta-profile.test.tsx
@@ -0,0 +1,103 @@
+import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
+import React from "react";
+import { renderHook, waitFor, act } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { useDeleteMetaProfile } from "#/hooks/mutation/use-delete-meta-profile";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import {
+ META_PROFILES_QUERY_KEYS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+
+vi.mock("#/api/meta-profiles-service/meta-profiles-service.api");
+vi.mock("#/api/settings-service/settings-service.api");
+
+describe("useDeleteMetaProfile", () => {
+ let queryClient: QueryClient;
+ let wrapper: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) => React.ReactElement;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ );
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ vi.clearAllMocks();
+ });
+
+ it("calls MetaProfilesService.deleteMetaProfile with name", async () => {
+ vi.mocked(MetaProfilesService.deleteMetaProfile).mockResolvedValue({
+ name: "balanced",
+ message: "deleted",
+ });
+
+ const { result } = renderHook(() => useDeleteMetaProfile(), { wrapper });
+
+ await act(async () => {
+ await result.current.mutateAsync("balanced");
+ });
+
+ expect(MetaProfilesService.deleteMetaProfile).toHaveBeenCalledWith(
+ "balanced",
+ );
+ });
+
+ it("invalidates the meta-profile AND settings caches on success", async () => {
+ // Deleting the active meta-profile clears active_meta_profile in settings,
+ // so the settings caches must be refreshed too (mirrors activation).
+ vi.mocked(MetaProfilesService.deleteMetaProfile).mockResolvedValue({
+ name: "balanced",
+ message: "deleted",
+ });
+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
+ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");
+
+ const { result } = renderHook(() => useDeleteMetaProfile(), { wrapper });
+
+ await act(async () => {
+ await result.current.mutateAsync("balanced");
+ });
+
+ expect(invalidateCacheSpy).toHaveBeenCalled();
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: META_PROFILES_QUERY_KEYS.all,
+ });
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: SETTINGS_QUERY_KEYS.personal(),
+ });
+ });
+
+ it("propagates delete errors", async () => {
+ vi.mocked(MetaProfilesService.deleteMetaProfile).mockRejectedValue(
+ new Error("nope"),
+ );
+
+ const { result } = renderHook(() => useDeleteMetaProfile(), { wrapper });
+
+ await expect(
+ act(async () => {
+ await result.current.mutateAsync("balanced");
+ }),
+ ).rejects.toThrow("nope");
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+ });
+});
diff --git a/__tests__/hooks/query/use-conversation-metrics.test.tsx b/__tests__/hooks/query/use-conversation-metrics.test.tsx
index 44cab91f80..d34df19afd 100644
--- a/__tests__/hooks/query/use-conversation-metrics.test.tsx
+++ b/__tests__/hooks/query/use-conversation-metrics.test.tsx
@@ -5,6 +5,12 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useConversationMetrics } from "#/hooks/query/use-conversation-metrics";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
const runtimeInfo = {
@@ -29,21 +35,32 @@ const runtimeInfo = {
},
};
-function makeWrapper() {
+function makeWrapper({ activeBackend = false } = {}) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
- return ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={client}>{children}</QueryClientProvider>
- );
+ return ({ children }: { children: React.ReactNode }) => {
+ const content = activeBackend ? (
+ <ActiveBackendProvider>{children}</ActiveBackendProvider>
+ ) : (
+ children
+ );
+ return <QueryClientProvider client={client}>{content}</QueryClientProvider>;
+ };
}
afterEach(() => {
vi.restoreAllMocks();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ __resetActiveStoreForTests();
});
beforeEach(() => {
vi.restoreAllMocks();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ __resetActiveStoreForTests();
});
describe("useConversationMetrics", () => {
@@ -56,6 +73,17 @@ describe("useConversationMetrics", () => {
.spyOn(AgentServerConversationService, "getRuntimeConversation")
.mockResolvedValue(runtimeInfo);
+ setRegisteredBackends([
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: "https://app.example.com",
+ apiKey: "cloud-key",
+ kind: "cloud",
+ },
+ ]);
+ setActiveSelection({ backendId: "cloud-1", orgId: null });
+
// Act
const { result } = renderHook(
() =>
@@ -65,7 +93,7 @@ describe("useConversationMetrics", () => {
"session-key",
true,
),
- { wrapper: makeWrapper() },
+ { wrapper: makeWrapper({ activeBackend: true }) },
);
// Assert — the query fires and resolves to the runtime data.
@@ -79,6 +107,31 @@ describe("useConversationMetrics", () => {
);
});
+ it("waits for the runtime URL before polling metrics on cloud backends", async () => {
+ const spy = vi.spyOn(
+ AgentServerConversationService,
+ "getRuntimeConversation",
+ );
+ setRegisteredBackends([
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: "https://app.example.com",
+ apiKey: "cloud-key",
+ kind: "cloud",
+ },
+ ]);
+ setActiveSelection({ backendId: "cloud-1", orgId: null });
+
+ const { result } = renderHook(
+ () => useConversationMetrics("conv-abc", null, "session-key", true),
+ { wrapper: makeWrapper({ activeBackend: true }) },
+ );
+
+ expect(result.current.data).toBeUndefined();
+ expect(spy).not.toHaveBeenCalled();
+ });
+
it("fires the query when sessionApiKey is null (local backends without auth)", async () => {
// Arrange
const spy = vi
diff --git a/__tests__/hooks/use-settings-nav-items.test.tsx b/__tests__/hooks/use-settings-nav-items.test.tsx
index 2b95fc2b1a..033d1f5afb 100644
--- a/__tests__/hooks/use-settings-nav-items.test.tsx
+++ b/__tests__/hooks/use-settings-nav-items.test.tsx
@@ -181,9 +181,9 @@ describe("useSettingsNavItems", () => {
}
});
- it("lists only the Application page when the canvas is locked to a Cloud host", () => {
+ it("lists every Canvas settings page when locked to an organization Cloud host", () => {
// Arrange — SaaS / self-hosted OHE serve the canvas with `--lock-to-cloud`;
- // the OHE settings shell ("All Cloud Settings") owns every other page.
+ // the Cloud settings shell stays reachable through "All Cloud Settings".
vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");
useConfigMock.mockReturnValue({ data: createConfig() });
useActiveBackendMock.mockReturnValue({
@@ -198,6 +198,6 @@ describe("useSettingsNavItems", () => {
const paths = result.current
.filter((item) => item.type === "item")
.map((item) => (item.type === "item" ? item.item.to : null));
- expect(paths).toEqual(["/settings/app"]);
+ expect(paths).toEqual(OSS_NAV_ITEMS.map((item) => item.to));
});
});
diff --git a/src/api/cloud/client.test.ts b/src/api/cloud/client.test.ts
new file mode 100644
index 0000000000..9e39868e06
--- /dev/null
+++ b/src/api/cloud/client.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const {
+ CloudClientMock,
+ getAgentServerBaseUrlMock,
+ getAgentServerHeadersMock,
+} = vi.hoisted(() => ({
+ CloudClientMock: vi.fn(function CloudClient(
+ this: { proxy?: unknown },
+ options: { proxy?: unknown },
+ ) {
+ this.proxy = options.proxy;
+ }),
+ getAgentServerBaseUrlMock: vi.fn(),
+ getAgentServerHeadersMock: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ CloudClient: CloudClientMock,
+}));
+
+vi.mock("../agent-server-config", () => ({
+ getAgentServerBaseUrl: getAgentServerBaseUrlMock,
+ getAgentServerHeaders: getAgentServerHeadersMock,
+}));
+
+vi.mock("../backend-registry/active-store", () => ({
+ getActiveBackend: () => ({
+ backend: {
+ id: "locked-cloud",
+ name: "OpenHands Cloud",
+ host: "https://cloud.example.test",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ },
+ orgId: "org-1",
+ }),
+}));
+
+import { createCloudClientForRuntime } from "./client";
+
+describe("createCloudClientForRuntime", () => {
+ beforeEach(() => {
+ CloudClientMock.mockClear();
+ getAgentServerBaseUrlMock.mockReset();
+ getAgentServerHeadersMock.mockReset();
+ });
+
+ it("uses the cloud host as the runtime proxy in frontend-only SaaS", () => {
+ getAgentServerBaseUrlMock.mockReturnValue(null);
+
+ createCloudClientForRuntime();
+
+ expect(CloudClientMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: "https://cloud.example.test",
+ orgId: "org-1",
+ proxy: { host: "https://cloud.example.test", headers: {} },
+ }),
+ );
+ });
+
+ it("keeps using the local Agent Server proxy when configured", () => {
+ getAgentServerBaseUrlMock.mockReturnValue("http://localhost:8000");
+ getAgentServerHeadersMock.mockReturnValue({
+ "X-Session-API-Key": "session-key",
+ });
+
+ createCloudClientForRuntime();
+
+ expect(CloudClientMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ proxy: {
+ host: "http://localhost:8000",
+ headers: { "X-Session-API-Key": "session-key" },
+ },
+ }),
+ );
+ });
+});
diff --git a/src/api/cloud/client.ts b/src/api/cloud/client.ts
index f50b0951b7..125633ed71 100644
--- a/src/api/cloud/client.ts
+++ b/src/api/cloud/client.ts
@@ -32,8 +32,12 @@ function activeOrgForBackend(backend: Backend): string | null {
export function createCloudClient(backend?: Backend): CloudClient {
const target = requireCloudBackend(backend);
- const proxyBaseUrl = getAgentServerBaseUrl();
- const proxyHeaders = proxyBaseUrl ? getAgentServerHeaders() : {};
+ const agentServerProxyBaseUrl = getAgentServerBaseUrl();
+ // Standalone Canvas uses its local Agent Server as the runtime proxy. The
+ // SaaS Canvas is frontend-only, so fall back to the selected Cloud host,
+ // which exposes the same /api/cloud-proxy endpoint.
+ const proxyBaseUrl = agentServerProxyBaseUrl ?? target.host;
+ const proxyHeaders = agentServerProxyBaseUrl ? getAgentServerHeaders() : {};
return new CloudClient({
host: target.host,
@@ -43,14 +47,10 @@ export function createCloudClient(backend?: Backend): CloudClient {
// transport used for direct and proxied calls. Per-request
// `timeoutSeconds` still overrides it for direct calls.
timeout: 30_000,
- ...(proxyBaseUrl
- ? {
- proxy: {
- host: proxyBaseUrl,
- headers: proxyHeaders,
- },
- }
- : {}),
+ proxy: {
+ host: proxyBaseUrl,
+ headers: proxyHeaders,
+ },
});
}
diff --git a/src/api/cloud/meta-profiles-service.api.ts b/src/api/cloud/meta-profiles-service.api.ts
new file mode 100644
index 0000000000..bfd919c4b0
--- /dev/null
+++ b/src/api/cloud/meta-profiles-service.api.ts
@@ -0,0 +1,79 @@
+import { getActiveBackend } from "../backend-registry/active-store";
+import type { Backend } from "../backend-registry/types";
+import type {
+ ActivateMetaProfileResponse,
+ MetaProfile,
+ MetaProfileDetailResponse,
+ MetaProfileListResponse,
+ MetaProfileMutationResponse,
+} from "../meta-profiles-service/meta-profiles-service.api";
+import { callCloudProxy } from "./proxy";
+
+function cloudMetaProfilesTarget(): { backend: Backend; base: string } {
+ const { backend, orgId } = getActiveBackend();
+ if (backend.kind !== "cloud" || !orgId) {
+ throw new Error(
+ "Cloud Model Router settings require an organization-bound backend.",
+ );
+ }
+ return {
+ backend,
+ base: `/api/organizations/${encodeURIComponent(orgId)}/meta-profiles`,
+ };
+}
+
+export async function fetchCloudMetaProfiles(): Promise<MetaProfileListResponse> {
+ const { backend, base } = cloudMetaProfilesTarget();
+ return callCloudProxy<MetaProfileListResponse>({
+ backend,
+ method: "GET",
+ path: base,
+ });
+}
+
+export async function fetchCloudMetaProfile(
+ name: string,
+): Promise<MetaProfileDetailResponse> {
+ const { backend, base } = cloudMetaProfilesTarget();
+ return callCloudProxy<MetaProfileDetailResponse>({
+ backend,
+ method: "GET",
+ path: `${base}/${encodeURIComponent(name)}`,
+ });
+}
+
+export async function saveCloudMetaProfile(
+ name: string,
+ config: MetaProfile,
+): Promise<MetaProfileMutationResponse> {
+ const { backend, base } = cloudMetaProfilesTarget();
+ return callCloudProxy<MetaProfileMutationResponse>({
+ backend,
+ method: "POST",
+ path: `${base}/${encodeURIComponent(name)}`,
+ body: config,
+ });
+}
+
+export async function deleteCloudMetaProfile(
+ name: string,
+): Promise<MetaProfileMutationResponse> {
+ const { backend, base } = cloudMetaProfilesTarget();
+ return callCloudProxy<MetaProfileMutationResponse>({
+ backend,
+ method: "DELETE",
+ path: `${base}/${encodeURIComponent(name)}`,
+ });
+}
+
+export async function activateCloudMetaProfile(
+ name: string,
+): Promise<ActivateMetaProfileResponse> {
+ const { backend, base } = cloudMetaProfilesTarget();
+ return callCloudProxy<ActivateMetaProfileResponse>({
+ backend,
+ method: "POST",
+ path: `${base}/${encodeURIComponent(name)}/activate`,
+ body: {},
+ });
+}
diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.ts
index 249854cc47..c125654019 100644
--- a/src/api/conversation-service/conversation-service.api.ts
+++ b/src/api/conversation-service/conversation-service.api.ts
@@ -28,6 +28,7 @@ class ConversationService {
private static getClientOverrides() {
return {
+ conversationUrl: this.currentConversation?.conversation_url,
sessionApiKey: this.currentConversation?.session_api_key,
};
}
diff --git a/src/api/meta-profiles-service/meta-profiles-service.api.ts b/src/api/meta-profiles-service/meta-profiles-service.api.ts
new file mode 100644
index 0000000000..93c3fec90f
--- /dev/null
+++ b/src/api/meta-profiles-service/meta-profiles-service.api.ts
@@ -0,0 +1,101 @@
+/**
+ * MetaProfilesService wraps the agent-server's ``/api/meta-profiles`` endpoints
+ * (added in software-agent-sdk PR #4287). A meta-profile is a model-routing
+ * configuration consumed by the ``route_task_to_model`` tool: it names a
+ * ``classifier_model`` and a direct ``prompt_template``
+ * whose returned ``model`` value is matched to saved LLM profile names.
+ *
+ * Transport goes through the SDK's typed ``MetaProfilesClient`` (mirroring how
+ * ``ProfilesService`` uses ``ProfilesClient``), creating a client per call so
+ * it picks up the current backend configuration.
+ *
+ * Types are re-exported from the SDK for consumer convenience.
+ */
+import { MetaProfilesClient } from "@openhands/typescript-client/clients";
+import type {
+ ActivateMetaProfileResponse,
+ MetaProfile,
+ MetaProfileClass,
+ MetaProfileDetailResponse,
+ MetaProfileInfo,
+ MetaProfileListResponse,
+ MetaProfileMutationResponse,
+} from "@openhands/typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
+import { getActiveBackend } from "../backend-registry/active-store";
+import {
+ activateCloudMetaProfile,
+ deleteCloudMetaProfile,
+ fetchCloudMetaProfile,
+ fetchCloudMetaProfiles,
+ saveCloudMetaProfile,
+} from "../cloud/meta-profiles-service.api";
+
+// Re-export SDK types for consumers
+export type {
+ ActivateMetaProfileResponse,
+ MetaProfile,
+ MetaProfileClass,
+ MetaProfileDetailResponse,
+ MetaProfileInfo,
+ MetaProfileListResponse,
+ MetaProfileMutationResponse,
+};
+
+class MetaProfilesService {
+ static async listMetaProfiles(): Promise<MetaProfileListResponse> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ return fetchCloudMetaProfiles();
+ }
+ return new MetaProfilesClient(
+ getAgentServerClientOptions(),
+ ).listMetaProfiles();
+ }
+
+ static async getMetaProfile(
+ name: string,
+ ): Promise<MetaProfileDetailResponse> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ return fetchCloudMetaProfile(name);
+ }
+ return new MetaProfilesClient(getAgentServerClientOptions()).getMetaProfile(
+ name,
+ );
+ }
+
+ static async saveMetaProfile(
+ name: string,
+ config: MetaProfile,
+ ): Promise<MetaProfileMutationResponse> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ return saveCloudMetaProfile(name, config);
+ }
+ return new MetaProfilesClient(
+ getAgentServerClientOptions(),
+ ).saveMetaProfile(name, config);
+ }
+
+ static async deleteMetaProfile(
+ name: string,
+ ): Promise<MetaProfileMutationResponse> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ return deleteCloudMetaProfile(name);
+ }
+ return new MetaProfilesClient(
+ getAgentServerClientOptions(),
+ ).deleteMetaProfile(name);
+ }
+
+ static async activateMetaProfile(
+ name: string,
+ ): Promise<ActivateMetaProfileResponse> {
+ if (getActiveBackend().backend.kind === "cloud") {
+ return activateCloudMetaProfile(name);
+ }
+ return new MetaProfilesClient(
+ getAgentServerClientOptions(),
+ ).activateMetaProfile(name);
+ }
+}
+
+export default MetaProfilesService;
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-event-content.test.tsx b/src/components/conversation-events/chat/event-content-helpers/get-event-content.test.tsx
index f36dcc327d..f01f6b9b98 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-event-content.test.tsx
+++ b/src/components/conversation-events/chat/event-content-helpers/get-event-content.test.tsx
@@ -819,6 +819,24 @@ describe("observation titles", () => {
key: "MODEL$SWITCHED_TO_PROFILE",
values: { name: "accurate" },
},
+ {
+ name: "failed router switch",
+ observation: observationOf("ClassifyAndSwitchLLMObservation", {
+ is_error: true,
+ model: "fast",
+ }),
+ key: "MODEL$SWITCH_FAILED",
+ values: { name: "fast" },
+ },
+ {
+ name: "successful router switch",
+ observation: observationOf("ClassifyAndSwitchLLMObservation", {
+ is_error: false,
+ model: "accurate",
+ }),
+ key: "MODEL$SWITCHED_TO_PROFILE",
+ values: { name: "accurate" },
+ },
{
name: "browser",
observation: observationOf("BrowserObservation", {}),
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
index d0ae422ac0..bb1ccff2ec 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
+++ b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
@@ -238,6 +238,14 @@ const getObservationEventTitle = (
name: event.observation.profile_name,
};
break;
+ case "ClassifyAndSwitchLLMObservation":
+ observationKey = event.observation.is_error
+ ? "MODEL$SWITCH_FAILED"
+ : "MODEL$SWITCHED_TO_PROFILE";
+ observationValues = {
+ name: event.observation.model,
+ };
+ break;
case "BrowserObservation":
observationKey = "OBSERVATION_MESSAGE$BROWSE";
break;
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-observation-content.ts b/src/components/conversation-events/chat/event-content-helpers/get-observation-content.ts
index 45ec656e43..10259d262d 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-observation-content.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/get-observation-content.ts
@@ -19,6 +19,7 @@ import {
InvokeSkillObservation,
CanvasUIObservation,
SwitchLLMObservation,
+ ClassifyAndSwitchLLMObservation,
} from "#/types/agent-server/core/base/observation";
// File Editor Observations
@@ -211,6 +212,35 @@ const getSwitchLLMObservationContent = (
return parts.join("\n");
};
+// Router-driven model switch (mirrors SwitchLLMObservation, but `model` is the
+// activated profile name and `active_model` is the underlying model string).
+const getClassifyAndSwitchLLMObservationContent = (
+ event: ObservationEvent<ClassifyAndSwitchLLMObservation>,
+): string => {
+ const { observation } = event;
+
+ const textContent = observation.content
+ .filter((c) => c.type === "text")
+ .map((c) => c.text)
+ .join("\n");
+
+ if (observation.is_error) {
+ return textContent
+ ? `**Error:**\n${textContent}`
+ : `**Error:**\nFailed to switch LLM profile.`;
+ }
+
+ const parts = [`**Profile:** \`${observation.model}\``];
+ if (observation.active_model) {
+ parts.push(`**Active model:** \`${observation.active_model}\``);
+ }
+ if (observation.chosen_class) {
+ parts.push(`**Reason:** ${observation.chosen_class}`);
+ }
+
+ return parts.join("\n");
+};
+
// Complex Observations
const getTaskTrackerObservationContent = (
event: ObservationEvent<TaskTrackerObservation>,
@@ -429,6 +459,10 @@ export const getObservationContent = (event: ObservationEvent): string => {
return getSwitchLLMObservationContent(
event as ObservationEvent<SwitchLLMObservation>,
);
+ case "ClassifyAndSwitchLLMObservation":
+ return getClassifyAndSwitchLLMObservationContent(
+ event as ObservationEvent<ClassifyAndSwitchLLMObservation>,
+ );
default:
return getDefaultEventContent(event);
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-observation-result.ts b/src/components/conversation-events/chat/event-content-helpers/get-observation-result.ts
index 0ac7a1eb1d..99ba1fa247 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-observation-result.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/get-observation-result.ts
@@ -52,6 +52,7 @@ export const getObservationResult = (
if (observation.is_error) return "error";
return "success";
case "SwitchLLMObservation":
+ case "ClassifyAndSwitchLLMObservation":
if (observation.is_error) return "error";
return "success";
case "InvokeSkillObservation":
diff --git a/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts b/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
index 5e8005b361..c287a473cd 100644
--- a/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
@@ -92,8 +92,12 @@ export const shouldRenderEvent = (event: OpenHandsEvent) => {
// Successful model switches are rendered through ModelMessages so they
// look identical to `/model <profile>` confirmations. Failed switches
// still render as observations so the error remains visible in chat.
+ // Same treatment for the router-driven classifier switch — its success
+ // path produces the same inline "Switched to" message via the
+ // model-store seam, so it must not render as a raw observation card.
if (
- event.observation.kind === "SwitchLLMObservation" &&
+ (event.observation.kind === "SwitchLLMObservation" ||
+ event.observation.kind === "ClassifyAndSwitchLLMObservation") &&
!event.observation.is_error
) {
return false;
diff --git a/src/components/features/settings/integrations-settings-link.tsx b/src/components/features/settings/integrations-settings-link.tsx
index fcb1b72615..33c8b38356 100644
--- a/src/components/features/settings/integrations-settings-link.tsx
+++ b/src/components/features/settings/integrations-settings-link.tsx
@@ -3,7 +3,6 @@ import { ExternalLink, Puzzle } from "lucide-react";
import { I18nKey } from "#/i18n/declaration";
import { useActiveBackendContext } from "#/contexts/active-backend-context";
import { isNoBackend } from "#/api/backend-registry/active-store";
-import { getLockedCloudHost } from "#/api/agent-server-config";
import { cn } from "#/utils/utils";
import {
SIDEBAR_ICON_SLOT_CLASS,
@@ -13,10 +12,9 @@ import {
} from "#/components/features/sidebar/sidebar-layout";
/**
- * Renders only for cloud backends — local backends have no equivalent
- * hosted integrations settings page. Also hidden when the canvas is locked to
- * a Cloud host (SaaS / self-hosted OHE): the OHE settings shell behind
- * "All Cloud Settings" already exposes Integrations (OHE-3168).
+ * Renders only for cloud backends — local backends have no equivalent hosted
+ * integrations settings page. In locked-to-Cloud deployments this sits beside
+ * "All Cloud Settings" as a direct shortcut to the Cloud integrations page.
*/
export function IntegrationsSettingsLink() {
const { t } = useTranslation("openhands");
@@ -24,7 +22,6 @@ export function IntegrationsSettingsLink() {
const { backend, orgId } = active;
if (isNoBackend(backend) || backend.kind !== "cloud") return null;
- if (getLockedCloudHost() !== null) return null;
// `org` is consumed by the cloud settings loader so the page opens on the
// org that is active here instead of the cloud's last-used org.
diff --git a/src/components/features/settings/meta-llm-profiles/default-meta-profile.ts b/src/components/features/settings/meta-llm-profiles/default-meta-profile.ts
new file mode 100644
index 0000000000..df6f216ab4
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/default-meta-profile.ts
@@ -0,0 +1,140 @@
+import type { MetaProfile } from "#/api/meta-profiles-service/meta-profiles-service.api";
+
+export const DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME =
+ "default-max-score-pareto";
+export const DEFAULT_MIN_COST_PARETO_META_PROFILE_NAME =
+ "default-min-cost-pareto";
+
+export const DEFAULT_MAX_SCORE_PARETO_META_PROFILE_MODEL_TABLE = `- gpt-5.4: swe-bench: 75.60%/$0.63; swt-bench: 70.40%/$0.47; swe-bench-multimodal: 36.80%/$1.45; commit0: 56.20%/$4.04; gaia: 82.40%/$0.61
+- gpt-5.5: swe-bench: 78.20%/$1.52; swt-bench: 83.40%/$0.92; swe-bench-multimodal: 38.20%/$2.81; commit0: 43.80%/$5.56; gaia: 86.10%/$0.74
+- minimax-m3: swe-bench: 76.40%/$0.17; swt-bench: 81.10%/$0.11; swe-bench-multimodal: 36.80%/$0.35; commit0: 25.00%/$0.62; gaia: 66.70%/$0.35
+- claude-opus-4-6: swe-bench: 76.80%/$0.77; swt-bench: 78.80%/$0.43; swe-bench-multimodal: 41.80%/$2.37; commit0: 56.20%/$7.69; gaia: 80.00%/$0.44
+- claude-opus-4-7: swe-bench: 81.60%/$1.33; swt-bench: 80.80%/$0.82; swe-bench-multimodal: 48.50%/$2.83; commit0: 56.20%/$5.69; gaia: 81.20%/$0.89
+- claude-opus-4-8: swe-bench: 83.80%/$0.75; swt-bench: 84.30%/$0.73; swe-bench-multimodal: 50.00%/$1.81; commit0: 62.50%/$7.83; gaia: 78.80%/$1.17
+- claude-fable-5: swe-bench: 95.80%/$1.43; swt-bench: 91.90%/$1.47; swe-bench-multimodal: 70.60%/$4.39; commit0: 62.50%/$12.49; gaia: 84.20%/$7.91
+- kimi-k2.5: swe-bench: 68.80%/$0.41; swt-bench: 61.90%/$0.42; swe-bench-multimodal: 32.80%/$1.62; commit0: 18.80%/$1.26; gaia: 63.60%/$0.38
+- kimi-k2.6: swe-bench: 74.60%/$0.67; swt-bench: 70.40%/$0.33; swe-bench-multimodal: 41.20%/$0.64; commit0: 25.00%/$1.52; gaia: 74.50%/$0.42
+- deepseek-v3.2-reasoner: swe-bench: 71.60%/$0.16; swt-bench: 53.60%/$0.12; swe-bench-multimodal: 27.90%/$0.19; commit0: 25.00%/$0.57; gaia: 50.30%/$0.06
+- claude-sonnet-4-5: swe-bench: 74.20%/$1.19; swt-bench: 68.80%/$0.98; swe-bench-multimodal: 36.80%/$1.89; commit0: 12.50%/$3.23; gaia: 72.70%/$0.87
+- gpt-5.2-codex: swe-bench: 73.80%/$0.94; swt-bench: 67.00%/$0.66; swe-bench-multimodal: 35.90%/$2.97; commit0: 43.80%/$5.50; gaia: 70.90%/$0.55`;
+
+export const DEFAULT_MAX_SCORE_PARETO_META_PROFILE_PROMPT = `You are a model router for an autonomous software agent. Your job is to pick exactly one model for the task below. Do not solve the task; never answer it.
+
+Step 1 — Classify the task into exactly one category:
+- BUG-FIX / CODE REPAIR: fix a defect or implement a change in an existing, mature repository (SWE-bench-like).
+- TEST GENERATION / TEST REPAIR: write or fix tests that reproduce or verify behavior; the deliverable is tests, not the fix (SWT-bench-like).
+- VISUAL / UI / MULTIMODAL: task references screenshots, rendered output, CSS/SVG/canvas, charts, images, or frontend visual behavior (SWE-bench-multimodal-like). HARD SLICE.
+- GREENFIELD / FROM-SCRATCH IMPLEMENTATION: build a library or module from a spec with sparse or skeleton existing code; many functions to implement against a test suite (Commit0-like). HARD SLICE.
+- RESEARCH / QA / INFORMATION GATHERING: web lookup, multi-hop factual reasoning, file/data inspection questions (GAIA-like).
+
+Step 2 — Judge difficulty within the category using four tiers:
+- EASY: small, localized change; clear reproduction; single file or function; unambiguous spec; simple lookup. A strong cheap model very likely solves it.
+- STANDARD: a typical instance — nontrivial but bounded (a focused patch, a coherent test-suite change, a multi-step but contained question).
+- HARD: cross-cutting or subtle; multiple interacting components, tricky reproduction, ambiguous spec, or deep domain knowledge — the kind of instance a strong frontier model plausibly fails.
+- EXCEPTIONAL: clearly among the hardest instances — sprawling changes across many subsystems, deeply ambiguous or contradictory requirements, tasks that even top frontier models routinely fail.
+
+Step 3 — Route using these rules (exact model names):
+
+BUG-FIX / CODE REPAIR:
+- EASY: "minimax-m3" — very strong cheap solver on well-scoped patches; large savings when it solves.
+- STANDARD: "claude-opus-4-8" — best solve-rate-per-dollar on repository bug fixes. Do NOT escalate above it here: escalating on ordinary bug fixes only converts an already-solved instance into a more expensive one.
+- HARD or EXCEPTIONAL (the task text itself signals that claude-opus-4-8 would plausibly fail: sprawling scope, many subsystems, extreme subtlety): "claude-fable-5" — its solve advantage is decisive exactly on these instances.
+
+TEST GENERATION / TEST REPAIR:
+- EASY or STANDARD: "minimax-m3" — near-frontier on test writing at a small fraction of frontier cost; the default for normal test tasks.
+- HARD (complex fixtures, intricate reproduction, deep repo comprehension needed): "claude-opus-4-8".
+- EXCEPTIONAL only (async/flaky/deeply entangled behavior a normal frontier model would likely fail): "claude-fable-5".
+
+VISUAL / UI / MULTIMODAL (HARD SLICE — do not under-route):
+- Default (EASY-but-nontrivial through EXCEPTIONAL): "claude-fable-5" — the strongest multimodal solver by a wide margin; here the extra cost buys solves no other model gets.
+- Only if the task is clearly trivial for a cheap model (e.g., a one-line CSS/text tweak with an obvious, fully specified expected output): "kimi-k2.6".
+
+GREENFIELD / FROM-SCRATCH (HARD SLICE — do not under-route):
+- Default: "claude-opus-4-8" — matches the top solve rate at meaningfully lower cost; do not escalate to claude-fable-5 here, it adds no solve advantage.
+- Only if the spec is small and self-contained (a few functions, clear I/O contract, easy verification): "gpt-5.4".
+
+RESEARCH / QA / INFORMATION GATHERING:
+- Default: "gpt-5.5" — strongest on this category and far cheaper than heavyweight coding models.
+- EASY (a single straightforward lookup or simple file inspection): "gpt-5.4".
+
+Tie-breaking principles:
+- A cheap model only helps if it actually solves; a cheap failure saves nothing and loses the instance. Never pick a cheap model on a HARD SLICE or a HARD/EXCEPTIONAL instance just to reduce cost.
+- Equally, never pay a premium for capability that adds nothing: if claude-opus-4-8 is likely to solve, do not escalate to claude-fable-5. Escalate ONLY where its solve advantage is decisive: multimodal tasks, or code/test tasks that claude-opus-4-8 would likely fail.
+- Prefer routes likely to solve instances that claude-opus-4-8 would fail; keep claude-opus-4-8 on hard cases it solves.
+- If two models are similarly likely to solve, choose the cheaper one.
+- If the category is genuinely ambiguous, treat it as BUG-FIX / CODE REPAIR and route by difficulty.
+- When difficulty is uncertain between two tiers on a HARD SLICE, choose the higher tier; elsewhere, choose the tier the evidence in the task text best supports.
+
+You may choose any model listed in the model table below; the recommendations above should be followed unless the task text gives a strong, specific reason to deviate.
+
+{{ model_table }}
+
+Return ONLY valid JSON in this exact shape, with the model field containing an exact model name from the table:
+{"model": "<exact model name>", "reason": "<short reason: category + difficulty tier + why this model>"}
+
+Task:
+{{ instance_text }}`;
+
+export const DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT: MetaProfile = {
+ classifier_model: "minimax-m3",
+ classes: [],
+ prompt_template: DEFAULT_MAX_SCORE_PARETO_META_PROFILE_PROMPT,
+ model_table: DEFAULT_MAX_SCORE_PARETO_META_PROFILE_MODEL_TABLE,
+};
+
+export const DEFAULT_MIN_COST_PARETO_META_PROFILE_PROMPT = `You are a model router for an autonomous software-agent task. Select exactly one model to run the task. Do not attempt to solve the task yourself.
+
+ROUTING GOAL:
+Expand the score/cost value frontier by routing each task to the cheapest model that is likely to solve it, and escalating only when the task pattern predicts that cheaper models will fail. A cheap route that fails is a regression, not a savings. An expensive route is justified only when cheaper models would likely miss.
+
+CORE PRINCIPLES:
+- Never reward raw cheapness: pick the cheapest *credible solver*, not the cheapest model.
+- Never pay for prestige: escalate on evidence of task difficulty, not on task importance, repo fame, or urgent-sounding phrasing.
+- The most expensive flagship is rarely the best value even when escalation is warranted; several mid-premium models match or beat it on specific families at a fraction of the cost. Escalate *into the right family specialist*, not upward by price.
+- Protect hard slices (whole-repository buildouts and visually-centered tasks): on these, prefer a likely solve over a small cost saving — but match model strength to actual scope rather than escalating reflexively, because even flagships fail on many of these and the waste is large.
+- Most routine tasks are solvable by strong low/mid-cost models; premium routes should be a minority reserved for tasks with multiple concrete difficulty signals.
+
+TASK FAMILIES AND DECISION LADDERS:
+
+1. Test writing / reproduction tasks (write or extend tests for a described behavior or bug)
+ Default: MiniMax-M3. This family is dominated by cheap strong test models; it has the highest safe-downgrade rate of any family and premium routing here is almost always waste.
+ Escalate (rarely) to GPT-5.5 or claude-opus-4-8 only for genuinely hard testing: intricate fixtures, async/concurrency behavior, deep framework mocking, or tests requiring understanding of a large multi-component interaction. A single unfamiliar framework name is not a difficulty signal.
+
+2. Localized coding / issue fixes in an existing repository (a described bug or small feature with a clear locus)
+ Default: MiniMax-M3, including for large or famous repositories — repo size alone predicts nothing. Use Kimi-K2.6 as an intermediate step when the change is moderately involved but still localized.
+ Escalate to claude-opus-4-8 only when TWO OR MORE concrete signals are present: ambiguous or underspecified behavior, multi-component or cross-layer changes, framework internals, migrations, concurrency, serialization, or data-integrity concerns. Historical escalations on a single signal mostly paid premium prices for tasks the cheap default already solves — treat one signal as a reason to use the intermediate tier, not the premium tier.
+
+3. Information / research / question answering (answer a question using tools, retrieval, or reasoning)
+ Default: Kimi-K2.6 for straightforward lookups and single-hop questions.
+ Escalate readily to GPT-5.4 for multi-hop reasoning, exact numeric or date computation, cross-referencing multiple sources, or tool-heavy research chains — GPT-5.4 is cheap enough that this escalation is low-risk and it is the strongest value in this family. Use GPT-5.5 only when the question stacks several of those demands at once.
+ Do NOT route this family to premium coding flagships: they cost more and solve no more here than GPT-5.4.
+
+4. Visual / multimodal tasks (screenshots, rendering, UI behavior, image-referenced bugs) — PROTECTED SLICE
+ This family has the lowest solve rates overall; under-routing is the dominant failure mode, so bias toward strength.
+ - Incidental visuals (the image merely illustrates a trivial, clearly-localized code edit): Kimi-K2.6 — it is the cheapest model with credible multimodal performance; do not use bargain text-first models here even for simple-looking tasks.
+ - Substantive visual reasoning (layout, rendering pipelines, styling logic, interpreting the screenshot to locate the bug): claude-opus-4-8.
+ - Central, subtle, or multi-state visual behavior (the fix hinges on precise visual semantics or multiple UI states): claude-fable-5 — the strongest model earns its cost here, and cheaper premium models fail often enough that the upgrade is justified.
+
+5. Whole-module / whole-repository buildout (implement a full library or module from a spec to pass a test suite) — PROTECTED SLICE
+ High-variance family: no model solves them all, and blanket top-flagship routing both fails on some and dramatically overpays on others.
+ - Standard-scope builds (moderate API surface, well-specified behavior, mainstream domain): GPT-5.4. It matches the premium tier's solve rate on this family at roughly half the cost; prefer it as the workhorse buildout route.
+ - Large or algorithmically dense builds (numeric/tensor kernels, encoders/decoders, character or protocol handling, parsing suites, wide API surface): claude-fable-5 — mid-premium models have a real failure rate exactly on these, and a failed build wastes the entire (expensive) task.
+ - Never route this family below the GPT-5.4 tier for cost reasons.
+
+ANTI-PATTERNS TO AVOID:
+- Escalating routine repo fixes to a premium model on a single vague difficulty signal — most such tasks are solved far cheaper.
+- Routing research/QA tasks to premium coding flagships instead of GPT-5.4/GPT-5.5.
+- Using claude-opus-4-8 as the buildout workhorse when GPT-5.4 covers standard scope at half the cost.
+- Downgrading protected-
+
+Task:
+{{ instance_text }}
+
+Return ONLY JSON: {"model": "<exact model name>", "reason": "<short reason>"}`;
+
+export const DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT: MetaProfile = {
+ classifier_model: "minimax-m3",
+ classes: [],
+ prompt_template: DEFAULT_MIN_COST_PARETO_META_PROFILE_PROMPT,
+ model_table: DEFAULT_MAX_SCORE_PARETO_META_PROFILE_MODEL_TABLE,
+};
diff --git a/src/components/features/settings/meta-llm-profiles/delete-meta-profile-modal.tsx b/src/components/features/settings/meta-llm-profiles/delete-meta-profile-modal.tsx
new file mode 100644
index 0000000000..d1d51313ac
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/delete-meta-profile-modal.tsx
@@ -0,0 +1,90 @@
+import { useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinner } from "#/components/shared/loading-spinner";
+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";
+import { useDeleteMetaProfile } from "#/hooks/mutation/use-delete-meta-profile";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { I18nKey } from "#/i18n/declaration";
+
+interface DeleteMetaProfileModalProps {
+ name: string | null;
+ onClose: () => void;
+}
+
+export function DeleteMetaProfileModal({
+ name,
+ onClose,
+}: DeleteMetaProfileModalProps) {
+ const { t } = useTranslation("openhands");
+ const deleteMetaProfile = useDeleteMetaProfile();
+ const cancelButtonRef = useRef<HTMLButtonElement>(null);
+
+ if (!name) return null;
+
+ const handleDelete = async () => {
+ try {
+ await deleteMetaProfile.mutateAsync(name);
+ displaySuccessToast(t(I18nKey.SETTINGS$META_PROFILE_DELETED, { name }));
+ onClose();
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC);
+ displayErrorToast(message);
+ }
+ };
+
+ const handleClose = () => {
+ if (!deleteMetaProfile.isPending) {
+ onClose();
+ }
+ };
+
+ const footer = (
+ <>
+ <BrandButton
+ ref={cancelButtonRef}
+ type="button"
+ variant="tertiary"
+ onClick={handleClose}
+ isDisabled={deleteMetaProfile.isPending}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ testId="delete-meta-profile-confirm"
+ type="button"
+ variant="danger"
+ onClick={handleDelete}
+ isDisabled={deleteMetaProfile.isPending}
+ aria-busy={deleteMetaProfile.isPending}
+ >
+ {deleteMetaProfile.isPending ? (
+ <>
+ <LoadingSpinner size="small" />
+ <span className="sr-only">{t(I18nKey.BUTTON$DELETE)}</span>
+ </>
+ ) : (
+ t(I18nKey.BUTTON$DELETE)
+ )}
+ </BrandButton>
+ </>
+ );
+
+ return (
+ <ApiKeyModalBase
+ isOpen
+ title={t(I18nKey.SETTINGS$META_PROFILE_DELETE_TITLE)}
+ footer={footer}
+ onClose={handleClose}
+ initialFocusRef={cancelButtonRef}
+ >
+ <p className="text-sm break-all">
+ {t(I18nKey.SETTINGS$META_PROFILE_DELETE_CONFIRMATION, { name })}
+ </p>
+ </ApiKeyModalBase>
+ );
+}
diff --git a/src/components/features/settings/meta-llm-profiles/index.ts b/src/components/features/settings/meta-llm-profiles/index.ts
new file mode 100644
index 0000000000..a1bd04d8c1
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/index.ts
@@ -0,0 +1,5 @@
+export { MetaLlmSettingsView } from "./meta-llm-settings-view";
+export { MetaProfileEditor } from "./meta-profile-editor";
+export { MetaProfileRow } from "./meta-profile-row";
+export { MetaProfileActionsMenu } from "./meta-profile-actions-menu";
+export { DeleteMetaProfileModal } from "./delete-meta-profile-modal";
diff --git a/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx b/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx
new file mode 100644
index 0000000000..7260bb3c49
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/meta-llm-settings-view.tsx
@@ -0,0 +1,384 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { HttpError } from "@openhands/typescript-client";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { ApiKeyModalBase } from "#/components/features/settings/api-key-modal-base";
+import { LoadingSpinner } from "#/components/shared/loading-spinner";
+import { useMetaProfiles } from "#/hooks/query/use-meta-profiles";
+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
+import { useProviderConnections } from "#/hooks/query/use-provider-connections";
+import { useSaveMetaProfile } from "#/hooks/mutation/use-save-meta-profile";
+import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
+import { useActivateMetaProfile } from "#/hooks/mutation/use-activate-meta-profile";
+import MetaProfilesService, {
+ type MetaProfile,
+} from "#/api/meta-profiles-service/meta-profiles-service.api";
+import type { SaveProfileRequest } from "#/api/profiles-service/profiles-service.api";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { I18nKey } from "#/i18n/declaration";
+import { MetaProfileEditor } from "./meta-profile-editor";
+import { MetaProfileRow } from "./meta-profile-row";
+import { DeleteMetaProfileModal } from "./delete-meta-profile-modal";
+import {
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MIN_COST_PARETO_META_PROFILE_NAME,
+} from "./default-meta-profile";
+import {
+ buildRouterModel,
+ collectRequiredRouterModelNames,
+} from "./router-profiles";
+
+type ViewMode = "list" | "create" | "edit";
+type RouterTemplate = "max-score-pareto" | "min-cost-pareto" | "custom";
+
+interface EditingMetaProfile {
+ name: string;
+ config: MetaProfile;
+}
+
+const CUSTOM_META_PROFILE_CONFIG: MetaProfile = {
+ classifier_model: "",
+ classes: [],
+ prompt_template: "",
+ model_table: "",
+};
+
+export function MetaLlmSettingsView() {
+ const { t } = useTranslation("openhands");
+ const { data, isLoading, error } = useMetaProfiles();
+ const { data: llmProfilesData } = useLlmProfiles();
+ const { data: providerConnections } = useProviderConnections();
+ const saveMetaProfile = useSaveMetaProfile();
+ const saveLlmProfile = useSaveLlmProfile();
+ const activateMetaProfile = useActivateMetaProfile();
+
+ const [view, setView] = useState<ViewMode>("list");
+ const [editing, setEditing] = useState<EditingMetaProfile | null>(null);
+ const [createInitial, setCreateInitial] = useState<EditingMetaProfile | null>(
+ null,
+ );
+ // Whether the create editor should pre-select a provider connection to
+ // populate the router's LLM profiles (true for the built-in Pareto templates,
+ // false for a blank custom profile).
+ const [createRouterProfilesByDefault, setCreateRouterProfilesByDefault] =
+ useState(true);
+ const [isTemplateModalOpen, setIsTemplateModalOpen] = useState(false);
+ const [nameToDelete, setNameToDelete] = useState<string | null>(null);
+ const [isCreatingRouterProfiles, setIsCreatingRouterProfiles] =
+ useState(false);
+ const [createdProviderConnections, setCreatedProviderConnections] = useState<
+ ProviderConnection[]
+ >([]);
+
+ const metaProfiles = data?.meta_profiles ?? [];
+ const active = data?.active_meta_profile ?? null;
+ const availableProfiles = (llmProfilesData?.profiles ?? []).map(
+ (p) => p.name,
+ );
+ const connections = useMemo(() => {
+ const byId = new Map<string, ProviderConnection>();
+ for (const connection of providerConnections ?? []) {
+ byId.set(connection.id, connection);
+ }
+ for (const connection of createdProviderConnections) {
+ byId.set(connection.id, connection);
+ }
+ return [...byId.values()];
+ }, [providerConnections, createdProviderConnections]);
+ const existingNames = metaProfiles.map((p) => p.name);
+ // A 404 means the backend predates the /api/meta-profiles endpoints
+ // (software-agent-sdk #3744). Surface that explicitly instead of a generic
+ // error so the page isn't a dead end on older backends.
+ const isUnsupportedBackend =
+ error instanceof HttpError && error.status === 404;
+
+ const handleActivate = async (name: string) => {
+ try {
+ await activateMetaProfile.mutateAsync(name);
+ displaySuccessToast(t(I18nKey.SETTINGS$META_PROFILE_ACTIVATED, { name }));
+ } catch (activateError) {
+ const message =
+ activateError instanceof Error
+ ? activateError.message
+ : t(I18nKey.ERROR$GENERIC);
+ displayErrorToast(message);
+ }
+ };
+
+ const handleEdit = async (name: string) => {
+ try {
+ const detail = await MetaProfilesService.getMetaProfile(name);
+ setEditing({ name: detail.name, config: detail.config });
+ setView("edit");
+ } catch (loadError) {
+ const message =
+ loadError instanceof Error
+ ? loadError.message
+ : t(I18nKey.ERROR$GENERIC);
+ displayErrorToast(message);
+ }
+ };
+
+ const handleChooseTemplate = (template: RouterTemplate) => {
+ if (template === "max-score-pareto") {
+ setCreateInitial({
+ name: DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+ config: DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ });
+ setCreateRouterProfilesByDefault(true);
+ } else if (template === "min-cost-pareto") {
+ setCreateInitial({
+ name: DEFAULT_MIN_COST_PARETO_META_PROFILE_NAME,
+ config: DEFAULT_MIN_COST_PARETO_META_PROFILE_DEFAULT,
+ });
+ setCreateRouterProfilesByDefault(true);
+ } else {
+ setCreateInitial({ name: "", config: CUSTOM_META_PROFILE_CONFIG });
+ setCreateRouterProfilesByDefault(false);
+ }
+
+ setEditing(null);
+ setIsTemplateModalOpen(false);
+ setView("create");
+ };
+
+ // Create an LLM profile for every model the router config needs that does not
+ // already exist, linking the chosen provider connection for credentials. The
+ // endpoint is derived by convention from the connection's provider
+ // (``<provider>/<name>``); the profile name stays the bare model name so the
+ // router can match the classifier's answer against it.
+ const createMissingRouterLlmProfiles = async (
+ config: MetaProfile,
+ providerConnectionId: string,
+ ) => {
+ const connection = connections.find((c) => c.id === providerConnectionId);
+ if (!connection) {
+ throw new Error("The selected provider connection no longer exists.");
+ }
+
+ const existingProfileNames = new Set(
+ availableProfiles.map((profileName) => profileName.toLowerCase()),
+ );
+ const missingNames = collectRequiredRouterModelNames(config).filter(
+ (modelName) => !existingProfileNames.has(modelName.toLowerCase()),
+ );
+ if (missingNames.length === 0) return;
+
+ for (const modelName of missingNames) {
+ await saveLlmProfile.mutateAsync({
+ name: modelName,
+ request: {
+ llm: {
+ model: buildRouterModel(connection.provider, modelName),
+ usage_id: modelName,
+ provider_connection_id: connection.id,
+ } as SaveProfileRequest["llm"],
+ include_secrets: true,
+ },
+ });
+ }
+ };
+
+ const handleProviderConnectionCreated = (connection: ProviderConnection) => {
+ setCreatedProviderConnections((existing) => [
+ connection,
+ ...existing.filter((item) => item.id !== connection.id),
+ ]);
+ };
+
+ const handleSave = async (
+ name: string,
+ config: MetaProfile,
+ providerConnectionId: string | null,
+ ) => {
+ const shouldActivateAfterCreate = view === "create" && active === null;
+ try {
+ if (view === "create" && providerConnectionId) {
+ setIsCreatingRouterProfiles(true);
+ await createMissingRouterLlmProfiles(config, providerConnectionId);
+ }
+ await saveMetaProfile.mutateAsync({ name, config });
+ if (shouldActivateAfterCreate) {
+ await activateMetaProfile.mutateAsync(name);
+ }
+ displaySuccessToast(t(I18nKey.SETTINGS$META_PROFILE_SAVED, { name }));
+ setView("list");
+ setEditing(null);
+ setCreateInitial(null);
+ } catch (saveError) {
+ const message =
+ saveError instanceof Error
+ ? saveError.message
+ : t(I18nKey.ERROR$GENERIC);
+ displayErrorToast(message);
+ } finally {
+ setIsCreatingRouterProfiles(false);
+ }
+ };
+
+ const handleCancel = () => {
+ setView("list");
+ setEditing(null);
+ setCreateInitial(null);
+ };
+
+ if (isUnsupportedBackend) {
+ return (
+ <p
+ data-testid="meta-profile-unsupported"
+ className="text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_UNSUPPORTED)}
+ </p>
+ );
+ }
+
+ if (view === "create" || view === "edit") {
+ return (
+ <MetaProfileEditor
+ mode={view === "edit" ? "edit" : "create"}
+ initialName={view === "edit" ? editing?.name : createInitial?.name}
+ initialConfig={
+ view === "edit" ? editing?.config : createInitial?.config
+ }
+ providerConnections={connections}
+ selectRouterConnectionByDefault={
+ view === "create" ? createRouterProfilesByDefault : false
+ }
+ availableProfiles={availableProfiles}
+ existingNames={existingNames}
+ isSaving={saveMetaProfile.isPending || isCreatingRouterProfiles}
+ onSave={handleSave}
+ onCancel={handleCancel}
+ onProviderConnectionCreated={handleProviderConnectionCreated}
+ />
+ );
+ }
+
+ return (
+ <>
+ <div className="flex flex-col gap-4">
+ {availableProfiles.length === 0 ? (
+ <p
+ data-testid="meta-profile-no-llm-profiles"
+ className="text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_NO_LLM_PROFILES)}
+ </p>
+ ) : null}
+
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h2 className="text-base font-medium text-white">
+ {t(I18nKey.SETTINGS$META_PROFILES_AVAILABLE)}
+ </h2>
+ <BrandButton
+ testId="add-meta-profile"
+ type="button"
+ variant="secondary"
+ className="ml-auto"
+ onClick={() => {
+ setIsTemplateModalOpen(true);
+ }}
+ >
+ {t(I18nKey.SETTINGS$ADD_META_PROFILE)}
+ </BrandButton>
+ </div>
+
+ {isLoading ? (
+ <div className="flex justify-center py-6">
+ <LoadingSpinner size="small" />
+ </div>
+ ) : null}
+
+ {error ? (
+ <p className="text-sm text-red-400">{t(I18nKey.ERROR$GENERIC)}</p>
+ ) : null}
+
+ {!isLoading && !error && metaProfiles.length === 0 ? (
+ <p
+ data-testid="meta-profile-empty"
+ className="text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_NO_PROFILES)}
+ </p>
+ ) : null}
+
+ {metaProfiles.length > 0 ? (
+ <div className="flex flex-col gap-2" data-testid="meta-profile-list">
+ {metaProfiles.map((info) => (
+ <MetaProfileRow
+ key={info.name}
+ info={info}
+ isActive={info.name === active}
+ onActivate={handleActivate}
+ onEdit={handleEdit}
+ onDelete={setNameToDelete}
+ isActivating={activateMetaProfile.isPending}
+ />
+ ))}
+ </div>
+ ) : null}
+ </div>
+
+ <DeleteMetaProfileModal
+ name={nameToDelete}
+ onClose={() => setNameToDelete(null)}
+ />
+ <ApiKeyModalBase
+ isOpen={isTemplateModalOpen}
+ title={t(I18nKey.SETTINGS$META_PROFILE_TEMPLATE_TITLE)}
+ width="md"
+ onClose={() => setIsTemplateModalOpen(false)}
+ footer={
+ <BrandButton
+ testId="meta-profile-template-cancel"
+ type="button"
+ variant="tertiary"
+ onClick={() => setIsTemplateModalOpen(false)}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ }
+ >
+ <div
+ data-testid="meta-profile-template-modal"
+ className="flex flex-col gap-3"
+ >
+ <BrandButton
+ testId="meta-profile-template-max-score"
+ type="button"
+ variant="secondary"
+ className="justify-start"
+ onClick={() => handleChooseTemplate("max-score-pareto")}
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_TEMPLATE_MAX_SCORE)}
+ </BrandButton>
+ <BrandButton
+ testId="meta-profile-template-min-cost"
+ type="button"
+ variant="secondary"
+ className="justify-start"
+ onClick={() => handleChooseTemplate("min-cost-pareto")}
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_TEMPLATE_MIN_COST)}
+ </BrandButton>
+ <BrandButton
+ testId="meta-profile-template-custom"
+ type="button"
+ variant="secondary"
+ className="justify-start"
+ onClick={() => handleChooseTemplate("custom")}
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_TEMPLATE_CUSTOM)}
+ </BrandButton>
+ </div>
+ </ApiKeyModalBase>
+ </>
+ );
+}
diff --git a/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx b/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx
new file mode 100644
index 0000000000..7aa95515ec
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/meta-profile-actions-menu.tsx
@@ -0,0 +1,231 @@
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useCallback,
+ useState,
+} from "react";
+import ReactDOM from "react-dom";
+import { useTranslation } from "react-i18next";
+import { cn } from "#/utils/utils";
+import { dropdownMenuListClassName } from "#/utils/dropdown-classes";
+import { I18nKey } from "#/i18n/declaration";
+import { ConversationNameContextMenuIconText } from "#/components/features/conversation/conversation-name-context-menu-icon-text";
+import EditIcon from "#/icons/u-edit.svg?react";
+import CheckCircleIcon from "#/icons/u-check-circle.svg?react";
+import DeleteIcon from "#/icons/u-delete.svg?react";
+
+interface MenuItemProps {
+ index: number;
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+ onKeyDown: (e: React.KeyboardEvent, index: number) => void;
+ menuItemsRef: React.MutableRefObject<(HTMLButtonElement | null)[]>;
+ disabled?: boolean;
+ testId: string;
+}
+
+function MenuItem({
+ index,
+ icon,
+ label,
+ onClick,
+ onKeyDown,
+ menuItemsRef,
+ disabled,
+ testId,
+}: MenuItemProps) {
+ return (
+ <button
+ ref={(el) => {
+ // eslint-disable-next-line no-param-reassign
+ menuItemsRef.current[index] = el;
+ }}
+ type="button"
+ onClick={onClick}
+ onKeyDown={(e) => onKeyDown(e, index)}
+ disabled={disabled}
+ className={cn(
+ "group w-full cursor-pointer rounded px-2 py-2 text-start text-nowrap text-sm font-normal",
+ "text-[var(--oh-foreground)] hover:bg-[var(--oh-interactive-hover)]",
+ "disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent",
+ )}
+ role="menuitem"
+ data-testid={testId}
+ >
+ <ConversationNameContextMenuIconText icon={icon} text={label} />
+ </button>
+ );
+}
+
+interface MetaProfileActionsMenuProps {
+ onEdit: () => void;
+ onSetActive: () => void;
+ onDelete: () => void;
+ isActive: boolean;
+ isActivating: boolean;
+ onClose: () => void;
+ /**
+ * Element the menu should anchor against. When provided, the menu renders
+ * into a portal at the document body using fixed positioning so it cannot be
+ * clipped by ancestors with `overflow: auto/hidden` (e.g. the settings
+ * `<main>` scroll container).
+ */
+ anchorRef?: React.RefObject<HTMLElement | null>;
+}
+
+export function MetaProfileActionsMenu({
+ onEdit,
+ onSetActive,
+ onDelete,
+ isActive,
+ isActivating,
+ onClose,
+ anchorRef,
+}: MetaProfileActionsMenuProps) {
+ const { t } = useTranslation("openhands");
+ const menuRef = useRef<HTMLDivElement>(null);
+ const menuItemsRef = useRef<(HTMLButtonElement | null)[]>([]);
+
+ const anchorElement = anchorRef?.current ?? null;
+ const [portalStyle, setPortalStyle] = useState<React.CSSProperties>();
+
+ useLayoutEffect(() => {
+ if (!anchorElement) return undefined;
+
+ const updatePosition = () => {
+ const rect = anchorElement.getBoundingClientRect();
+ if (!rect) return;
+ const gap = 8;
+ setPortalStyle({
+ position: "fixed",
+ zIndex: 9999,
+ top: rect.bottom + gap,
+ right: window.innerWidth - rect.right,
+ width: "max-content",
+ });
+ };
+
+ updatePosition();
+ window.addEventListener("resize", updatePosition);
+ window.addEventListener("scroll", updatePosition, true);
+ return () => {
+ window.removeEventListener("resize", updatePosition);
+ window.removeEventListener("scroll", updatePosition, true);
+ };
+ }, [anchorElement]);
+
+ // Focus first item when menu opens
+ useEffect(() => {
+ menuItemsRef.current[0]?.focus();
+ }, []);
+
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ const target = event.target as Node;
+ if (menuRef.current && !menuRef.current.contains(target)) {
+ onClose();
+ }
+ };
+
+ const handleEscape = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ onClose();
+ }
+ };
+
+ document.addEventListener("mousedown", handleClickOutside);
+ document.addEventListener("keydown", handleEscape);
+
+ return () => {
+ document.removeEventListener("mousedown", handleClickOutside);
+ document.removeEventListener("keydown", handleEscape);
+ };
+ }, [onClose]);
+
+ const handleAction = (action: () => void) => {
+ action();
+ onClose();
+ };
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent, currentIndex: number) => {
+ if (e.key === "Tab") {
+ onClose();
+ return;
+ }
+ const itemCount = menuItemsRef.current.filter(Boolean).length;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ const nextIndex = (currentIndex + 1) % itemCount;
+ menuItemsRef.current[nextIndex]?.focus();
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ const prevIndex = (currentIndex - 1 + itemCount) % itemCount;
+ menuItemsRef.current[prevIndex]?.focus();
+ }
+ },
+ [onClose],
+ );
+
+ const setActiveDisabled = isActive || isActivating;
+ const isPortaled = Boolean(anchorElement);
+
+ const menu = (
+ <div
+ ref={menuRef}
+ className={cn(
+ "absolute right-0 top-full z-10 mt-2 w-[160px] rounded-md border border-[var(--oh-border-subtle)] bg-tertiary px-1 py-1 shadow-lg",
+ dropdownMenuListClassName,
+ isPortaled &&
+ "!static !top-auto !bottom-auto !left-auto !right-auto !mt-0",
+ )}
+ role="menu"
+ aria-orientation="vertical"
+ data-testid="meta-profile-actions-menu"
+ >
+ <MenuItem
+ index={0}
+ icon={<EditIcon width={16} height={16} />}
+ label={t(I18nKey.BUTTON$EDIT)}
+ onClick={() => handleAction(onEdit)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ testId="meta-profile-edit"
+ />
+ <MenuItem
+ index={1}
+ icon={<CheckCircleIcon width={16} height={16} />}
+ label={t(I18nKey.SETTINGS$META_PROFILE_ACTIVATE)}
+ onClick={() => handleAction(onSetActive)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ disabled={setActiveDisabled}
+ testId="meta-profile-set-active"
+ />
+ <MenuItem
+ index={2}
+ icon={<DeleteIcon width={16} height={16} />}
+ label={t(I18nKey.BUTTON$DELETE)}
+ onClick={() => handleAction(onDelete)}
+ onKeyDown={handleKeyDown}
+ menuItemsRef={menuItemsRef}
+ testId="meta-profile-delete"
+ />
+ </div>
+ );
+
+ if (isPortaled) {
+ if (typeof document === "undefined" || !portalStyle) {
+ return null;
+ }
+ return ReactDOM.createPortal(
+ // portal position computed from DOM bounding rect at runtime
+ <div style={portalStyle}>{menu}</div>,
+ document.body,
+ );
+ }
+
+ return menu;
+}
diff --git a/src/components/features/settings/meta-llm-profiles/meta-profile-editor.tsx b/src/components/features/settings/meta-llm-profiles/meta-profile-editor.tsx
new file mode 100644
index 0000000000..dd582b4b20
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/meta-profile-editor.tsx
@@ -0,0 +1,370 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";
+import { ProfileNameInput } from "#/components/features/settings/llm-profiles/profile-name-input";
+import { ProviderConnectionModal } from "#/components/features/settings/llm-profiles/provider-connection-modal";
+import { Typography } from "#/ui/typography";
+import { isProfileNameValid } from "#/utils/derive-profile-name";
+import { cn } from "#/utils/utils";
+import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";
+import { I18nKey } from "#/i18n/declaration";
+import type { MetaProfile } from "#/api/meta-profiles-service/meta-profiles-service.api";
+import type { ProviderConnection } from "#/api/provider-connections-service/provider-connections-service.api";
+import {
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT,
+ DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME,
+} from "./default-meta-profile";
+
+// Dropdown key that means "don't create any router profiles" (i.e. all the
+// referenced LLM profiles already exist or the user will create them manually).
+const NO_ROUTER_CONNECTION_KEY = "";
+
+interface MetaProfileEditorProps {
+ mode: "create" | "edit";
+ initialName?: string;
+ initialConfig?: MetaProfile;
+ /**
+ * When true (create mode, built-in templates), the first provider connection
+ * is pre-selected so the router's LLM profiles are created on save.
+ */
+ selectRouterConnectionByDefault?: boolean;
+ /**
+ * Provider connections offered for populating the router's LLM profiles.
+ * Empty on cloud / older backends, where the picker is hidden.
+ */
+ providerConnections?: ProviderConnection[];
+ /** Names of saved LLM profiles, offered as dropdown options. */
+ availableProfiles: string[];
+ /**
+ * Names of existing meta-profiles. In create mode a name already present
+ * here is rejected, so "Add" cannot silently overwrite an existing profile
+ * (the backend save contract is create-or-overwrite).
+ */
+ existingNames?: string[];
+ isSaving: boolean;
+ onSave: (
+ name: string,
+ config: MetaProfile,
+ providerConnectionId: string | null,
+ ) => void;
+ onCancel: () => void;
+ onProviderConnectionCreated?: (connection: ProviderConnection) => void;
+}
+
+const EMPTY_CONFIG: MetaProfile = {
+ classifier_model: "",
+ prompt_template: "",
+ model_table: "",
+};
+
+const INSTANCE_TEXT_PLACEHOLDER = /{{\s*instance_text\s*}}/;
+const INSTANCE_TEXT_PLACEHOLDER_TEXT = "{{ instance_text }}";
+const MODEL_TABLE_PLACEHOLDER_TEXT = "{{ model_table }}";
+const PROMPT_TEMPLATE_PLACEHOLDER = `Return JSON with the best model for this task.
+${MODEL_TABLE_PLACEHOLDER_TEXT}
+
+Task:
+${INSTANCE_TEXT_PLACEHOLDER_TEXT}`;
+
+const normalizeConfig = (config?: MetaProfile): MetaProfile => ({
+ classifier_model: config?.classifier_model ?? "",
+ classes: [],
+ prompt_template: config?.prompt_template ?? "",
+ model_table: config?.model_table ?? "",
+});
+
+export function MetaProfileEditor({
+ mode,
+ initialName,
+ initialConfig,
+ selectRouterConnectionByDefault,
+ providerConnections = [],
+ availableProfiles,
+ existingNames = [],
+ isSaving,
+ onSave,
+ onCancel,
+ onProviderConnectionCreated,
+}: MetaProfileEditorProps) {
+ const { t } = useTranslation("openhands");
+ const isEdit = mode === "edit";
+ const startingConfig = normalizeConfig(
+ initialConfig ??
+ (isEdit ? EMPTY_CONFIG : DEFAULT_MAX_SCORE_PARETO_META_PROFILE_DEFAULT),
+ );
+ const [name, setName] = useState(
+ initialName ?? (isEdit ? "" : DEFAULT_MAX_SCORE_PARETO_META_PROFILE_NAME),
+ );
+ const [config, setConfig] = useState<MetaProfile>(() => startingConfig);
+ const [createdProviderConnections, setCreatedProviderConnections] = useState<
+ ProviderConnection[]
+ >([]);
+ const [isProviderConnectionModalOpen, setIsProviderConnectionModalOpen] =
+ useState(false);
+ const connectionOptions = useMemo(() => {
+ const byId = new Map<string, ProviderConnection>();
+ for (const connection of providerConnections)
+ byId.set(connection.id, connection);
+ for (const connection of createdProviderConnections) {
+ byId.set(connection.id, connection);
+ }
+ return [...byId.values()];
+ }, [providerConnections, createdProviderConnections]);
+ const showRouterConnectionPicker = !isEdit;
+ const [routerConnectionId, setRouterConnectionId] = useState(() =>
+ selectRouterConnectionByDefault && providerConnections.length > 0
+ ? providerConnections[0].id
+ : NO_ROUTER_CONNECTION_KEY,
+ );
+
+ useEffect(() => {
+ if (
+ !showRouterConnectionPicker ||
+ routerConnectionId ||
+ !selectRouterConnectionByDefault ||
+ connectionOptions.length === 0
+ ) {
+ return;
+ }
+ setRouterConnectionId(connectionOptions[0].id);
+ }, [
+ connectionOptions,
+ routerConnectionId,
+ selectRouterConnectionByDefault,
+ showRouterConnectionPicker,
+ ]);
+
+ const profileItems = useMemo(
+ () => availableProfiles.map((p) => ({ key: p, label: p })),
+ [availableProfiles],
+ );
+ const routerConnectionItems = useMemo(
+ () => [
+ {
+ key: NO_ROUTER_CONNECTION_KEY,
+ label: t(I18nKey.SETTINGS$META_PROFILE_ROUTER_CONNECTION_NONE),
+ },
+ ...connectionOptions.map((connection) => ({
+ key: connection.id,
+ label: `${connection.display_name} (${connection.provider})`,
+ })),
+ ],
+ [connectionOptions, t],
+ );
+
+ const nameValid = isProfileNameValid(name, { isRequired: true });
+ // In create mode, a name that already exists would overwrite that profile
+ // (the backend save is create-or-overwrite), so reject it here.
+ const isDuplicateName = !isEdit && existingNames.includes(name.trim());
+ const canSave =
+ nameValid &&
+ !isDuplicateName &&
+ config.classifier_model.trim().length > 0 &&
+ INSTANCE_TEXT_PLACEHOLDER.test(config.prompt_template ?? "");
+
+ const handleProviderConnectionSaved = (connection: ProviderConnection) => {
+ setCreatedProviderConnections((existing) => [
+ connection,
+ ...existing.filter((item) => item.id !== connection.id),
+ ]);
+ onProviderConnectionCreated?.(connection);
+ setRouterConnectionId(connection.id);
+ };
+
+ const handleSave = () => {
+ if (!canSave || isSaving) return;
+ onSave(
+ name.trim(),
+ {
+ classifier_model: config.classifier_model.trim(),
+ classes: [],
+ prompt_template: (config.prompt_template ?? "").trim(),
+ model_table: config.model_table?.trim() || null,
+ },
+ showRouterConnectionPicker && routerConnectionId
+ ? routerConnectionId
+ : null,
+ );
+ };
+
+ return (
+ <div className="flex flex-col gap-6" data-testid="meta-profile-editor">
+ <Typography.H3>
+ {t(
+ isEdit
+ ? I18nKey.SETTINGS$EDIT_META_PROFILE
+ : I18nKey.SETTINGS$NEW_META_PROFILE,
+ )}
+ </Typography.H3>
+
+ <div className="flex flex-col gap-1">
+ <ProfileNameInput
+ testId="meta-profile-name-input"
+ value={name}
+ onChange={setName}
+ isDisabled={isEdit || isSaving}
+ isRequired
+ />
+ {isDuplicateName ? (
+ <p
+ data-testid="meta-profile-name-taken"
+ className="text-xs text-red-400"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_NAME_TAKEN)}
+ </p>
+ ) : null}
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <SettingsDropdownInput
+ testId="meta-profile-classifier-input"
+ name="classifier_model"
+ label={t(I18nKey.SETTINGS$META_PROFILE_CLASSIFIER)}
+ items={profileItems}
+ defaultSelectedKey={startingConfig.classifier_model || undefined}
+ allowsCustomValue
+ isDisabled={isSaving}
+ onInputChange={(value) =>
+ setConfig((prev) => ({ ...prev, classifier_model: value }))
+ }
+ onSelectionChange={(key) =>
+ setConfig((prev) => ({
+ ...prev,
+ classifier_model: key ? String(key) : "",
+ }))
+ }
+ />
+ <p className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$META_PROFILE_CLASSIFIER_HELP)}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <label className="flex flex-col gap-2.5">
+ <span className="text-sm">
+ {t(I18nKey.SETTINGS$META_PROFILE_PROMPT_TEMPLATE)}
+ </span>
+ <textarea
+ data-testid="meta-profile-prompt-template"
+ rows={8}
+ spellCheck={false}
+ value={config.prompt_template ?? ""}
+ placeholder={PROMPT_TEMPLATE_PLACEHOLDER}
+ onChange={(event) =>
+ setConfig((prev) => ({
+ ...prev,
+ prompt_template: event.target.value,
+ }))
+ }
+ disabled={isSaving}
+ className={cn(
+ formControlMultilineFieldClassName,
+ "font-mono text-xs",
+ )}
+ />
+ </label>
+ <p className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$META_PROFILE_PROMPT_TEMPLATE_HELP, {
+ instance_text: INSTANCE_TEXT_PLACEHOLDER_TEXT,
+ model_table: MODEL_TABLE_PLACEHOLDER_TEXT,
+ })}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <label className="flex flex-col gap-2.5">
+ <span className="text-sm">
+ {t(I18nKey.SETTINGS$META_PROFILE_MODEL_TABLE)}
+ </span>
+ <textarea
+ data-testid="meta-profile-model-table"
+ rows={5}
+ spellCheck={false}
+ value={config.model_table ?? ""}
+ placeholder={t(
+ I18nKey.SETTINGS$META_PROFILE_MODEL_TABLE_PLACEHOLDER,
+ )}
+ onChange={(event) =>
+ setConfig((prev) => ({
+ ...prev,
+ model_table: event.target.value,
+ }))
+ }
+ disabled={isSaving}
+ className={cn(
+ formControlMultilineFieldClassName,
+ "font-mono text-xs",
+ )}
+ />
+ </label>
+ <p className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$META_PROFILE_MODEL_TABLE_HELP, {
+ model_table: MODEL_TABLE_PLACEHOLDER_TEXT,
+ })}
+ </p>
+ </div>
+
+ {showRouterConnectionPicker ? (
+ <div className="flex flex-col gap-2">
+ <SettingsDropdownInput
+ testId="meta-profile-router-connection"
+ name="router_connection"
+ label={t(I18nKey.SETTINGS$META_PROFILE_CREATE_ROUTER_PROFILES)}
+ items={routerConnectionItems}
+ selectedKey={routerConnectionId}
+ isDisabled={isSaving}
+ onSelectionChange={(key) =>
+ setRouterConnectionId(
+ key ? String(key) : NO_ROUTER_CONNECTION_KEY,
+ )
+ }
+ />
+ <div className="flex flex-wrap items-center gap-3">
+ <p className="text-xs text-[var(--oh-muted)]">
+ {t(I18nKey.SETTINGS$META_PROFILE_CREATE_ROUTER_PROFILES_HELP)}
+ </p>
+ <BrandButton
+ testId="meta-profile-add-provider-connection"
+ type="button"
+ variant="secondary"
+ onClick={() => setIsProviderConnectionModalOpen(true)}
+ isDisabled={isSaving}
+ >
+ {t(I18nKey.SETTINGS$PROVIDER_CONNECTION_ADD)}
+ </BrandButton>
+ </div>
+ </div>
+ ) : null}
+
+ {isProviderConnectionModalOpen ? (
+ <ProviderConnectionModal
+ isCreate
+ onClose={() => setIsProviderConnectionModalOpen(false)}
+ onSaved={handleProviderConnectionSaved}
+ />
+ ) : null}
+
+ <div className="flex items-center gap-3">
+ <BrandButton
+ testId="meta-profile-save"
+ type="button"
+ variant="primary"
+ onClick={handleSave}
+ isDisabled={!canSave || isSaving}
+ >
+ {t(I18nKey.BUTTON$SAVE)}
+ </BrandButton>
+ <BrandButton
+ testId="meta-profile-cancel"
+ type="button"
+ variant="tertiary"
+ onClick={onCancel}
+ isDisabled={isSaving}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx b/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx
new file mode 100644
index 0000000000..adf94213af
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/meta-profile-row.tsx
@@ -0,0 +1,91 @@
+import { useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { MetaProfileActionsMenu } from "./meta-profile-actions-menu";
+import { MetaProfileInfo } from "#/api/meta-profiles-service/meta-profiles-service.api";
+import { I18nKey } from "#/i18n/declaration";
+import { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";
+import { BrandBadge } from "#/components/shared/badge";
+import { cn } from "#/utils/utils";
+import {
+ settingsListIconActionButtonClassName,
+ settingsListRowClassName,
+} from "#/utils/settings-list-classes";
+
+interface MetaProfileRowProps {
+ info: MetaProfileInfo;
+ isActive: boolean;
+ onActivate: (name: string) => void;
+ onEdit: (name: string) => void;
+ onDelete: (name: string) => void;
+ isActivating: boolean;
+}
+
+export function MetaProfileRow({
+ info,
+ isActive,
+ onActivate,
+ onEdit,
+ onDelete,
+ isActivating,
+}: MetaProfileRowProps) {
+ const { t } = useTranslation("openhands");
+ const [menuOpen, setMenuOpen] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const route = info.classifier_model ? String(info.classifier_model) : "";
+ const mode =
+ info.num_classes > 0
+ ? `${info.num_classes} ${t(I18nKey.SETTINGS$META_PROFILE_CLASSES)}`
+ : t(I18nKey.SETTINGS$META_PROFILE_DIRECT_PROMPT);
+ const summary = `${route}${route ? " · " : ""}${mode}`;
+
+ return (
+ <div
+ data-testid={`meta-profile-row-${info.name}`}
+ className={cn(settingsListRowClassName, "justify-between gap-3")}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <span
+ className="min-w-0 max-w-full truncate text-sm font-medium text-white"
+ title={info.name}
+ >
+ {info.name}
+ </span>
+ <span
+ className="min-w-0 max-w-full truncate text-sm text-[var(--oh-muted)]"
+ title={summary}
+ >
+ {summary}
+ </span>
+ {isActive && (
+ <BrandBadge
+ className="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs"
+ data-testid="meta-profile-active-badge"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_ACTIVE)}
+ </BrandBadge>
+ )}
+ </div>
+ <div className="relative shrink-0">
+ <EllipsisButton
+ ref={triggerRef}
+ onClick={() => setMenuOpen((open) => !open)}
+ ariaLabel={t(I18nKey.SETTINGS$PROFILE_MENU)}
+ testId={`meta-profile-menu-trigger-${info.name}`}
+ className={settingsListIconActionButtonClassName}
+ />
+ {menuOpen && (
+ <MetaProfileActionsMenu
+ anchorRef={triggerRef}
+ onEdit={() => onEdit(info.name)}
+ onSetActive={() => onActivate(info.name)}
+ onDelete={() => onDelete(info.name)}
+ isActive={isActive}
+ isActivating={isActivating}
+ onClose={() => setMenuOpen(false)}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/settings/meta-llm-profiles/router-profiles.ts b/src/components/features/settings/meta-llm-profiles/router-profiles.ts
new file mode 100644
index 0000000000..775cb0044b
--- /dev/null
+++ b/src/components/features/settings/meta-llm-profiles/router-profiles.ts
@@ -0,0 +1,67 @@
+/**
+ * Helpers for creating the LLM profiles a meta-profile (model router) needs.
+ *
+ * A router's ``model_table`` lists the models the classifier may pick from, one
+ * per line as ``- <name> <description...>``. The router matches the classifier's
+ * answer against saved LLM *profile names*, so each ``<name>`` must exist as a
+ * profile. We create the missing ones by pairing the name with a chosen provider
+ * connection: the endpoint is derived by convention as
+ * ``<provider>.toLowerCase()/<name>`` and the profile links the connection for
+ * its credentials instead of cloning them.
+ */
+
+/**
+ * Extract model names from a router ``model_table``.
+ *
+ * Each row looks like ``- <name> <anything else>`` (the trailing text is human
+ * description we ignore). A ``:`` directly after the name (``- <name>: stats``)
+ * is also stripped. Blank lines and non-list lines are skipped, and names are
+ * de-duplicated while preserving first-seen order.
+ */
+export function parseModelTableNames(
+ modelTable: string | null | undefined,
+): string[] {
+ if (!modelTable) return [];
+ const names: string[] = [];
+ const seen = new Set<string>();
+ for (const line of modelTable.split("\n")) {
+ const match = line.match(/^\s*-\s+(\S+)/);
+ if (!match) continue;
+ const name = match[1].replace(/:+$/, "");
+ const key = name.toLowerCase();
+ if (!name || seen.has(key)) continue;
+ seen.add(key);
+ names.push(name);
+ }
+ return names;
+}
+
+/**
+ * Derive the LLM endpoint for a router model under a provider connection.
+ *
+ * Convention (intentionally simple so this can ship; extend per-provider in a
+ * later PR if needed): ``<provider>.toLowerCase()/<name>``. This holds for
+ * openhands, anthropic, gemini, openai and similar litellm providers.
+ */
+export function buildRouterModel(provider: string, name: string): string {
+ return `${provider.toLowerCase()}/${name}`;
+}
+
+/**
+ * The set of profile names a router config depends on: every model in the
+ * table plus the classifier model. De-duplicated, first-seen order, table
+ * names first.
+ */
+export function collectRequiredRouterModelNames(config: {
+ classifier_model?: string | null;
+ model_table?: string | null;
+}): string[] {
+ const names = parseModelTableNames(config.model_table);
+ const seen = new Set(names.map((name) => name.toLowerCase()));
+ const extra = (config.classifier_model ?? "").trim();
+ if (extra && !seen.has(extra.toLowerCase())) {
+ seen.add(extra.toLowerCase());
+ names.push(extra);
+ }
+ return names;
+}
diff --git a/src/constants/settings-nav.tsx b/src/constants/settings-nav.tsx
index 9d7d800c9a..1e82cad8b2 100644
--- a/src/constants/settings-nav.tsx
+++ b/src/constants/settings-nav.tsx
@@ -1,4 +1,4 @@
-import { AppWindow, Brain, Shield } from "lucide-react";
+import { AppWindow, Brain, Route as RouteIcon, Shield } from "lucide-react";
import KeyIcon from "#/icons/key.svg?react";
import MemoryIcon from "#/icons/memory_icon.svg?react";
import CircuitIcon from "#/icons/u-circuit.svg?react";
@@ -29,6 +29,12 @@ export const OSS_NAV_ITEMS: SettingsNavItem[] = [
text: "SETTINGS$NAV_LLM",
subtitle: "SETTINGS$PAGE_LLM_SUBLINE",
},
+ {
+ icon: <RouteIcon className="size-4" strokeWidth={2} aria-hidden />,
+ to: "/settings/meta-llm",
+ text: "SETTINGS$NAV_META_LLM",
+ subtitle: "SETTINGS$PAGE_META_LLM_SUBLINE",
+ },
{
icon: <MemoryIcon width={16} height={16} />,
to: "/settings/condenser",
@@ -68,10 +74,11 @@ export const OSS_NAV_ITEMS: SettingsNavItem[] = [
];
/**
- * The only OSS nav entry listed when the canvas is locked to a Cloud host —
- * i.e. deployed into SaaS / self-hosted OHE next to the OHE web app, whose own
- * settings shell (reached via "All Cloud Settings") owns everything else. The
- * other pages stay routable for in-app deep links; they are just unlisted
- * (OHE-3168).
+ * Default page for locked-to-Cloud deployments. The full Canvas settings nav
+ * remains available; "All Cloud Settings" links out to the Cloud settings shell
+ * for pages Canvas does not own directly.
*/
export const LOCKED_CLOUD_SETTINGS_NAV_PATH = "/settings/app";
+export const LOCKED_CLOUD_SETTINGS_NAV_PATHS = new Set(
+ OSS_NAV_ITEMS.map((item) => item.to),
+);
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index c1057b09bd..c5ec28b045 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -37,6 +37,7 @@ import {
isBrowserObservationEvent,
isBrowserNavigateActionEvent,
isSwitchLLMObservationEvent,
+ isClassifyAndSwitchLLMObservationEvent,
isCanvasUIActionEvent,
isStreamingDeltaEvent,
isLaunchChildConversationActionEvent,
@@ -576,6 +577,8 @@ export function ConversationWebSocketProvider({
const switchLLMObservation = isSwitchLLMObservationEvent(event)
? event
: null;
+ const classifyAndSwitchLLMObservation =
+ isClassifyAndSwitchLLMObservationEvent(event) ? event : null;
addEvent(event);
if (isDuplicateEvent) {
return;
@@ -734,6 +737,42 @@ export function ConversationWebSocketProvider({
invalidateConversationQueries(queryClient, conversationId);
}
+ // Router-driven model switch (Pareto/meta-profile classifier).
+ // Same UI semantics as SwitchLLMObservation: update the combobox,
+ // stamp the active profile, record the inline "Switched to"
+ // message. Per the SDK wire contract, `model` is the saved LLM
+ // profile name that was activated and `active_model` is the
+ // underlying model string — so the profile stamp and inline
+ // message use `model` (mirroring SwitchLLMObservation.profile_name),
+ // while the combobox cache update uses `active_model`.
+ if (
+ conversationId &&
+ classifyAndSwitchLLMObservation &&
+ !classifyAndSwitchLLMObservation.observation.is_error &&
+ classifyAndSwitchLLMObservation.observation.model
+ ) {
+ const profileName =
+ classifyAndSwitchLLMObservation.observation.model;
+
+ recordModelSwitchMessage(conversationId, profileName);
+
+ stampActiveLlmProfile(
+ conversationId,
+ profileName,
+ classifyAndSwitchLLMObservation.timestamp,
+ );
+
+ if (classifyAndSwitchLLMObservation.observation.active_model) {
+ updateConversationLlmModelInCache(
+ queryClient,
+ conversationId,
+ classifyAndSwitchLLMObservation.observation.active_model,
+ );
+ }
+
+ invalidateConversationQueries(queryClient, conversationId);
+ }
+
// Handle canvas_ui ActionEvents from both the legacy Python tool and
// the client-defined JSON tool. The server acknowledges immediately;
// the actual UI change happens here on the client.
diff --git a/src/hooks/chat/record-model-switch-message.test.ts b/src/hooks/chat/record-model-switch-message.test.ts
index c53f487d53..1258808873 100644
--- a/src/hooks/chat/record-model-switch-message.test.ts
+++ b/src/hooks/chat/record-model-switch-message.test.ts
@@ -36,6 +36,31 @@ const switchObservation = (
},
}) as unknown as OpenHandsEvent;
+// Router-driven switch. Per the SDK wire contract, `model` is the activated
+// saved profile name and `active_model` is the underlying model string — the
+// seed must stamp/profile off `model`, not `active_model`.
+const classifySwitchObservation = (
+ id: string,
+ profileName: string,
+ activeModel = "openhands/kimi-k2.6",
+ isError = false,
+ timestamp = "2024-01-01T00:00:00Z",
+): OpenHandsEvent =>
+ ({
+ id,
+ timestamp,
+ source: "environment",
+ action_id: `action-${id}`,
+ observation: {
+ kind: "ClassifyAndSwitchLLMObservation",
+ content: [],
+ is_error: isError,
+ chosen_class: `model: ${profileName}`,
+ model: profileName,
+ active_model: activeModel,
+ },
+ }) as unknown as OpenHandsEvent;
+
// An agent action event. `ThinkAction` is renderable (shown as a thinking
// block); `PlanningFileEditorAction` is hidden by `shouldRenderEvent`.
const agentAction = (id: string, kind: string): OpenHandsEvent =>
@@ -329,4 +354,50 @@ describe("seedModelSwitchesFromHistory", () => {
"2024-01-01T00:00:00Z",
);
});
+
+ describe("router-driven ClassifyAndSwitchLLMObservation", () => {
+ it("records the inline switch and stamps the profile from `model`, not `active_model`", () => {
+ // `active_model` is the underlying model string ("openhands/kimi-k2.6");
+ // the stamp and inline message must use the saved profile name in `model`.
+ seedModelSwitchesFromHistory("c1", [
+ userMessage("u1"),
+ classifySwitchObservation("o1", "kimi-k2.6", "openhands/kimi-k2.6"),
+ ]);
+
+ const entries = entriesFor("c1");
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({
+ switchedTo: "kimi-k2.6",
+ anchorEventId: "u1",
+ });
+ expect(activeProfileFor("c1")).toBe("kimi-k2.6");
+ expect(stampedProfileFor("c1")).toBe("kimi-k2.6");
+ });
+
+ it("ignores a router switch that has no `model` even if `active_model` is present", () => {
+ seedModelSwitchesFromHistory("c1", [
+ userMessage("u1"),
+ classifySwitchObservation("o1", "", "openhands/kimi-k2.6"),
+ ]);
+
+ expect(entriesFor("c1")).toHaveLength(0);
+ expect(activeProfileFor("c1")).toBeUndefined();
+ expect(stampedProfileFor("c1")).toBeUndefined();
+ });
+
+ it("does not stamp from a failed router switch", () => {
+ seedModelSwitchesFromHistory("c1", [
+ userMessage("u1"),
+ classifySwitchObservation(
+ "e1",
+ "kimi-k2.6",
+ "openhands/kimi-k2.6",
+ true,
+ ),
+ ]);
+
+ expect(activeProfileFor("c1")).toBeUndefined();
+ expect(stampedProfileFor("c1")).toBeUndefined();
+ });
+ });
});
diff --git a/src/hooks/chat/record-model-switch-message.ts b/src/hooks/chat/record-model-switch-message.ts
index dce835c134..f5296d892c 100644
--- a/src/hooks/chat/record-model-switch-message.ts
+++ b/src/hooks/chat/record-model-switch-message.ts
@@ -5,7 +5,10 @@ import {
mergeStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
import { OpenHandsEvent } from "#/types/agent-server/core";
-import { isSwitchLLMObservationEvent } from "#/types/agent-server/type-guards";
+import {
+ isClassifyAndSwitchLLMObservationEvent,
+ isSwitchLLMObservationEvent,
+} from "#/types/agent-server/type-guards";
import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
export function recordModelSwitchMessage(
@@ -107,6 +110,26 @@ export function seedModelSwitchesFromHistory(
profileName: event.observation.profile_name,
timestamp: event.timestamp,
};
+ } else if (
+ isClassifyAndSwitchLLMObservationEvent(event) &&
+ !event.observation.is_error &&
+ event.observation.model
+ ) {
+ // Router-driven switch: the matched LLM profile name is the
+ // observation's `model` (the SDK matched classifier output against
+ // saved profile names case-insensitively and stamped the profile name
+ // there; `active_model` is the underlying model string, not the
+ // profile name).
+ const profileName = event.observation.model;
+ switches.push({
+ id: `history-classify-switch:${event.id}`,
+ anchorEventId: lastRenderableId,
+ profileName,
+ });
+ latestSwitch = {
+ profileName,
+ timestamp: event.timestamp,
+ };
}
if (shouldRenderEvent(event)) {
lastRenderableId = String(event.id);
diff --git a/src/hooks/mutation/use-activate-meta-profile.ts b/src/hooks/mutation/use-activate-meta-profile.ts
new file mode 100644
index 0000000000..2b02097d09
--- /dev/null
+++ b/src/hooks/mutation/use-activate-meta-profile.ts
@@ -0,0 +1,29 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import {
+ META_PROFILES_QUERY_KEYS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+
+export function useActivateMetaProfile() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (name: string) => MetaProfilesService.activateMetaProfile(name),
+ onSuccess: async () => {
+ // Activating a meta-profile sets ``active_meta_profile`` in settings,
+ // which controls whether the route_task_to_model tool is attached to
+ // new conversations — so refresh the settings caches too.
+ SettingsService.invalidateCache();
+ await queryClient.invalidateQueries({
+ queryKey: META_PROFILES_QUERY_KEYS.all,
+ });
+ await queryClient.invalidateQueries({
+ queryKey: SETTINGS_QUERY_KEYS.personal(),
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts; disable global toast
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/mutation/use-delete-meta-profile.ts b/src/hooks/mutation/use-delete-meta-profile.ts
new file mode 100644
index 0000000000..709d307d01
--- /dev/null
+++ b/src/hooks/mutation/use-delete-meta-profile.ts
@@ -0,0 +1,30 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import {
+ META_PROFILES_QUERY_KEYS,
+ SETTINGS_QUERY_KEYS,
+} from "#/hooks/query/query-keys";
+
+export function useDeleteMetaProfile() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: (name: string) => MetaProfilesService.deleteMetaProfile(name),
+ onSuccess: async () => {
+ // Deleting the *active* meta-profile clears ``active_meta_profile`` in
+ // settings (and detaches the route_task_to_model tool from new
+ // conversations), so refresh the settings caches too — mirroring
+ // activation. Without this, settings can stay stale until reload.
+ SettingsService.invalidateCache();
+ await queryClient.invalidateQueries({
+ queryKey: META_PROFILES_QUERY_KEYS.all,
+ });
+ await queryClient.invalidateQueries({
+ queryKey: SETTINGS_QUERY_KEYS.personal(),
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts; disable global toast
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/mutation/use-save-meta-profile.ts b/src/hooks/mutation/use-save-meta-profile.ts
new file mode 100644
index 0000000000..d4fdfa2847
--- /dev/null
+++ b/src/hooks/mutation/use-save-meta-profile.ts
@@ -0,0 +1,26 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import MetaProfilesService, {
+ type MetaProfile,
+} from "#/api/meta-profiles-service/meta-profiles-service.api";
+import { META_PROFILES_QUERY_KEYS } from "#/hooks/query/query-keys";
+
+interface SaveMetaProfileVariables {
+ name: string;
+ config: MetaProfile;
+}
+
+export function useSaveMetaProfile() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ name, config }: SaveMetaProfileVariables) =>
+ MetaProfilesService.saveMetaProfile(name, config),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: META_PROFILES_QUERY_KEYS.all,
+ });
+ },
+ // Consumers handle errors with try-catch and manual toasts; disable global toast
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index eb2c56033f..6ddba7e78e 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -22,6 +22,10 @@ export const LLM_PROFILES_QUERY_KEYS = {
all: ["llm-profiles"] as const,
} as const;
+export const META_PROFILES_QUERY_KEYS = {
+ all: ["meta-profiles"] as const,
+} as const;
+
export const AGENT_PROFILES_QUERY_KEYS = {
all: ["agent-profiles"] as const,
// Nested under `all` so profile mutations invalidate cached details too.
diff --git a/src/hooks/query/use-conversation-metrics.ts b/src/hooks/query/use-conversation-metrics.ts
index 351907368f..0b3850addf 100644
--- a/src/hooks/query/use-conversation-metrics.ts
+++ b/src/hooks/query/use-conversation-metrics.ts
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import { getCombinedMetrics } from "#/utils/conversation-metrics";
import type { MetricsSnapshot } from "#/api/conversation-service/agent-server-conversation-service.types";
@@ -13,6 +14,10 @@ export const useConversationMetrics = (
isLoading: boolean;
error: unknown;
} => {
+ const { backend } = useActiveBackend();
+ const runtimeEndpointReady =
+ backend.kind !== "cloud" || Boolean(conversationUrl);
+
const query = useQuery({
queryKey: [
"conversation-metrics",
@@ -32,9 +37,11 @@ export const useConversationMetrics = (
},
// conversation_url is only set for cloud conversations; local ones are
// served by the ConversationClient fallback in getRuntimeConversation.
- // Gating on it left local conversations with no REST snapshot at all
- // (zeros after a page reload until live WS metrics arrived).
- enabled: enabled && !!conversationId,
+ // Gating local on it left local conversations with no REST snapshot at all
+ // (zeros after a page reload until live WS metrics arrived). Cloud must
+ // wait for the per-conversation runtime URL; otherwise the typed client has
+ // no local backend to fall back to and throws "No backend is configured".
+ enabled: enabled && !!conversationId && runtimeEndpointReady,
staleTime: 1000 * 30,
gcTime: 1000 * 60 * 5,
refetchInterval: 1000 * 30,
diff --git a/src/hooks/query/use-meta-profiles.ts b/src/hooks/query/use-meta-profiles.ts
new file mode 100644
index 0000000000..2513a7c238
--- /dev/null
+++ b/src/hooks/query/use-meta-profiles.ts
@@ -0,0 +1,23 @@
+import { useQuery } from "@tanstack/react-query";
+import MetaProfilesService from "#/api/meta-profiles-service/meta-profiles-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { CONFIG_CACHE_OPTIONS, META_PROFILES_QUERY_KEYS } from "./query-keys";
+
+export { META_PROFILES_QUERY_KEYS };
+
+interface UseMetaProfilesOptions {
+ enabled?: boolean;
+}
+
+export function useMetaProfiles(options: UseMetaProfilesOptions = {}) {
+ const { backend, orgId } = useActiveBackend();
+
+ return useQuery({
+ // Include backend identity to prevent cache pollution when switching backends
+ queryKey: [...META_PROFILES_QUERY_KEYS.all, backend.id, orgId],
+ queryFn: MetaProfilesService.listMetaProfiles,
+ ...CONFIG_CACHE_OPTIONS,
+ enabled: options.enabled ?? true,
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/use-llm-configured.test.tsx b/src/hooks/use-llm-configured.test.tsx
index c4ae6b0aa1..7162c0e206 100644
--- a/src/hooks/use-llm-configured.test.tsx
+++ b/src/hooks/use-llm-configured.test.tsx
@@ -173,4 +173,43 @@ describe("useLlmConfigured", () => {
// Detail is fetched because the profile is local + active + key-less.
expect(mockGetProfile).toHaveBeenCalledWith("gpt-5.5");
});
+
+ it("treats a keyed active cloud LLM profile as configured without settings key", async () => {
+ const cloudBackend: Backend = {
+ id: "test-cloud",
+ name: "Test Cloud",
+ host: "https://app.example.com",
+ apiKey: "cloud-token",
+ kind: "cloud",
+ };
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ mockGetSettings.mockResolvedValue({
+ ...DEFAULT_SETTINGS,
+ llm_api_key_set: false,
+ agent_settings: {
+ ...(DEFAULT_SETTINGS.agent_settings ?? {}),
+ agent_kind: "openhands",
+ },
+ });
+ mockListProfiles.mockResolvedValue({
+ active_profile: "GPT-5.4",
+ profiles: [
+ {
+ name: "GPT-5.4",
+ model: "openhands/GPT-5.4",
+ base_url: null,
+ api_key_set: true,
+ provider_connection_id: "conn-openhands",
+ },
+ ],
+ });
+
+ const { result } = renderLlmConfiguredHook();
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.isConfigured).toBe(true);
+ expect(mockGetProfile).not.toHaveBeenCalled();
+ });
});
diff --git a/src/hooks/use-llm-configured.ts b/src/hooks/use-llm-configured.ts
index 8ce0145777..6a0346217a 100644
--- a/src/hooks/use-llm-configured.ts
+++ b/src/hooks/use-llm-configured.ts
@@ -129,16 +129,14 @@ export function useLlmConfigured(): LlmConfiguredResult {
config?.feature_flags,
);
- // In local mode, profiles are the source of truth: a usable LLM must be
- // backed by an active profile that still exists and is authenticated. API-key
- // profiles use the list endpoint's api_key_set flag; subscription profiles
- // intentionally have no key, so we inspect the active profile detail config.
- // The raw settings key can be a stale copy left behind by a deleted profile
- // (settings are not cleared on delete), so we don't count it here. Cloud
- // backends don't use profiles and keep the settings-key signal.
+ // Profiles are the source of truth on local. Cloud still accepts the legacy
+ // settings-key signal, but provider-backed org profiles can be usable even
+ // when settings.llm_api_key_set is false.
const hasUsableActiveProfile =
hasActiveProfileApiKey || hasActiveProfileSubscription;
- const hasUsableLlm = isLocal ? hasUsableActiveProfile : hasApiKey;
+ const hasUsableLlm = isLocal
+ ? hasUsableActiveProfile
+ : hasApiKey || hasUsableActiveProfile;
// Treat a fetch failure as indeterminate (same as loading) only when it
// leaves us with no data to decide from — otherwise a transient network
diff --git a/src/hooks/use-settings-nav-items.ts b/src/hooks/use-settings-nav-items.ts
index ce863ba439..cdb266bb74 100644
--- a/src/hooks/use-settings-nav-items.ts
+++ b/src/hooks/use-settings-nav-items.ts
@@ -1,6 +1,6 @@
import { useConfig } from "#/hooks/query/use-config";
import {
- LOCKED_CLOUD_SETTINGS_NAV_PATH,
+ LOCKED_CLOUD_SETTINGS_NAV_PATHS,
OSS_NAV_ITEMS,
SettingsNavItem,
} from "#/constants/settings-nav";
@@ -21,14 +21,14 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] {
const { data: config } = useConfig();
const { backend } = useActiveBackend();
const featureFlags = config?.feature_flags;
- // Locked-to-Cloud (SaaS / self-hosted OHE) lists only the Application page;
- // the OHE settings shell behind "All Cloud Settings" owns the rest (OHE-3168).
+ // Locked-to-Cloud still lists the full Canvas settings nav; the Cloud shell
+ // remains available through "All Cloud Settings" for Cloud-owned pages.
const isLockedToCloud = getLockedCloudHost() !== null;
return OSS_NAV_ITEMS.filter(
(item) =>
!isSettingsPageHidden(item.to, featureFlags) &&
- (!isLockedToCloud || item.to === LOCKED_CLOUD_SETTINGS_NAV_PATH),
+ (!isLockedToCloud || LOCKED_CLOUD_SETTINGS_NAV_PATHS.has(item.to)),
).map((item) => {
const renamedItem =
item.to === "/settings"
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 381b206e5e..9ad333c8cb 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -5473,6 +5473,720 @@
"uk": "LLM",
"ca": "LLM"
},
+ "SETTINGS$NAV_META_LLM": {
+ "en": "Model Router",
+ "ja": "モデルルーター",
+ "zh-CN": "模型路由器",
+ "zh-TW": "模型路由器",
+ "ko-KR": "모델 라우터",
+ "no": "Modellruter",
+ "it": "Router dei modelli",
+ "pt": "Roteador de modelos",
+ "es": "Enrutador de modelos",
+ "ar": "موجّه النماذج",
+ "fr": "Routeur de modèles",
+ "tr": "Model yönlendirici",
+ "de": "Modell-Router",
+ "uk": "Маршрутизатор моделей",
+ "ca": "Encaminador de models"
+ },
+ "SETTINGS$PAGE_META_LLM_SUBLINE": {
+ "en": "Meta-profiles that route each task to the right LLM profile.",
+ "ja": "各タスクを適切な LLM プロファイルへ振り分けるメタプロファイルです。",
+ "zh-CN": "将每个任务路由到合适 LLM 配置文件的元配置文件。",
+ "zh-TW": "將每個任務路由到合適 LLM 設定檔的中繼設定檔。",
+ "ko-KR": "각 작업을 적절한 LLM 프로필로 라우팅하는 메타 프로필입니다.",
+ "no": "Metaprofiler som sender hver oppgave til riktig LLM-profil.",
+ "it": "Meta-profili che instradano ogni attività al profilo LLM corretto.",
+ "pt": "Meta-perfis que encaminham cada tarefa para o perfil de LLM correto.",
+ "es": "Metaperfiles que enrutan cada tarea al perfil de LLM correcto.",
+ "ar": "ملفات تعريف وصفية توجه كل مهمة إلى ملف LLM المناسب.",
+ "fr": "Méta-profils qui orientent chaque tâche vers le bon profil LLM.",
+ "tr": "Her görevi doğru LLM profiline yönlendiren meta profiller.",
+ "de": "Metaprofile, die jede Aufgabe an das passende LLM-Profil leiten.",
+ "uk": "Метапрофілі, які спрямовують кожне завдання до правильного профілю LLM.",
+ "ca": "Metaperfils que encaminen cada tasca al perfil LLM adequat."
+ },
+ "SETTINGS$META_PROFILES_AVAILABLE": {
+ "en": "Available meta-profiles",
+ "ja": "利用可能なメタプロファイル",
+ "zh-CN": "可用的元配置文件",
+ "zh-TW": "可用的中繼設定檔",
+ "ko-KR": "사용 가능한 메타 프로필",
+ "no": "Tilgjengelige metaprofiler",
+ "it": "Meta-profili disponibili",
+ "pt": "Meta-perfis disponíveis",
+ "es": "Metaperfiles disponibles",
+ "ar": "ملفات التعريف الوصفية المتاحة",
+ "fr": "Méta-profils disponibles",
+ "tr": "Kullanılabilir meta profiller",
+ "de": "Verfügbare Metaprofile",
+ "uk": "Доступні метапрофілі",
+ "ca": "Metaperfils disponibles"
+ },
+ "SETTINGS$ADD_META_PROFILE": {
+ "en": "Add Model Router",
+ "ja": "メタプロファイルを追加",
+ "zh-CN": "添加元配置文件",
+ "zh-TW": "新增中繼設定檔",
+ "ko-KR": "메타 프로필 추가",
+ "no": "Legg til metaprofil",
+ "it": "Aggiungi meta-profilo",
+ "pt": "Adicionar meta-perfil",
+ "es": "Añadir metaperfil",
+ "ar": "إضافة ملف تعريف وصفي",
+ "fr": "Ajouter un méta-profil",
+ "tr": "Meta profil ekle",
+ "de": "Metaprofil hinzufügen",
+ "uk": "Додати метапрофіль",
+ "ca": "Afegeix un metaperfil"
+ },
+ "SETTINGS$META_PROFILE_TEMPLATE_TITLE": {
+ "en": "Choose Model Router template",
+ "ja": "モデルルーターテンプレートを選択",
+ "zh-CN": "选择模型路由器模板",
+ "zh-TW": "選擇模型路由器範本",
+ "ko-KR": "모델 라우터 템플릿 선택",
+ "no": "Velg modellrutermal",
+ "it": "Scegli un modello di router",
+ "pt": "Escolher modelo de roteador",
+ "es": "Elegir plantilla de enrutador",
+ "ar": "اختر قالب موجّه النماذج",
+ "fr": "Choisir un modèle de routeur",
+ "tr": "Model yönlendirici şablonu seç",
+ "de": "Modellrouter-Vorlage auswählen",
+ "uk": "Виберіть шаблон маршрутизатора моделей",
+ "ca": "Tria una plantilla d'encaminador de models"
+ },
+ "SETTINGS$META_PROFILE_TEMPLATE_MAX_SCORE": {
+ "en": "Add Default Pareto Max Score",
+ "ja": "デフォルト Pareto 最大スコアを追加",
+ "zh-CN": "添加默认 Pareto 最高分",
+ "zh-TW": "新增預設 Pareto 最高分",
+ "ko-KR": "기본 Pareto 최대 점수 추가",
+ "no": "Legg til standard Pareto maks poengsum",
+ "it": "Aggiungi Pareto predefinito a punteggio massimo",
+ "pt": "Adicionar Pareto padrão de pontuação máxima",
+ "es": "Añadir Pareto predeterminado de puntuación máxima",
+ "ar": "إضافة Pareto افتراضي بأعلى نتيجة",
+ "fr": "Ajouter le Pareto par défaut à score maximal",
+ "tr": "Varsayılan en yüksek puanlı Pareto ekle",
+ "de": "Standard-Pareto mit maximaler Punktzahl hinzufügen",
+ "uk": "Додати типовий Pareto з максимальною оцінкою",
+ "ca": "Afegeix Pareto predeterminat de puntuació màxima"
+ },
+ "SETTINGS$META_PROFILE_TEMPLATE_MIN_COST": {
+ "en": "Add Default Pareto Min Cost",
+ "ja": "デフォルト Pareto 最小コストを追加",
+ "zh-CN": "添加默认 Pareto 最低成本",
+ "zh-TW": "新增預設 Pareto 最低成本",
+ "ko-KR": "기본 Pareto 최소 비용 추가",
+ "no": "Legg til standard Pareto min kostnad",
+ "it": "Aggiungi Pareto predefinito a costo minimo",
+ "pt": "Adicionar Pareto padrão de custo mínimo",
+ "es": "Añadir Pareto predeterminado de costo mínimo",
+ "ar": "إضافة Pareto افتراضي بأقل تكلفة",
+ "fr": "Ajouter le Pareto par défaut à coût minimal",
+ "tr": "Varsayılan en düşük maliyetli Pareto ekle",
+ "de": "Standard-Pareto mit minimalen Kosten hinzufügen",
+ "uk": "Додати типовий Pareto з мінімальною вартістю",
+ "ca": "Afegeix Pareto predeterminat de cost mínim"
+ },
+ "SETTINGS$META_PROFILE_TEMPLATE_CUSTOM": {
+ "en": "Custom",
+ "ja": "カスタム",
+ "zh-CN": "自定义",
+ "zh-TW": "自訂",
+ "ko-KR": "사용자 지정",
+ "no": "Egendefinert",
+ "it": "Personalizzato",
+ "pt": "Personalizado",
+ "es": "Personalizado",
+ "ar": "مخصص",
+ "fr": "Personnalisé",
+ "tr": "Özel",
+ "de": "Benutzerdefiniert",
+ "uk": "Власний",
+ "ca": "Personalitzat"
+ },
+ "SETTINGS$NEW_META_PROFILE": {
+ "en": "New meta-profile",
+ "ja": "新しいメタプロファイル",
+ "zh-CN": "新元配置文件",
+ "zh-TW": "新增中繼設定檔",
+ "ko-KR": "새 메타 프로필",
+ "no": "Ny metaprofil",
+ "it": "Nuovo meta-profilo",
+ "pt": "Novo meta-perfil",
+ "es": "Nuevo metaperfil",
+ "ar": "ملف تعريف وصفي جديد",
+ "fr": "Nouveau méta-profil",
+ "tr": "Yeni meta profil",
+ "de": "Neues Metaprofil",
+ "uk": "Новий метапрофіль",
+ "ca": "Metaperfil nou"
+ },
+ "SETTINGS$EDIT_META_PROFILE": {
+ "en": "Edit meta-profile",
+ "ja": "メタプロファイルを編集",
+ "zh-CN": "编辑元配置文件",
+ "zh-TW": "編輯中繼設定檔",
+ "ko-KR": "메타 프로필 편집",
+ "no": "Rediger metaprofil",
+ "it": "Modifica meta-profilo",
+ "pt": "Editar meta-perfil",
+ "es": "Editar metaperfil",
+ "ar": "تعديل ملف التعريف الوصفي",
+ "fr": "Modifier le méta-profil",
+ "tr": "Meta profili düzenle",
+ "de": "Metaprofil bearbeiten",
+ "uk": "Редагувати метапрофіль",
+ "ca": "Edita el metaperfil"
+ },
+ "SETTINGS$META_PROFILE_CLASSIFIER": {
+ "en": "Classifier model",
+ "ja": "分類モデル",
+ "zh-CN": "分类器模型",
+ "zh-TW": "分類器模型",
+ "ko-KR": "분류 모델",
+ "no": "Klassifiseringsmodell",
+ "it": "Modello classificatore",
+ "pt": "Modelo classificador",
+ "es": "Modelo clasificador",
+ "ar": "نموذج التصنيف",
+ "fr": "Modèle de classification",
+ "tr": "Sınıflandırıcı model",
+ "de": "Klassifizierungsmodell",
+ "uk": "Модель класифікатора",
+ "ca": "Model classificador"
+ },
+ "SETTINGS$META_PROFILE_CLASSIFIER_HELP": {
+ "en": "LLM profile used to categorize each task before routing.",
+ "ja": "ルーティング前に各タスクを分類するために使う LLM プロファイルです。",
+ "zh-CN": "在路由前用于对每个任务分类的 LLM 配置文件。",
+ "zh-TW": "在路由前用來分類每個任務的 LLM 設定檔。",
+ "ko-KR": "라우팅 전에 각 작업을 분류하는 데 사용하는 LLM 프로필입니다.",
+ "no": "LLM-profilen som brukes til å kategorisere hver oppgave før ruting.",
+ "it": "Profilo LLM usato per classificare ogni attività prima dell’instradamento.",
+ "pt": "Perfil de LLM usado para categorizar cada tarefa antes do roteamento.",
+ "es": "Perfil de LLM usado para categorizar cada tarea antes del enrutamiento.",
+ "ar": "ملف LLM المستخدم لتصنيف كل مهمة قبل التوجيه.",
+ "fr": "Profil LLM utilisé pour classer chaque tâche avant le routage.",
+ "tr": "Yönlendirmeden önce her görevi sınıflandırmak için kullanılan LLM profili.",
+ "de": "LLM-Profil, mit dem jede Aufgabe vor dem Routing kategorisiert wird.",
+ "uk": "Профіль LLM, що використовується для класифікації кожного завдання перед маршрутизацією.",
+ "ca": "Perfil LLM utilitzat per classificar cada tasca abans de l’encaminament."
+ },
+ "SETTINGS$META_PROFILE_CLASSES": {
+ "en": "Task classes",
+ "ja": "タスククラス",
+ "zh-CN": "任务类别",
+ "zh-TW": "任務類別",
+ "ko-KR": "작업 클래스",
+ "no": "Oppgaveklasser",
+ "it": "Classi di attività",
+ "pt": "Classes de tarefa",
+ "es": "Clases de tarea",
+ "ar": "فئات المهام",
+ "fr": "Classes de tâches",
+ "tr": "Görev sınıfları",
+ "de": "Aufgabenklassen",
+ "uk": "Класи завдань",
+ "ca": "Classes de tasca"
+ },
+ "SETTINGS$META_PROFILE_CLASSES_HELP": {
+ "en": "Each class maps a kind of task to the LLM profile that should handle it.",
+ "ja": "各クラスはタスクの種類を、それを処理する LLM プロファイルに対応付けます。",
+ "zh-CN": "每个类别都会把一种任务映射到应处理它的 LLM 配置文件。",
+ "zh-TW": "每個類別都會把一種任務對應到應處理它的 LLM 設定檔。",
+ "ko-KR": "각 클래스는 작업 유형을 처리할 LLM 프로필에 매핑합니다.",
+ "no": "Hver klasse kobler en oppgavetype til LLM-profilen som skal håndtere den.",
+ "it": "Ogni classe associa un tipo di attività al profilo LLM che deve gestirla.",
+ "pt": "Cada classe mapeia um tipo de tarefa para o perfil de LLM que deve tratá-la.",
+ "es": "Cada clase asigna un tipo de tarea al perfil de LLM que debe manejarla.",
+ "ar": "تربط كل فئة نوعًا من المهام بملف LLM الذي يجب أن يتولاها.",
+ "fr": "Chaque classe associe un type de tâche au profil LLM qui doit la traiter.",
+ "tr": "Her sınıf, bir görev türünü onu işlemesi gereken LLM profiline eşler.",
+ "de": "Jede Klasse ordnet eine Aufgabenart dem LLM-Profil zu, das sie bearbeiten soll.",
+ "uk": "Кожен клас зіставляє тип завдання з профілем LLM, який має його обробляти.",
+ "ca": "Cada classe associa un tipus de tasca al perfil LLM que l’ha de gestionar."
+ },
+ "SETTINGS$META_PROFILE_ADD_CLASS": {
+ "en": "Add class",
+ "ja": "クラスを追加",
+ "zh-CN": "添加类别",
+ "zh-TW": "新增類別",
+ "ko-KR": "클래스 추가",
+ "no": "Legg til klasse",
+ "it": "Aggiungi classe",
+ "pt": "Adicionar classe",
+ "es": "Añadir clase",
+ "ar": "إضافة فئة",
+ "fr": "Ajouter une classe",
+ "tr": "Sınıf ekle",
+ "de": "Klasse hinzufügen",
+ "uk": "Додати клас",
+ "ca": "Afegeix una classe"
+ },
+ "SETTINGS$META_PROFILE_REMOVE_CLASS": {
+ "en": "Remove class",
+ "ja": "クラスを削除",
+ "zh-CN": "移除类别",
+ "zh-TW": "移除類別",
+ "ko-KR": "클래스 제거",
+ "no": "Fjern klasse",
+ "it": "Rimuovi classe",
+ "pt": "Remover classe",
+ "es": "Eliminar clase",
+ "ar": "إزالة الفئة",
+ "fr": "Supprimer la classe",
+ "tr": "Sınıfı kaldır",
+ "de": "Klasse entfernen",
+ "uk": "Вилучити клас",
+ "ca": "Elimina la classe"
+ },
+ "SETTINGS$META_PROFILE_CLASS_DESCRIPTION": {
+ "en": "Task description",
+ "ja": "タスクの説明",
+ "zh-CN": "任务描述",
+ "zh-TW": "任務描述",
+ "ko-KR": "작업 설명",
+ "no": "Oppgavebeskrivelse",
+ "it": "Descrizione attività",
+ "pt": "Descrição da tarefa",
+ "es": "Descripción de la tarea",
+ "ar": "وصف المهمة",
+ "fr": "Description de la tâche",
+ "tr": "Görev açıklaması",
+ "de": "Aufgabenbeschreibung",
+ "uk": "Опис завдання",
+ "ca": "Descripció de la tasca"
+ },
+ "SETTINGS$META_PROFILE_CLASS_DESCRIPTION_PLACEHOLDER": {
+ "en": "e.g. task is UI oriented or requires looking at images",
+ "ja": "例: UI 指向のタスク、または画像確認が必要なタスク",
+ "zh-CN": "例如:任务偏向 UI,或需要查看图片",
+ "zh-TW": "例如:任務偏向 UI,或需要查看圖片",
+ "ko-KR": "예: UI 중심 작업이거나 이미지 확인이 필요한 작업",
+ "no": "f.eks. oppgaven er UI-orientert eller krever å se på bilder",
+ "it": "es. attività orientata alla UI o che richiede di esaminare immagini",
+ "pt": "ex.: tarefa voltada para UI ou que exige analisar imagens",
+ "es": "p. ej., tarea orientada a UI o que requiere revisar imágenes",
+ "ar": "مثلًا: المهمة موجهة للواجهة أو تتطلب النظر إلى صور",
+ "fr": "par ex. tâche orientée UI ou nécessitant d’examiner des images",
+ "tr": "örn. görev UI odaklıdır veya görüntülere bakmayı gerektirir",
+ "de": "z. B. Aufgabe ist UI-orientiert oder erfordert das Betrachten von Bildern",
+ "uk": "наприклад: завдання пов’язане з UI або потребує перегляду зображень",
+ "ca": "p. ex. la tasca està orientada a la UI o requereix mirar imatges"
+ },
+ "SETTINGS$META_PROFILE_CLASS_MODEL": {
+ "en": "Model",
+ "ja": "モデル",
+ "zh-CN": "模型",
+ "zh-TW": "模型",
+ "ko-KR": "모델",
+ "no": "Modell",
+ "it": "Modello",
+ "pt": "Modelo",
+ "es": "Modelo",
+ "ar": "النموذج",
+ "fr": "Modèle",
+ "tr": "Model",
+ "de": "Modell",
+ "uk": "Модель",
+ "ca": "Model"
+ },
+ "SETTINGS$META_PROFILE_CLASSES_EMPTY": {
+ "en": "No classes yet — tasks will always use the default model.",
+ "ja": "クラスはまだありません — タスクは常にデフォルトモデルを使います。",
+ "zh-CN": "还没有类别 — 任务将始终使用默认模型。",
+ "zh-TW": "還沒有類別 — 任務將一律使用預設模型。",
+ "ko-KR": "아직 클래스가 없습니다 — 작업은 항상 기본 모델을 사용합니다.",
+ "no": "Ingen klasser ennå — oppgaver bruker alltid standardmodellen.",
+ "it": "Ancora nessuna classe — le attività useranno sempre il modello predefinito.",
+ "pt": "Ainda não há classes — as tarefas sempre usarão o modelo padrão.",
+ "es": "Aún no hay clases; las tareas siempre usarán el modelo predeterminado.",
+ "ar": "لا توجد فئات بعد — ستستخدم المهام دائمًا النموذج الافتراضي.",
+ "fr": "Aucune classe pour l’instant — les tâches utiliseront toujours le modèle par défaut.",
+ "tr": "Henüz sınıf yok — görevler her zaman varsayılan modeli kullanacak.",
+ "de": "Noch keine Klassen — Aufgaben verwenden immer das Standardmodell.",
+ "uk": "Класів ще немає — завдання завжди використовуватимуть типову модель.",
+ "ca": "Encara no hi ha classes — les tasques sempre faran servir el model predeterminat."
+ },
+ "SETTINGS$META_PROFILE_DIRECT_PROMPT": {
+ "en": "Direct prompt",
+ "ja": "ダイレクトプロンプト",
+ "zh-CN": "直接提示词",
+ "zh-TW": "直接提示詞",
+ "ko-KR": "직접 프롬프트",
+ "no": "Direkte prompt",
+ "it": "Prompt diretto",
+ "pt": "Prompt direto",
+ "es": "Prompt directo",
+ "ar": "مطالبة مباشرة",
+ "fr": "Prompt direct",
+ "tr": "Doğrudan istem",
+ "de": "Direkter Prompt",
+ "uk": "Прямий промпт",
+ "ca": "Indicació directa"
+ },
+ "SETTINGS$META_PROFILE_PROMPT_TEMPLATE": {
+ "en": "Prompt template",
+ "ja": "プロンプトテンプレート",
+ "zh-CN": "提示词模板",
+ "zh-TW": "提示詞範本",
+ "ko-KR": "프롬프트 템플릿",
+ "no": "Promptmal",
+ "it": "Modello del prompt",
+ "pt": "Modelo de prompt",
+ "es": "Plantilla de prompt",
+ "ar": "قالب المطالبة",
+ "fr": "Modèle de prompt",
+ "tr": "İstem şablonu",
+ "de": "Promptvorlage",
+ "uk": "Шаблон промпта",
+ "ca": "Plantilla d'indicació"
+ },
+ "SETTINGS$META_PROFILE_PROMPT_TEMPLATE_HELP": {
+ "en": "Prompt sent to the classifier model. It must include {{ instance_text }} and may include {{ model_table }}.",
+ "ja": "分類モデルに送信するプロンプトです。{{ instance_text }} を含める必要があり、{{ model_table }} も使用できます。",
+ "zh-CN": "发送给分类器模型的提示词。必须包含 {{ instance_text }},也可以包含 {{ model_table }}。",
+ "zh-TW": "傳送給分類器模型的提示詞。必須包含 {{ instance_text }},也可以包含 {{ model_table }}。",
+ "ko-KR": "분류 모델에 보내는 프롬프트입니다. {{ instance_text }}를 포함해야 하며 {{ model_table }}도 포함할 수 있습니다.",
+ "no": "Prompten som sendes til klassifiseringsmodellen. Den må inneholde {{ instance_text }} og kan inneholde {{ model_table }}.",
+ "it": "Prompt inviato al modello classificatore. Deve includere {{ instance_text }} e può includere {{ model_table }}.",
+ "pt": "Prompt enviado ao modelo classificador. Ele deve incluir {{ instance_text }} e pode incluir {{ model_table }}.",
+ "es": "Prompt enviado al modelo clasificador. Debe incluir {{ instance_text }} y puede incluir {{ model_table }}.",
+ "ar": "المطالبة المرسلة إلى نموذج التصنيف. يجب أن تتضمن {{ instance_text }} ويمكن أن تتضمن {{ model_table }}.",
+ "fr": "Prompt envoyé au modèle de classification. Il doit inclure {{ instance_text }} et peut inclure {{ model_table }}.",
+ "tr": "Sınıflandırıcı modele gönderilen istem. {{ instance_text }} içermeli ve {{ model_table }} içerebilir.",
+ "de": "Prompt, der an das Klassifizierungsmodell gesendet wird. Er muss {{ instance_text }} enthalten und kann {{ model_table }} enthalten.",
+ "uk": "Промпт, який надсилається моделі класифікації. Він має містити {{ instance_text }} і може містити {{ model_table }}.",
+ "ca": "Indicació enviada al model classificador. Ha d'incloure {{ instance_text }} i pot incloure {{ model_table }}."
+ },
+ "SETTINGS$META_PROFILE_PROMPT_TEMPLATE_PLACEHOLDER": {
+ "en": "Return JSON with the best model for this task.\\n{{ model_table }}\\n\\nTask:\\n{{ instance_text }}",
+ "ja": "このタスクに最適なモデルを JSON で返してください。\\n{{ model_table }}\\n\\nタスク:\\n{{ instance_text }}",
+ "zh-CN": "返回包含此任务最佳模型的 JSON。\\n{{ model_table }}\\n\\n任务:\\n{{ instance_text }}",
+ "zh-TW": "傳回包含此任務最佳模型的 JSON。\\n{{ model_table }}\\n\\n任務:\\n{{ instance_text }}",
+ "ko-KR": "이 작업에 가장 적합한 모델을 JSON으로 반환하세요.\\n{{ model_table }}\\n\\n작업:\\n{{ instance_text }}",
+ "no": "Returner JSON med den beste modellen for denne oppgaven.\\n{{ model_table }}\\n\\nOppgave:\\n{{ instance_text }}",
+ "it": "Restituisci JSON con il modello migliore per questa attività.\\n{{ model_table }}\\n\\nAttività:\\n{{ instance_text }}",
+ "pt": "Retorne JSON com o melhor modelo para esta tarefa.\\n{{ model_table }}\\n\\nTarefa:\\n{{ instance_text }}",
+ "es": "Devuelve JSON con el mejor modelo para esta tarea.\\n{{ model_table }}\\n\\nTarea:\\n{{ instance_text }}",
+ "ar": "أرجع JSON يتضمن أفضل نموذج لهذه المهمة.\\n{{ model_table }}\\n\\nالمهمة:\\n{{ instance_text }}",
+ "fr": "Renvoyez du JSON avec le meilleur modèle pour cette tâche.\\n{{ model_table }}\\n\\nTâche :\\n{{ instance_text }}",
+ "tr": "Bu görev için en iyi modeli içeren JSON döndür.\\n{{ model_table }}\\n\\nGörev:\\n{{ instance_text }}",
+ "de": "Gib JSON mit dem besten Modell für diese Aufgabe zurück.\\n{{ model_table }}\\n\\nAufgabe:\\n{{ instance_text }}",
+ "uk": "Поверни JSON із найкращою моделлю для цього завдання.\\n{{ model_table }}\\n\\nЗавдання:\\n{{ instance_text }}",
+ "ca": "Retorna JSON amb el millor model per a aquesta tasca.\\n{{ model_table }}\\n\\nTasca:\\n{{ instance_text }}"
+ },
+ "SETTINGS$META_PROFILE_MODEL_TABLE": {
+ "en": "Model table",
+ "ja": "モデル表",
+ "zh-CN": "模型表",
+ "zh-TW": "模型表",
+ "ko-KR": "모델 표",
+ "no": "Modelltabell",
+ "it": "Tabella dei modelli",
+ "pt": "Tabela de modelos",
+ "es": "Tabla de modelos",
+ "ar": "جدول النماذج",
+ "fr": "Table des modèles",
+ "tr": "Model tablosu",
+ "de": "Modelltabelle",
+ "uk": "Таблиця моделей",
+ "ca": "Taula de models"
+ },
+ "SETTINGS$META_PROFILE_MODEL_TABLE_HELP": {
+ "en": "Optional text inserted wherever the prompt template uses {{ model_table }}.",
+ "ja": "プロンプトテンプレート内の {{ model_table }} に挿入される任意のテキストです。",
+ "zh-CN": "可选文本,会插入到提示词模板中的 {{ model_table }} 位置。",
+ "zh-TW": "選用文字,會插入到提示詞範本中的 {{ model_table }} 位置。",
+ "ko-KR": "프롬프트 템플릿의 {{ model_table }} 위치에 삽입되는 선택 텍스트입니다.",
+ "no": "Valgfri tekst som settes inn der promptmalen bruker {{ model_table }}.",
+ "it": "Testo opzionale inserito ovunque il modello del prompt usi {{ model_table }}.",
+ "pt": "Texto opcional inserido onde o modelo de prompt usa {{ model_table }}.",
+ "es": "Texto opcional que se inserta donde la plantilla de prompt usa {{ model_table }}.",
+ "ar": "نص اختياري يُدرج حيث يستخدم قالب المطالبة {{ model_table }}.",
+ "fr": "Texte facultatif inséré partout où le modèle de prompt utilise {{ model_table }}.",
+ "tr": "İstem şablonunda {{ model_table }} kullanılan yere eklenen isteğe bağlı metin.",
+ "de": "Optionaler Text, der überall dort eingefügt wird, wo die Promptvorlage {{ model_table }} verwendet.",
+ "uk": "Необов'язковий текст, який вставляється всюди, де шаблон промпта використовує {{ model_table }}.",
+ "ca": "Text opcional inserit allà on la plantilla d'indicació usa {{ model_table }}."
+ },
+ "SETTINGS$META_PROFILE_ROUTER_CONNECTION_NONE": {
+ "en": "Don't create profiles",
+ "ja": "プロファイルを作成しない",
+ "zh-CN": "不创建配置文件",
+ "zh-TW": "不建立設定檔",
+ "ko-KR": "프로필을 만들지 않음",
+ "no": "Ikke opprett profiler",
+ "ar": "عدم إنشاء ملفات تعريف",
+ "de": "Keine Profile erstellen",
+ "fr": "Ne pas créer de profils",
+ "it": "Non creare profili",
+ "pt": "Não criar perfis",
+ "es": "No crear perfiles",
+ "ca": "No creïs perfils",
+ "tr": "Profil oluşturma",
+ "uk": "Не створювати профілі"
+ },
+ "SETTINGS$META_PROFILE_CREATE_ROUTER_PROFILES": {
+ "en": "Create missing router LLM profiles using",
+ "ja": "このルーターに不足している LLM プロファイルを作成",
+ "zh-CN": "为此路由器创建缺失的 LLM 配置文件",
+ "zh-TW": "為此路由器建立缺少的 LLM 設定檔",
+ "ko-KR": "이 라우터에 누락된 LLM 프로필 만들기",
+ "no": "Opprett manglende LLM-profiler for denne ruteren",
+ "it": "Crea i profili LLM mancanti per questo router",
+ "pt": "Criar perfis de LLM ausentes para este roteador",
+ "es": "Crear perfiles de LLM faltantes para este enrutador",
+ "ar": "إنشاء ملفات تعريف LLM المفقودة لهذا الموجّه",
+ "fr": "Créer les profils LLM manquants pour ce routeur",
+ "tr": "Bu yönlendirici için eksik LLM profillerini oluştur",
+ "de": "Fehlende LLM-Profile für diesen Router erstellen",
+ "uk": "Створити відсутні профілі LLM для цього маршрутизатора",
+ "ca": "Crea els perfils LLM que falten per a aquest encaminador"
+ },
+ "SETTINGS$META_PROFILE_CREATE_ROUTER_PROFILES_HELP": {
+ "en": "Missing models from the table are created as LLM profiles linked to the selected provider connection.",
+ "ja": "すべてのルーターモデルに現在のプロバイダー設定を再利用します。",
+ "zh-CN": "这会为所有路由器模型复用当前的提供商设置。",
+ "zh-TW": "這會為所有路由器模型重用目前的提供者設定。",
+ "ko-KR": "모든 라우터 모델에 현재 제공업체 설정을 재사용합니다.",
+ "no": "Dette gjenbruker gjeldende leverandørinnstillinger for alle rutermodeller.",
+ "it": "Riutilizzerà le impostazioni attuali del provider per tutti i modelli del router.",
+ "pt": "Isso reutilizará as configurações atuais do provedor para todos os modelos do roteador.",
+ "es": "Esto reutilizará la configuración actual del proveedor para todos los modelos del enrutador.",
+ "ar": "سيؤدي هذا إلى إعادة استخدام إعدادات المزوّد الحالية لكل نماذج الموجّه.",
+ "fr": "Cela réutilisera les paramètres actuels du fournisseur pour tous les modèles du routeur.",
+ "tr": "Bu, tüm yönlendirici modelleri için mevcut sağlayıcı ayarlarınızı yeniden kullanır.",
+ "de": "Dadurch werden Ihre aktuellen Anbieter-Einstellungen für alle Router-Modelle wiederverwendet.",
+ "uk": "Це повторно використає поточні налаштування постачальника для всіх моделей маршрутизатора.",
+ "ca": "Això reutilitzarà la configuració actual del proveïdor per a tots els models de l’encaminador."
+ },
+ "SETTINGS$META_PROFILE_MODEL_TABLE_PLACEHOLDER": {
+ "en": "- GPT-5.4: strong for coding and reasoning\\n- MiniMax-M3: efficient fallback",
+ "ja": "- GPT-5.4: コーディングと推論に強い\\n- MiniMax-M3: 効率的なフォールバック",
+ "zh-CN": "- GPT-5.4:擅长编码和推理\\n- MiniMax-M3:高效的备用模型",
+ "zh-TW": "- GPT-5.4:擅長編碼和推理\\n- MiniMax-M3:高效的備用模型",
+ "ko-KR": "- GPT-5.4: 코딩과 추론에 강함\\n- MiniMax-M3: 효율적인 대체 모델",
+ "no": "- GPT-5.4: sterk på koding og resonnering\\n- MiniMax-M3: effektiv reserve",
+ "it": "- GPT-5.4: forte per codice e ragionamento\\n- MiniMax-M3: fallback efficiente",
+ "pt": "- GPT-5.4: forte em código e raciocínio\\n- MiniMax-M3: fallback eficiente",
+ "es": "- GPT-5.4: sólido para código y razonamiento\\n- MiniMax-M3: alternativa eficiente",
+ "ar": "- GPT-5.4: قوي في البرمجة والاستدلال\\n- MiniMax-M3: بديل فعّال",
+ "fr": "- GPT-5.4 : solide pour le code et le raisonnement\\n- MiniMax-M3 : solution de repli efficace",
+ "tr": "- GPT-5.4: kodlama ve akıl yürütmede güçlü\\n- MiniMax-M3: verimli yedek",
+ "de": "- GPT-5.4: stark bei Code und Schlussfolgern\\n- MiniMax-M3: effiziente Ausweichoption",
+ "uk": "- GPT-5.4: сильний у кодуванні та міркуванні\\n- MiniMax-M3: ефективний запасний варіант",
+ "ca": "- GPT-5.4: fort per a codi i raonament\\n- MiniMax-M3: alternativa eficient"
+ },
+ "SETTINGS$META_PROFILE_NO_PROFILES": {
+ "en": "No meta-profiles yet. Add one to route tasks across your LLM profiles.",
+ "ja": "メタプロファイルはまだありません。タスクを LLM プロファイル間で振り分けるには追加してください。",
+ "zh-CN": "还没有元配置文件。添加一个以在 LLM 配置文件之间路由任务。",
+ "zh-TW": "還沒有中繼設定檔。新增一個以在 LLM 設定檔之間路由任務。",
+ "ko-KR": "아직 메타 프로필이 없습니다. LLM 프로필 간에 작업을 라우팅하려면 하나를 추가하세요.",
+ "no": "Ingen metaprofiler ennå. Legg til en for å rute oppgaver mellom LLM-profilene dine.",
+ "it": "Ancora nessun meta-profilo. Aggiungine uno per instradare le attività tra i tuoi profili LLM.",
+ "pt": "Ainda não há meta-perfis. Adicione um para rotear tarefas entre seus perfis de LLM.",
+ "es": "Aún no hay metaperfiles. Añade uno para enrutar tareas entre tus perfiles de LLM.",
+ "ar": "لا توجد ملفات تعريف وصفية بعد. أضف واحدًا لتوجيه المهام بين ملفات LLM لديك.",
+ "fr": "Aucun méta-profil pour l’instant. Ajoutez-en un pour router les tâches entre vos profils LLM.",
+ "tr": "Henüz meta profil yok. Görevleri LLM profilleriniz arasında yönlendirmek için bir tane ekleyin.",
+ "de": "Noch keine Metaprofile. Fügen Sie eines hinzu, um Aufgaben zwischen Ihren LLM-Profilen zu routen.",
+ "uk": "Метапрофілів ще немає. Додайте один, щоб маршрутизувати завдання між вашими профілями LLM.",
+ "ca": "Encara no hi ha metaperfils. Afegeix-ne un per encaminar tasques entre els teus perfils LLM."
+ },
+ "SETTINGS$META_PROFILE_NAME_TAKEN": {
+ "en": "A meta-profile with this name already exists. Choose a different name, or edit the existing one.",
+ "ja": "この名前のメタプロファイルはすでに存在します。別の名前を選ぶか、既存のものを編集してください。",
+ "zh-CN": "已存在同名元配置文件。请选择其他名称,或编辑现有配置文件。",
+ "zh-TW": "已存在同名中繼設定檔。請選擇其他名稱,或編輯現有設定檔。",
+ "ko-KR": "이 이름의 메타 프로필이 이미 있습니다. 다른 이름을 선택하거나 기존 항목을 편집하세요.",
+ "no": "En metaprofil med dette navnet finnes allerede. Velg et annet navn, eller rediger den eksisterende.",
+ "it": "Esiste già un meta-profilo con questo nome. Scegli un altro nome o modifica quello esistente.",
+ "pt": "Já existe um meta-perfil com este nome. Escolha outro nome ou edite o existente.",
+ "es": "Ya existe un metaperfil con este nombre. Elige otro nombre o edita el existente.",
+ "ar": "يوجد بالفعل ملف تعريف وصفي بهذا الاسم. اختر اسمًا مختلفًا أو عدّل الملف الموجود.",
+ "fr": "Un méta-profil portant ce nom existe déjà. Choisissez un autre nom ou modifiez l’existant.",
+ "tr": "Bu ada sahip bir meta profil zaten var. Farklı bir ad seçin veya mevcut olanı düzenleyin.",
+ "de": "Ein Metaprofil mit diesem Namen existiert bereits. Wählen Sie einen anderen Namen oder bearbeiten Sie das vorhandene.",
+ "uk": "Метапрофіль із такою назвою вже існує. Виберіть іншу назву або відредагуйте наявний.",
+ "ca": "Ja existeix un metaperfil amb aquest nom. Tria un altre nom o edita l’existent."
+ },
+ "SETTINGS$META_PROFILE_UNSUPPORTED": {
+ "en": "This backend doesn't support model routing yet. Update the agent server to manage meta-profiles.",
+ "ja": "このバックエンドはまだモデルルーティングをサポートしていません。メタプロファイルを管理するには agent server を更新してください。",
+ "zh-CN": "此后端尚不支持模型路由。请更新 agent server 以管理元配置文件。",
+ "zh-TW": "此後端尚不支援模型路由。請更新 agent server 以管理中繼設定檔。",
+ "ko-KR": "이 백엔드는 아직 모델 라우팅을 지원하지 않습니다. 메타 프로필을 관리하려면 agent server를 업데이트하세요.",
+ "no": "Denne backend støtter ikke modellruting ennå. Oppdater agent server for å administrere metaprofiler.",
+ "it": "Questo backend non supporta ancora il routing dei modelli. Aggiorna agent server per gestire i meta-profili.",
+ "pt": "Este backend ainda não oferece suporte ao roteamento de modelos. Atualize o agent server para gerenciar meta-perfis.",
+ "es": "Este backend aún no admite enrutamiento de modelos. Actualiza agent server para gestionar metaperfiles.",
+ "ar": "هذا الخلفية لا يدعم توجيه النماذج بعد. حدّث agent server لإدارة ملفات التعريف الوصفية.",
+ "fr": "Ce backend ne prend pas encore en charge le routage des modèles. Mettez à jour agent server pour gérer les méta-profils.",
+ "tr": "Bu arka uç henüz model yönlendirmeyi desteklemiyor. Meta profilleri yönetmek için agent server’ı güncelleyin.",
+ "de": "Dieses Backend unterstützt Modell-Routing noch nicht. Aktualisieren Sie den agent server, um Metaprofile zu verwalten.",
+ "uk": "Цей бекенд ще не підтримує маршрутизацію моделей. Оновіть agent server, щоб керувати метапрофілями.",
+ "ca": "Aquest backend encara no admet l’encaminament de models. Actualitza agent server per gestionar metaperfils."
+ },
+ "SETTINGS$META_PROFILE_ACTIVE": {
+ "en": "Active",
+ "ja": "アクティブ",
+ "zh-CN": "活跃",
+ "zh-TW": "使用中",
+ "ko-KR": "활성",
+ "no": "Aktiv",
+ "it": "Attivo",
+ "pt": "Ativo",
+ "es": "Activo",
+ "ar": "نشط",
+ "fr": "Actif",
+ "tr": "Etkin",
+ "de": "Aktiv",
+ "uk": "Активний",
+ "ca": "Actiu"
+ },
+ "SETTINGS$META_PROFILE_ACTIVATE": {
+ "en": "Set active",
+ "ja": "アクティブに設定",
+ "zh-CN": "设为活跃",
+ "zh-TW": "設為使用中",
+ "ko-KR": "활성으로 설정",
+ "no": "Sett som aktiv",
+ "it": "Imposta come attivo",
+ "pt": "Definir como ativo",
+ "es": "Establecer como activo",
+ "ar": "تعيين كنشط",
+ "fr": "Définir comme actif",
+ "tr": "Etkin olarak ayarla",
+ "de": "Als aktiv festlegen",
+ "uk": "Зробити активним",
+ "ca": "Defineix com a actiu"
+ },
+ "SETTINGS$META_PROFILE_SAVED": {
+ "en": "Meta-profile \"{{name}}\" saved",
+ "ja": "メタプロファイル \"{{name}}\" を保存しました",
+ "zh-CN": "已保存元配置文件“{{name}}”",
+ "zh-TW": "已儲存中繼設定檔「{{name}}」",
+ "ko-KR": "메타 프로필 \"{{name}}\"이(가) 저장되었습니다",
+ "no": "Metaprofilen «{{name}}» er lagret",
+ "it": "Meta-profilo \"{{name}}\" salvato",
+ "pt": "Meta-perfil \"{{name}}\" salvo",
+ "es": "Metaperfil \"{{name}}\" guardado",
+ "ar": "تم حفظ ملف التعريف الوصفي \"{{name}}\"",
+ "fr": "Méta-profil « {{name}} » enregistré",
+ "tr": "\"{{name}}\" meta profili kaydedildi",
+ "de": "Metaprofil „{{name}}“ gespeichert",
+ "uk": "Метапрофіль \"{{name}}\" збережено",
+ "ca": "S’ha desat el metaperfil \"{{name}}\""
+ },
+ "SETTINGS$META_PROFILE_ACTIVATED": {
+ "en": "Meta-profile \"{{name}}\" activated",
+ "ja": "メタプロファイル \"{{name}}\" をアクティブにしました",
+ "zh-CN": "已激活元配置文件“{{name}}”",
+ "zh-TW": "已啟用中繼設定檔「{{name}}」",
+ "ko-KR": "메타 프로필 \"{{name}}\"이(가) 활성화되었습니다",
+ "no": "Metaprofilen «{{name}}» er aktivert",
+ "it": "Meta-profilo \"{{name}}\" attivato",
+ "pt": "Meta-perfil \"{{name}}\" ativado",
+ "es": "Metaperfil \"{{name}}\" activado",
+ "ar": "تم تنشيط ملف التعريف الوصفي \"{{name}}\"",
+ "fr": "Méta-profil « {{name}} » activé",
+ "tr": "\"{{name}}\" meta profili etkinleştirildi",
+ "de": "Metaprofil „{{name}}“ aktiviert",
+ "uk": "Метапрофіль \"{{name}}\" активовано",
+ "ca": "S’ha activat el metaperfil \"{{name}}\""
+ },
+ "SETTINGS$META_PROFILE_DELETED": {
+ "en": "Meta-profile \"{{name}}\" deleted",
+ "ja": "メタプロファイル \"{{name}}\" を削除しました",
+ "zh-CN": "已删除元配置文件“{{name}}”",
+ "zh-TW": "已刪除中繼設定檔「{{name}}」",
+ "ko-KR": "메타 프로필 \"{{name}}\"이(가) 삭제되었습니다",
+ "no": "Metaprofilen «{{name}}» er slettet",
+ "it": "Meta-profilo \"{{name}}\" eliminato",
+ "pt": "Meta-perfil \"{{name}}\" excluído",
+ "es": "Metaperfil \"{{name}}\" eliminado",
+ "ar": "تم حذف ملف التعريف الوصفي \"{{name}}\"",
+ "fr": "Méta-profil « {{name}} » supprimé",
+ "tr": "\"{{name}}\" meta profili silindi",
+ "de": "Metaprofil „{{name}}“ gelöscht",
+ "uk": "Метапрофіль \"{{name}}\" видалено",
+ "ca": "S’ha suprimit el metaperfil \"{{name}}\""
+ },
+ "SETTINGS$META_PROFILE_DELETE_TITLE": {
+ "en": "Delete meta-profile",
+ "ja": "メタプロファイルを削除",
+ "zh-CN": "删除元配置文件",
+ "zh-TW": "刪除中繼設定檔",
+ "ko-KR": "메타 프로필 삭제",
+ "no": "Slett metaprofil",
+ "it": "Elimina meta-profilo",
+ "pt": "Excluir meta-perfil",
+ "es": "Eliminar metaperfil",
+ "ar": "حذف ملف التعريف الوصفي",
+ "fr": "Supprimer le méta-profil",
+ "tr": "Meta profili sil",
+ "de": "Metaprofil löschen",
+ "uk": "Видалити метапрофіль",
+ "ca": "Suprimeix el metaperfil"
+ },
+ "SETTINGS$META_PROFILE_DELETE_CONFIRMATION": {
+ "en": "Are you sure you want to delete \"{{name}}\"? This cannot be undone.",
+ "ja": "\"{{name}}\" を削除してもよろしいですか?この操作は元に戻せません。",
+ "zh-CN": "确定要删除“{{name}}”吗?此操作无法撤消。",
+ "zh-TW": "確定要刪除「{{name}}」嗎?此操作無法復原。",
+ "ko-KR": "\"{{name}}\"을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
+ "no": "Er du sikker på at du vil slette «{{name}}»? Dette kan ikke angres.",
+ "it": "Vuoi davvero eliminare \"{{name}}\"? Questa azione non può essere annullata.",
+ "pt": "Tem certeza de que deseja excluir \"{{name}}\"? Esta ação não pode ser desfeita.",
+ "es": "¿Seguro que quieres eliminar \"{{name}}\"? Esta acción no se puede deshacer.",
+ "ar": "هل أنت متأكد من حذف \"{{name}}\"؟ لا يمكن التراجع عن هذا الإجراء.",
+ "fr": "Voulez-vous vraiment supprimer « {{name}} » ? Cette action est irréversible.",
+ "tr": "\"{{name}}\" öğesini silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.",
+ "de": "Möchten Sie „{{name}}“ wirklich löschen? Dies kann nicht rückgängig gemacht werden.",
+ "uk": "Ви впевнені, що хочете видалити \"{{name}}\"? Цю дію не можна скасувати.",
+ "ca": "Segur que vols suprimir \"{{name}}\"? Aquesta acció no es pot desfer."
+ },
+ "SETTINGS$META_PROFILE_NO_LLM_PROFILES": {
+ "en": "Create LLM profiles first — meta-profiles route between your saved LLM profiles.",
+ "ja": "先に LLM プロファイルを作成してください — メタプロファイルは保存済みの LLM プロファイル間でルーティングします。",
+ "zh-CN": "请先创建 LLM 配置文件 — 元配置文件会在已保存的 LLM 配置文件之间路由。",
+ "zh-TW": "請先建立 LLM 設定檔 — 中繼設定檔會在已儲存的 LLM 設定檔之間路由。",
+ "ko-KR": "먼저 LLM 프로필을 만드세요 — 메타 프로필은 저장된 LLM 프로필 간에 라우팅합니다.",
+ "no": "Opprett LLM-profiler først — metaprofiler ruter mellom de lagrede LLM-profilene dine.",
+ "it": "Crea prima i profili LLM — i meta-profili instradano tra i profili LLM salvati.",
+ "pt": "Crie perfis de LLM primeiro — meta-perfis roteiam entre seus perfis de LLM salvos.",
+ "es": "Crea primero perfiles de LLM: los metaperfiles enrutan entre tus perfiles de LLM guardados.",
+ "ar": "أنشئ ملفات LLM أولًا — توجه الملفات الوصفية بين ملفات LLM المحفوظة لديك.",
+ "fr": "Créez d’abord des profils LLM — les méta-profils routent entre vos profils LLM enregistrés.",
+ "tr": "Önce LLM profilleri oluşturun — meta profiller kayıtlı LLM profilleriniz arasında yönlendirir.",
+ "de": "Erstellen Sie zuerst LLM-Profile — Metaprofile routen zwischen Ihren gespeicherten LLM-Profilen.",
+ "uk": "Спочатку створіть профілі LLM — метапрофілі маршрутизують між вашими збереженими профілями LLM.",
+ "ca": "Crea primer perfils LLM — els metaperfils encaminen entre els teus perfils LLM desats."
+ },
+ "SETTINGS$META_PROFILE_CLOUD_UNSUPPORTED": {
+ "en": "Meta-profiles are only available for local backends.",
+ "ja": "メタプロファイルはローカルバックエンドでのみ利用できます。",
+ "zh-CN": "元配置文件仅适用于本地后端。",
+ "zh-TW": "中繼設定檔僅適用於本機後端。",
+ "ko-KR": "메타 프로필은 로컬 백엔드에서만 사용할 수 있습니다.",
+ "no": "Metaprofiler er bare tilgjengelige for lokale backender.",
+ "it": "I meta-profili sono disponibili solo per backend locali.",
+ "pt": "Meta-perfis estão disponíveis apenas para backends locais.",
+ "es": "Los metaperfiles solo están disponibles para backends locales.",
+ "ar": "ملفات التعريف الوصفية متاحة فقط للخلفيات المحلية.",
+ "fr": "Les méta-profils ne sont disponibles que pour les backends locaux.",
+ "tr": "Meta profiller yalnızca yerel arka uçlarda kullanılabilir.",
+ "de": "Metaprofile sind nur für lokale Backends verfügbar.",
+ "uk": "Метапрофілі доступні лише для локальних бекендів.",
+ "ca": "Els metaperfils només estan disponibles per a backends locals."
+ },
"SETTINGS$AGENT_PAGE_DESCRIPTION": {
"en": "Choose between the built-in OpenHands agent and an external ACP (Agent Client Protocol) subprocess such as Claude Code, Codex, or Gemini CLI.",
"ja": "組み込みのOpenHandsエージェントと、Claude Code、Codex、Gemini CLIなどの外部ACP(Agent Client Protocol)サブプロセスのどちらかを選択します。",
@@ -14330,7 +15044,6 @@
"uk": "Повідомлено користувацькі метадані завдання.",
"ca": "S'han informat metadades personalitzades de la tasca."
},
-
"AUTOMATIONS$DETAIL$VIEW_CONVERSATION_FOR_RUN": {
"en": "View conversation for run at {{timestamp}}",
"ja": "{{timestamp}} の実行の会話を表示",
@@ -14348,7 +15061,6 @@
"uk": "Переглянути розмову для запуску о {{timestamp}}",
"ca": "Mostra la conversa de l'execució a {{timestamp}}"
},
-
"AUTOMATIONS$DETAIL$PHASE": {
"ar": "المرحلة",
"ca": "Fase",
diff --git a/src/routes.ts b/src/routes.ts
index 71d5a0d9a6..aa444409b0 100644
--- a/src/routes.ts
+++ b/src/routes.ts
@@ -24,6 +24,7 @@ export default [
route("settings", "routes/settings.tsx", [
index("routes/settings-index.tsx"),
route("llm", "routes/llm-settings.tsx"),
+ route("meta-llm", "routes/meta-llm-settings.tsx"),
route("agent", "routes/agent-settings.tsx"),
route("agents", "routes/agent-profiles-settings.tsx"),
route("condenser", "routes/condenser-settings.tsx"),
diff --git a/src/routes/meta-llm-settings.tsx b/src/routes/meta-llm-settings.tsx
new file mode 100644
index 0000000000..bd5ef2a948
--- /dev/null
+++ b/src/routes/meta-llm-settings.tsx
@@ -0,0 +1,32 @@
+import { useTranslation } from "react-i18next";
+import { MetaLlmSettingsView } from "#/components/features/settings/meta-llm-profiles";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { I18nKey } from "#/i18n/declaration";
+
+/**
+ * Settings route for managing *meta-profiles* — declarative model-routing
+ * configurations consumed by the agent's ``route_task_to_model`` tool.
+ *
+ * Local backends store meta-profiles on the agent-server. Organization-bound
+ * cloud backends store them in the SaaS control plane and pass the active
+ * configuration inline to ephemeral runtimes.
+ *
+ * Note: This is a route file, only the router should import the default export.
+ */
+export default function MetaLlmSettingsRoute() {
+ const { t } = useTranslation("openhands");
+ const { backend, orgId } = useActiveBackend();
+
+ if (backend.kind === "cloud" && !orgId) {
+ return (
+ <p
+ data-testid="meta-profile-cloud-unsupported"
+ className="text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.SETTINGS$META_PROFILE_CLOUD_UNSUPPORTED)}
+ </p>
+ );
+ }
+
+ return <MetaLlmSettingsView />;
+}
diff --git a/src/types/agent-server/core/base/base.ts b/src/types/agent-server/core/base/base.ts
index 31eea2470b..d75cb66b0b 100644
--- a/src/types/agent-server/core/base/base.ts
+++ b/src/types/agent-server/core/base/base.ts
@@ -12,7 +12,8 @@ type EventType =
| "TaskTracker"
| "PlanningFileEditor"
| "InvokeSkill"
- | "SwitchLLM";
+ | "SwitchLLM"
+ | "ClassifyAndSwitchLLM";
type ActionOnlyType =
| "BrowserNavigate"
diff --git a/src/types/agent-server/core/base/observation.ts b/src/types/agent-server/core/base/observation.ts
index 9a6fd719aa..930dfc7a3c 100644
--- a/src/types/agent-server/core/base/observation.ts
+++ b/src/types/agent-server/core/base/observation.ts
@@ -361,6 +361,31 @@ export interface SwitchLLMObservation extends ObservationBase<"SwitchLLMObservat
active_model: string | null;
}
+export interface ClassifyAndSwitchLLMObservation extends ObservationBase<"ClassifyAndSwitchLLMObservation"> {
+ /**
+ * Content returned from the classify-and-switch router tool.
+ */
+ content: Array<TextContent | ImageContent>;
+ /**
+ * Whether the router switch resulted in an error.
+ */
+ is_error: boolean;
+ /**
+ * Classifier category that won, if the classifier surfaced one.
+ */
+ chosen_class: string | null;
+ /**
+ * Model the classifier asked for (case-insensitively matched against saved
+ * LLM profile names on the agent-server side).
+ */
+ model: string | null;
+ /**
+ * Model actually activated after the router match. Drives the combobox
+ * update — same role as SwitchLLMObservation.active_model.
+ */
+ active_model: string | null;
+}
+
export type Observation =
| MCPToolObservation
| FinishObservation
@@ -377,4 +402,5 @@ export type Observation =
| InvokeSkillObservation
| TaskObservation
| CanvasUIObservation
- | SwitchLLMObservation;
+ | SwitchLLMObservation
+ | ClassifyAndSwitchLLMObservation;
diff --git a/src/types/agent-server/type-guards.ts b/src/types/agent-server/type-guards.ts
index 9964092b51..989cf163f4 100644
--- a/src/types/agent-server/type-guards.ts
+++ b/src/types/agent-server/type-guards.ts
@@ -16,6 +16,7 @@ import {
BrowserObservation,
BrowserNavigateAction,
SwitchLLMObservation,
+ ClassifyAndSwitchLLMObservation,
CanvasUIAction,
LaunchChildConversationAction,
} from "./core";
@@ -166,6 +167,16 @@ export const isSwitchLLMObservationEvent = (
isObservationEvent(event) &&
event.observation.kind === "SwitchLLMObservation";
+/**
+ * Type guard for router-driven model switches (Pareto/meta-profile classifier).
+ * Mirrors isSwitchLLMObservationEvent — same UI semantics, different tool.
+ */
+export const isClassifyAndSwitchLLMObservationEvent = (
+ event: OpenHandsEvent,
+): event is ObservationEvent<ClassifyAndSwitchLLMObservation> =>
+ isObservationEvent(event) &&
+ event.observation.kind === "ClassifyAndSwitchLLMObservation";
+
/**
* Type guard function to check if an action event is a BrowserNavigateAction
*/
diff --git a/src/utils/transcript-export/index.ts b/src/utils/transcript-export/index.ts
index 635d7bf780..75570dc33a 100644
--- a/src/utils/transcript-export/index.ts
+++ b/src/utils/transcript-export/index.ts
@@ -16,6 +16,7 @@ import {
isObservationEvent,
isStreamingDeltaEvent,
isSwitchLLMObservationEvent,
+ isClassifyAndSwitchLLMObservationEvent,
} from "#/types/agent-server/type-guards";
import { handleEventForUI } from "#/utils/handle-event-for-ui";
import { markdownFence } from "#/utils/markdown-fence";
@@ -105,6 +106,7 @@ const SAFE_OBSERVATION_DETAIL_KINDS = new Set([
"MCPToolObservation",
"StrReplaceEditorObservation",
"SwitchLLMObservation",
+ "ClassifyAndSwitchLLMObservation",
"TaskTrackerObservation",
"TaskObservation",
"TerminalObservation",
@@ -281,6 +283,8 @@ const buildTranscriptEntries = (
const renderableEvents = uiEvents.filter(
(event) =>
(isSwitchLLMObservationEvent(event) && !event.observation.is_error) ||
+ (isClassifyAndSwitchLLMObservationEvent(event) &&
+ !event.observation.is_error) ||
shouldRenderEvent(event),
);
const renderedItems = groupEvents(
@@ -345,6 +349,33 @@ const buildTranscriptEntries = (
continue;
}
+ if (
+ isClassifyAndSwitchLLMObservationEvent(event) &&
+ !event.observation.is_error &&
+ event.observation.model
+ ) {
+ // Router-driven switch: surface the activated profile the same way
+ // as a manual `/model` switch, and tag the chosen classifier
+ // category as the reason so transcript readers can see *why* the
+ // router picked this model.
+ entries.push({
+ kind: "note",
+ summary: translatePlain(I18nKey.MODEL$SWITCHED_TO_PROFILE, {
+ name: event.observation.model,
+ }),
+ content: [
+ `${i18n.t(I18nKey.TRANSCRIPT_EXPORT$MODEL)}: ${event.observation.active_model}`,
+ event.observation.chosen_class
+ ? `${i18n.t(I18nKey.TRANSCRIPT_EXPORT$REASON)}: ${event.observation.chosen_class}`
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n"),
+ timestamp: event.timestamp ?? "",
+ });
+ continue;
+ }
+
if (isMessageEvent(event)) {
const parsed = parseMessageFromEvent(event).trim();
if (event.source === "agent") {