π OpenHands: AI-Driven Development
feat: add LLM profiles API layer and React Query hooks (#387)
Rohit Malhotra0569bd77ec51
diff --git a/__tests__/api/profiles-service.test.ts b/__tests__/api/profiles-service.test.tsnew file mode 100644index 0000000000..bb7033a240--- /dev/null+++ b/__tests__/api/profiles-service.test.ts@@ -0,0 +1,231 @@+/**+ * ProfilesService tests using SDK client mocks.+ *+ * Note: We mock ProfilesClient directly because the SDK's HttpClient uses+ * native fetch that MSW doesn't intercept reliably in Node.js test environments.+ * This approach tests that ProfilesService correctly delegates to ProfilesClient+ * methods and propagates errors from the SDK.+ *+ * For full integration testing, use browser-level tests with MSW.+ */+import { ProfilesClient } from "@openhands/typescript-client/clients";+import { afterEach, describe, expect, it, vi, beforeEach } from "vitest";+import ProfilesService from "#/api/profiles-service/profiles-service.api";++// Mock the ProfilesClient from the SDK using vi.hoisted+const {+ mockListProfiles,+ mockGetProfile,+ mockSaveProfile,+ mockDeleteProfile,+ mockRenameProfile,+ mockActivateProfile,+} = vi.hoisted(() => ({+ mockListProfiles: vi.fn(),+ mockGetProfile: vi.fn(),+ mockSaveProfile: vi.fn(),+ mockDeleteProfile: vi.fn(),+ mockRenameProfile: vi.fn(),+ mockActivateProfile: vi.fn(),+}));++vi.mock("@openhands/typescript-client/clients", () => ({+ ProfilesClient: vi.fn(function ProfilesClientMock() {+ return {+ listProfiles: mockListProfiles,+ getProfile: mockGetProfile,+ saveProfile: mockSaveProfile,+ deleteProfile: mockDeleteProfile,+ renameProfile: mockRenameProfile,+ activateProfile: mockActivateProfile,+ };+ }),+}));++vi.mock("#/api/agent-server-client-options", () => ({+ getAgentServerClientOptions: vi.fn(() => ({+ host: "http://localhost:3000",+ apiKey: "test-key",+ })),+}));++describe("ProfilesService", () => {+ beforeEach(() => {+ mockListProfiles.mockReset();+ mockGetProfile.mockReset();+ mockSaveProfile.mockReset();+ mockDeleteProfile.mockReset();+ mockRenameProfile.mockReset();+ mockActivateProfile.mockReset();+ vi.mocked(ProfilesClient).mockClear();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ describe("listProfiles", () => {+ it("calls listProfiles and returns profiles list", async () => {+ const mockResponse = {+ profiles: [+ {+ name: "gpt-4-profile",+ model: "openai/gpt-4",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "claude-profile",+ model: "anthropic/claude-3",+ base_url: "https://api.anthropic.com",+ api_key_set: false,+ },+ ],+ active_profile: null,+ };++ mockListProfiles.mockResolvedValue(mockResponse);++ const result = await ProfilesService.listProfiles();++ expect(mockListProfiles).toHaveBeenCalled();+ expect(result).toEqual(mockResponse);+ expect(result.profiles).toHaveLength(2);+ });++ it("returns empty profiles array when no profiles exist", async () => {+ const mockResponse = { profiles: [], active_profile: null };+ mockListProfiles.mockResolvedValue(mockResponse);++ const result = await ProfilesService.listProfiles();++ expect(result.profiles).toEqual([]);+ });++ it("propagates errors from the SDK", async () => {+ mockListProfiles.mockRejectedValue(new Error("Network error"));++ await expect(ProfilesService.listProfiles()).rejects.toThrow(+ "Network error",+ );+ });+ });++ describe("getProfile", () => {+ it("calls getProfile with profile name", async () => {+ const mockResponse = {+ name: "my-profile",+ config: { model: "openai/gpt-4" },+ api_key_set: true,+ };++ mockGetProfile.mockResolvedValue(mockResponse);++ const result = await ProfilesService.getProfile("my-profile");++ expect(mockGetProfile).toHaveBeenCalledWith("my-profile", {});+ expect(result).toEqual(mockResponse);+ });++ it("passes exposeSecrets option when set", async () => {+ const mockResponse = {+ name: "my-profile",+ config: { model: "openai/gpt-4", api_key: "encrypted_..." },+ api_key_set: true,+ };++ mockGetProfile.mockResolvedValue(mockResponse);++ await ProfilesService.getProfile("my-profile", "encrypted");++ expect(mockGetProfile).toHaveBeenCalledWith("my-profile", {+ exposeSecrets: "encrypted",+ });+ });+ });++ describe("saveProfile", () => {+ it("calls saveProfile with name and request body", async () => {+ const mockResponse = { name: "new-profile", message: "Profile saved" };+ mockSaveProfile.mockResolvedValue(mockResponse);++ const request = {+ llm: {+ model: "openai/gpt-4",+ api_key: "sk-xxx",+ },+ include_secrets: true,+ };++ const result = await ProfilesService.saveProfile("new-profile", request);++ expect(mockSaveProfile).toHaveBeenCalledWith("new-profile", request);+ expect(result).toEqual(mockResponse);+ });++ it("saves profile with base_url", async () => {+ const mockResponse = { name: "custom-profile", message: "Profile saved" };+ mockSaveProfile.mockResolvedValue(mockResponse);++ const request = {+ llm: {+ model: "openai/gpt-4",+ base_url: "https://custom.api.com",+ },+ };++ await ProfilesService.saveProfile("custom-profile", request);++ expect(mockSaveProfile).toHaveBeenCalledWith("custom-profile", request);+ });+ });++ describe("deleteProfile", () => {+ it("calls deleteProfile with profile name", async () => {+ const mockResponse = { name: "old-profile", message: "Profile deleted" };+ mockDeleteProfile.mockResolvedValue(mockResponse);++ const result = await ProfilesService.deleteProfile("old-profile");++ expect(mockDeleteProfile).toHaveBeenCalledWith("old-profile");+ expect(result).toEqual(mockResponse);+ });+ });++ describe("renameProfile", () => {+ it("calls renameProfile with old and new names", async () => {+ const mockResponse = {+ name: "renamed-profile",+ message: "Profile renamed",+ };+ mockRenameProfile.mockResolvedValue(mockResponse);++ const result = await ProfilesService.renameProfile(+ "old-name",+ "renamed-profile",+ );++ expect(mockRenameProfile).toHaveBeenCalledWith(+ "old-name",+ "renamed-profile",+ );+ expect(result).toEqual(mockResponse);+ });+ });++ describe("activateProfile", () => {+ it("calls activateProfile with profile name", async () => {+ const mockResponse = {+ name: "active-profile",+ message: "Profile activated",+ llm_applied: true,+ };+ mockActivateProfile.mockResolvedValue(mockResponse);++ const result = await ProfilesService.activateProfile("active-profile");++ expect(mockActivateProfile).toHaveBeenCalledWith("active-profile");+ expect(result).toEqual(mockResponse);+ });+ });+});diff --git a/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx b/__tests__/hooks/mutation/use-activate-llm-profile.test.tsxnew file mode 100644index 0000000000..8183742954--- /dev/null+++ b/__tests__/hooks/mutation/use-activate-llm-profile.test.tsx@@ -0,0 +1,111 @@+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ LLM_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++vi.mock("#/api/profiles-service/profiles-service.api", () => ({+ default: {+ activateProfile: vi.fn(),+ },+}));++describe("useActivateLlmProfile", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ SettingsService.invalidateCache();+ });++ it("calls activateProfile and invalidates all relevant caches on success", async () => {+ const mockActivateProfile = vi.mocked(ProfilesService.activateProfile);+ mockActivateProfile.mockResolvedValue({+ name: "my-profile",+ message: "Profile activated",+ llm_applied: true,+ });++ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });++ const invalidateQueriesSpy = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useActivateLlmProfile(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ ),+ });++ // Trigger the mutation+ result.current.mutate("my-profile");++ // Wait for the mutation to complete+ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ // Verify activateProfile was called with the correct name+ expect(mockActivateProfile).toHaveBeenCalledWith("my-profile");++ // Verify all cache invalidations occur on success+ expect(invalidateCacheSpy).toHaveBeenCalled();+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(invalidateQueriesSpy).toHaveBeenCalledWith({+ queryKey: SETTINGS_QUERY_KEYS.personal(),+ });++ invalidateCacheSpy.mockRestore();+ invalidateQueriesSpy.mockRestore();+ });++ it("does not invalidate cache on activation failure", async () => {+ const mockActivateProfile = vi.mocked(ProfilesService.activateProfile);+ mockActivateProfile.mockRejectedValue(new Error("Profile not found"));++ // Create spy after beforeEach invalidation+ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });++ const { result } = renderHook(() => useActivateLlmProfile(), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ ),+ });++ // Trigger the mutation+ result.current.mutate("nonexistent-profile");++ // Wait for the mutation to fail+ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });++ // invalidateCache should NOT have been called on failure+ // (onSuccess is not called when mutation fails)+ expect(invalidateCacheSpy).not.toHaveBeenCalled();++ invalidateCacheSpy.mockRestore();+ });+});diff --git a/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx b/__tests__/hooks/mutation/use-delete-llm-profile.test.tsxnew file mode 100644index 0000000000..d861ce3b9d--- /dev/null+++ b/__tests__/hooks/mutation/use-delete-llm-profile.test.tsx@@ -0,0 +1,96 @@+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 { useDeleteLlmProfile } from "#/hooks/mutation/use-delete-llm-profile";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import { LLM_PROFILES_QUERY_KEYS, SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";++vi.mock("#/api/profiles-service/profiles-service.api");+vi.mock("#/api/settings-service/settings-service.api");++describe("useDeleteLlmProfile", () => {+ 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 ProfilesService.deleteProfile with name", async () => {+ vi.mocked(ProfilesService.deleteProfile).mockResolvedValue({+ name: "old-profile",+ message: "Profile deleted",+ });++ const { result } = renderHook(() => useDeleteLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync("old-profile");+ });++ expect(ProfilesService.deleteProfile).toHaveBeenCalledWith("old-profile");+ });++ it("invalidates LLM_PROFILES_QUERY_KEYS.all on success", async () => {+ vi.mocked(ProfilesService.deleteProfile).mockResolvedValue({+ name: "deleted-profile",+ message: "Profile deleted",+ });++ queryClient.setQueryData(LLM_PROFILES_QUERY_KEYS.all, {+ profiles: [{ name: "deleted-profile", model: "gpt-4", base_url: null, api_key_set: true }],+ });+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");+ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");++ const { result } = renderHook(() => useDeleteLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync("deleted-profile");+ });++ // Verifies all three cache invalidations occur on success+ expect(invalidateCacheSpy).toHaveBeenCalled();+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: SETTINGS_QUERY_KEYS.personal(),+ });+ });++ it("handles delete errors", async () => {+ const error = new Error("Profile not found");+ vi.mocked(ProfilesService.deleteProfile).mockRejectedValue(error);++ const { result } = renderHook(() => useDeleteLlmProfile(), { wrapper });++ await expect(+ act(async () => {+ await result.current.mutateAsync("nonexistent-profile");+ }),+ ).rejects.toThrow("Profile not found");++ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });+ });+});diff --git a/__tests__/hooks/mutation/use-rename-llm-profile.test.tsx b/__tests__/hooks/mutation/use-rename-llm-profile.test.tsxnew file mode 100644index 0000000000..4b55098af5--- /dev/null+++ b/__tests__/hooks/mutation/use-rename-llm-profile.test.tsx@@ -0,0 +1,161 @@+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 { useRenameLlmProfile } from "#/hooks/mutation/use-rename-llm-profile";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import { LLM_PROFILES_QUERY_KEYS, SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";++vi.mock("#/api/profiles-service/profiles-service.api");+vi.mock("#/api/settings-service/settings-service.api");++describe("useRenameLlmProfile", () => {+ 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 ProfilesService.renameProfile with name and newName", async () => {+ vi.mocked(ProfilesService.renameProfile).mockResolvedValue({+ name: "new-name",+ message: "Profile renamed",+ });++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "old-name",+ newName: "new-name",+ });+ });++ expect(ProfilesService.renameProfile).toHaveBeenCalledWith("old-name", "new-name");+ });++ it("invalidates LLM_PROFILES_QUERY_KEYS.all on success", async () => {+ vi.mocked(ProfilesService.renameProfile).mockResolvedValue({+ name: "renamed-profile",+ message: "Profile renamed",+ });++ queryClient.setQueryData(LLM_PROFILES_QUERY_KEYS.all, {+ profiles: [{ name: "old-name", model: "gpt-4", base_url: null, api_key_set: true }],+ });+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "old-name",+ newName: "renamed-profile",+ });+ });++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ });++ it("invalidates settings queries on success", async () => {+ vi.mocked(ProfilesService.renameProfile).mockResolvedValue({+ name: "new-name",+ message: "Profile renamed",+ });++ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "old-name",+ newName: "new-name",+ });+ });++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: SETTINGS_QUERY_KEYS.personal(),+ });+ });++ it("handles rename errors (e.g., name conflict)", async () => {+ const error = new Error("Profile name already exists");+ vi.mocked(ProfilesService.renameProfile).mockRejectedValue(error);++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await expect(+ act(async () => {+ await result.current.mutateAsync({+ name: "old-name",+ newName: "existing-name",+ });+ }),+ ).rejects.toThrow("Profile name already exists");++ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });+ });++ it("handles rename errors (e.g., profile not found)", async () => {+ const error = new Error("Profile not found");+ vi.mocked(ProfilesService.renameProfile).mockRejectedValue(error);++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await expect(+ act(async () => {+ await result.current.mutateAsync({+ name: "nonexistent",+ newName: "new-name",+ });+ }),+ ).rejects.toThrow("Profile not found");++ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });+ });++ it("invalidates SettingsService cache on success", async () => {+ vi.mocked(ProfilesService.renameProfile).mockResolvedValue({+ name: "new-name",+ message: "Profile renamed",+ });++ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");++ const { result } = renderHook(() => useRenameLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "old-name",+ newName: "new-name",+ });+ });++ expect(invalidateCacheSpy).toHaveBeenCalled();+ });+});diff --git a/__tests__/hooks/mutation/use-save-llm-profile.test.tsx b/__tests__/hooks/mutation/use-save-llm-profile.test.tsxnew file mode 100644index 0000000000..7ea91ab06b--- /dev/null+++ b/__tests__/hooks/mutation/use-save-llm-profile.test.tsx@@ -0,0 +1,138 @@+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 { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import { LLM_PROFILES_QUERY_KEYS, SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";++vi.mock("#/api/profiles-service/profiles-service.api");+vi.mock("#/api/settings-service/settings-service.api");++describe("useSaveLlmProfile", () => {+ 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 ProfilesService.saveProfile with name and request", async () => {+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue({+ name: "my-profile",+ message: "Profile saved",+ });++ const { result } = renderHook(() => useSaveLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "my-profile",+ request: {+ llm: {+ model: "openai/gpt-4",+ api_key: "sk-xxx",+ },+ },+ });+ });++ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("my-profile", {+ llm: {+ model: "openai/gpt-4",+ api_key: "sk-xxx",+ },+ });+ });++ it("saves profile with include_secrets flag", async () => {+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue({+ name: "snapshot-profile",+ message: "Profile saved",+ });++ const { result } = renderHook(() => useSaveLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "snapshot-profile",+ request: {+ llm: { model: "openai/gpt-4" },+ include_secrets: true,+ },+ });+ });++ expect(ProfilesService.saveProfile).toHaveBeenCalledWith("snapshot-profile", {+ llm: { model: "openai/gpt-4" },+ include_secrets: true,+ });+ });++ it("invalidates all relevant caches on success", async () => {+ vi.mocked(ProfilesService.saveProfile).mockResolvedValue({+ name: "test-profile",+ message: "Profile saved",+ });++ // Pre-populate the profiles cache+ queryClient.setQueryData(LLM_PROFILES_QUERY_KEYS.all, { profiles: [] });+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");+ const invalidateCacheSpy = vi.spyOn(SettingsService, "invalidateCache");++ const { result } = renderHook(() => useSaveLlmProfile(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({+ name: "test-profile",+ request: { llm: { model: "openai/gpt-4" } },+ });+ });++ // Verifies all three cache invalidations occur on success+ expect(invalidateCacheSpy).toHaveBeenCalled();+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: SETTINGS_QUERY_KEYS.personal(),+ });+ });++ it("handles save errors", async () => {+ const error = new Error("Profile name already exists");+ vi.mocked(ProfilesService.saveProfile).mockRejectedValue(error);++ const { result } = renderHook(() => useSaveLlmProfile(), { wrapper });++ await expect(+ act(async () => {+ await result.current.mutateAsync({+ name: "duplicate-name",+ request: { llm: { model: "openai/gpt-4" } },+ });+ }),+ ).rejects.toThrow("Profile name already exists");++ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });+ });+});diff --git a/__tests__/hooks/query/use-llm-profiles.test.tsx b/__tests__/hooks/query/use-llm-profiles.test.tsxnew file mode 100644index 0000000000..81f0a45201--- /dev/null+++ b/__tests__/hooks/query/use-llm-profiles.test.tsx@@ -0,0 +1,267 @@+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 {+ useLlmProfiles,+ LLM_PROFILES_QUERY_KEYS,+} from "#/hooks/query/use-llm-profiles";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import type { Backend } from "#/api/backend-registry/types";++vi.mock("#/api/profiles-service/profiles-service.api");++const localBackend1: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:8000",+ apiKey: "session-key",+ kind: "local",+};++const localBackend2: Backend = {+ id: "local-2",+ name: "Local 2",+ host: "http://localhost:9000",+ apiKey: "session-key-2",+ kind: "local",+};++describe("useLlmProfiles", () => {+ let queryClient: QueryClient;+ let wrapper: ({+ children,+ }: {+ children: React.ReactNode;+ }) => React.ReactElement;++ beforeEach(() => {+ __resetActiveStoreForTests();+ setRegisteredBackends([localBackend1, localBackend2]);+ setActiveSelection({ backendId: localBackend1.id, orgId: null });++ queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ });+ wrapper = ({ children }: { children: React.ReactNode }) =>+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(ActiveBackendProvider, null, children),+ );+ });++ afterEach(() => {+ queryClient.clear();+ vi.clearAllMocks();+ __resetActiveStoreForTests();+ });++ it("fetches profiles from ProfilesService.listProfiles", async () => {+ const mockProfiles = {+ profiles: [+ {+ name: "profile-1",+ model: "openai/gpt-4",+ base_url: null,+ api_key_set: true,+ },+ {+ name: "profile-2",+ model: "anthropic/claude-3",+ base_url: null,+ api_key_set: false,+ },+ ],+ active_profile: "profile-1",+ };++ vi.mocked(ProfilesService.listProfiles).mockResolvedValue(mockProfiles);++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ expect(ProfilesService.listProfiles).toHaveBeenCalledTimes(1);+ expect(result.current.data).toEqual(mockProfiles);+ expect(result.current.data?.profiles).toHaveLength(2);+ });++ it("includes backend.id and orgId in query key for cache isolation", async () => {+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_profile: null,+ });++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ const queries = queryClient.getQueryCache().findAll({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(queries).toHaveLength(1);+ // Verify full query key includes backend.id and orgId+ expect(queries[0].queryKey).toEqual([+ ...LLM_PROFILES_QUERY_KEYS.all,+ localBackend1.id,+ null, // orgId+ ]);+ });++ it("creates separate cache entries when switching backends", async () => {+ const profilesBackend1 = {+ profiles: [+ {+ name: "profile-backend-1",+ model: "openai/gpt-4",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: null,+ };+ const profilesBackend2 = {+ profiles: [+ {+ name: "profile-backend-2",+ model: "anthropic/claude-3",+ base_url: null,+ api_key_set: true,+ },+ ],+ active_profile: null,+ };++ vi.mocked(ProfilesService.listProfiles)+ .mockResolvedValueOnce(profilesBackend1)+ .mockResolvedValueOnce(profilesBackend2);++ // Fetch profiles for backend 1+ const { result, rerender } = renderHook(() => useLlmProfiles(), {+ wrapper,+ });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });+ expect(result.current.data?.profiles[0].name).toBe("profile-backend-1");++ // Switch to backend 2+ act(() => {+ setActiveSelection({ backendId: localBackend2.id, orgId: null });+ });+ rerender();++ await waitFor(() => {+ expect(result.current.data?.profiles[0].name).toBe("profile-backend-2");+ });++ // Verify we have 2 separate cache entries+ const queries = queryClient.getQueryCache().findAll({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(queries).toHaveLength(2);++ // Verify each has the correct backend.id in the query key+ const queryKeys = queries.map((q) => q.queryKey);+ expect(queryKeys).toContainEqual([+ ...LLM_PROFILES_QUERY_KEYS.all,+ localBackend1.id,+ null,+ ]);+ expect(queryKeys).toContainEqual([+ ...LLM_PROFILES_QUERY_KEYS.all,+ localBackend2.id,+ null,+ ]);+ });++ it("has staleTime of 5 minutes", async () => {+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_profile: null,+ });++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ const queries = queryClient.getQueryCache().findAll({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(queries).toHaveLength(1);+ expect((queries[0].options as Record<string, unknown>).staleTime).toBe(+ 1000 * 60 * 5,+ );+ });++ it("has gcTime of 15 minutes", async () => {+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_profile: null,+ });++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ const queries = queryClient.getQueryCache().findAll({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect(queries).toHaveLength(1);+ expect(queries[0].options.gcTime).toBe(1000 * 60 * 15);+ });++ it("disables toast notifications via meta", async () => {+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({+ profiles: [],+ active_profile: null,+ });++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ const queries = queryClient.getQueryCache().findAll({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ expect((queries[0].options as Record<string, unknown>).meta).toEqual({+ disableToast: true,+ });+ });++ it("handles API errors gracefully", async () => {+ const error = new Error("Network error");+ vi.mocked(ProfilesService.listProfiles).mockRejectedValue(error);++ const { result } = renderHook(() => useLlmProfiles(), { wrapper });++ await waitFor(() => {+ expect(result.current.isError).toBe(true);+ });++ expect(result.current.error).toBe(error);+ expect(result.current.data).toBeUndefined();+ });+});diff --git a/__tests__/utils/derive-profile-name.test.ts b/__tests__/utils/derive-profile-name.test.tsnew file mode 100644index 0000000000..c1770fc5b4--- /dev/null+++ b/__tests__/utils/derive-profile-name.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from "vitest";+import {+ PROFILE_NAME_PATTERN,+ deriveProfileNameFromModel,+} from "#/utils/derive-profile-name";++describe("PROFILE_NAME_PATTERN", () => {+ it("matches valid profile names starting with alphanumeric", () => {+ expect(PROFILE_NAME_PATTERN.test("a")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("Z")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("0")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("9")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("gpt-4")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("claude_3.5")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("my-profile-name")).toBe(true);+ expect(PROFILE_NAME_PATTERN.test("Profile_With.Mixed-Chars")).toBe(true);+ });++ it("rejects empty strings", () => {+ expect(PROFILE_NAME_PATTERN.test("")).toBe(false);+ });++ it("rejects names starting with non-alphanumeric characters", () => {+ expect(PROFILE_NAME_PATTERN.test(".hidden")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("_underscore")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("-dash")).toBe(false);+ });++ it("rejects names with invalid characters", () => {+ expect(PROFILE_NAME_PATTERN.test("name with spaces")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("name/slash")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("name\\backslash")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("name:colon")).toBe(false);+ expect(PROFILE_NAME_PATTERN.test("name@at")).toBe(false);+ });++ it("rejects names longer than 64 characters", () => {+ const exactlyValid = "a".repeat(64);+ const tooLong = "a".repeat(65);+ expect(PROFILE_NAME_PATTERN.test(exactlyValid)).toBe(true);+ expect(PROFILE_NAME_PATTERN.test(tooLong)).toBe(false);+ });+});++describe("deriveProfileNameFromModel", () => {+ it("extracts model name after provider prefix", () => {+ expect(deriveProfileNameFromModel("openai/gpt-4")).toBe("gpt-4");+ expect(deriveProfileNameFromModel("anthropic/claude-3")).toBe("claude-3");+ expect(deriveProfileNameFromModel("google/gemini-pro")).toBe("gemini-pro");+ });++ it("handles nested provider paths", () => {+ expect(deriveProfileNameFromModel("together/meta-llama/Llama-3")).toBe(+ "Llama-3",+ );+ expect(deriveProfileNameFromModel("azure/openai/gpt-4-turbo")).toBe(+ "gpt-4-turbo",+ );+ });++ it("returns model string as-is if no slash present", () => {+ expect(deriveProfileNameFromModel("gpt-4")).toBe("gpt-4");+ expect(deriveProfileNameFromModel("claude")).toBe("claude");+ });++ it("sanitizes invalid characters to dashes", () => {+ expect(deriveProfileNameFromModel("provider/model with spaces")).toBe(+ "model-with-spaces",+ );+ expect(deriveProfileNameFromModel("provider/model:variant")).toBe(+ "model-variant",+ );+ });++ it("collapses consecutive dashes", () => {+ expect(deriveProfileNameFromModel("provider/model--name")).toBe(+ "model-name",+ );+ expect(deriveProfileNameFromModel("provider/model@@@name")).toBe(+ "model-name",+ );+ });++ it("removes leading and trailing dashes", () => {+ expect(deriveProfileNameFromModel("provider/-model-")).toBe("model");+ expect(deriveProfileNameFromModel("provider/--name--")).toBe("name");+ });++ it("prepends 'profile-' when result starts with non-alphanumeric", () => {+ expect(deriveProfileNameFromModel("provider/.hidden")).toBe(+ "profile-.hidden",+ );+ expect(deriveProfileNameFromModel("provider/_underscore")).toBe(+ "profile-_underscore",+ );+ });++ it("truncates result to 64 characters", () => {+ const longModelName = "a".repeat(100);+ const result = deriveProfileNameFromModel(`provider/${longModelName}`);+ expect(result.length).toBeLessThanOrEqual(64);+ expect(result).toBe("a".repeat(64));+ });++ it("removes trailing dashes after truncation", () => {+ // Create a model name that when truncated at 64 chars ends with a dash+ // 63 'a's + dash at position 64 + more chars that get truncated+ const model = "a".repeat(63) + "-" + "b".repeat(10);+ const result = deriveProfileNameFromModel(`provider/${model}`);+ expect(result.length).toBe(63); // Trailing dash removed+ expect(result.endsWith("-")).toBe(false);+ expect(result).toBe("a".repeat(63));+ });++ it("returns 'default-profile' for empty input", () => {+ expect(deriveProfileNameFromModel("")).toBe("default-profile");+ });++ it("returns 'default-profile' when model name sanitizes to empty string", () => {+ // Model names that only contain invalid characters+ expect(deriveProfileNameFromModel("provider/@@@")).toBe("default-profile");+ expect(deriveProfileNameFromModel("provider/---")).toBe("default-profile");+ expect(deriveProfileNameFromModel("provider/!!!")).toBe("default-profile");+ expect(deriveProfileNameFromModel("provider/ ")).toBe("default-profile");+ });++ it("handles trailing slash by falling back to full input", () => {+ // "provider/" splits to ["provider", ""], falls back to "provider/"+ // which sanitizes "/" to "-" then trims to "provider"+ expect(deriveProfileNameFromModel("provider/")).toBe("provider");+ // "/" splits to ["", ""], falls back to "/" which sanitizes to empty,+ // then returns "default-profile"+ expect(deriveProfileNameFromModel("/")).toBe("default-profile");+ });+});diff --git a/src/api/profiles-service/profiles-service.api.ts b/src/api/profiles-service/profiles-service.api.tsnew file mode 100644index 0000000000..788f2b0ba4--- /dev/null+++ b/src/api/profiles-service/profiles-service.api.ts@@ -0,0 +1,88 @@+/**+ * ProfilesService provides a thin wrapper around the SDK's ProfilesClient,+ * creating a client per-call to pick up current backend configuration.+ *+ * Uses ProfilesClient from @openhands/typescript-client v0.2.0+.+ * All types are re-exported from the SDK for consumer convenience.+ *+ * Note: Unlike some SDK clients, we don't call client.close() here for+ * consistency with other services (SettingsService, SecretsService) that+ * also create SDK clients without explicit cleanup. The SDK clients use+ * fetch-based HTTP which doesn't require connection cleanup.+ */+import {+ ProfilesClient,+ type GetProfileOptions,+} from "@openhands/typescript-client/clients";+import type {+ ProfileInfo,+ ProfileListResponse,+ ProfileDetailResponse,+ ProfileMutationResponse,+ ActivateProfileResponse,+ SaveProfileRequest,+ ExposeSecretsMode,+} from "@openhands/typescript-client";+import { getAgentServerClientOptions } from "../agent-server-client-options";++// Re-export SDK types for consumers+export type {+ ProfileInfo,+ ProfileListResponse,+ ProfileDetailResponse,+ ProfileMutationResponse,+ ActivateProfileResponse,+ SaveProfileRequest,+ ExposeSecretsMode,+};++class ProfilesService {+ static async listProfiles(): Promise<ProfileListResponse> {+ return new ProfilesClient(getAgentServerClientOptions()).listProfiles();+ }++ static async getProfile(+ name: string,+ exposeSecrets?: ExposeSecretsMode,+ ): Promise<ProfileDetailResponse> {+ const options: GetProfileOptions = exposeSecrets ? { exposeSecrets } : {};+ return new ProfilesClient(getAgentServerClientOptions()).getProfile(+ name,+ options,+ );+ }++ static async saveProfile(+ name: string,+ request: SaveProfileRequest,+ ): Promise<ProfileMutationResponse> {+ return new ProfilesClient(getAgentServerClientOptions()).saveProfile(+ name,+ request,+ );+ }++ static async deleteProfile(name: string): Promise<ProfileMutationResponse> {+ return new ProfilesClient(getAgentServerClientOptions()).deleteProfile(+ name,+ );+ }++ static async renameProfile(+ name: string,+ newName: string,+ ): Promise<ProfileMutationResponse> {+ return new ProfilesClient(getAgentServerClientOptions()).renameProfile(+ name,+ newName,+ );+ }++ static async activateProfile(name: string): Promise<ActivateProfileResponse> {+ return new ProfilesClient(getAgentServerClientOptions()).activateProfile(+ name,+ );+ }+}++export default ProfilesService;diff --git a/src/hooks/mutation/use-activate-llm-profile.ts b/src/hooks/mutation/use-activate-llm-profile.tsnew file mode 100644index 0000000000..710912953d--- /dev/null+++ b/src/hooks/mutation/use-activate-llm-profile.ts@@ -0,0 +1,30 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ LLM_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++export function useActivateLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: (name: string) => ProfilesService.activateProfile(name),+ onSuccess: async () => {+ // Invalidate the SettingsService internal cache so getSettingsForConversation+ // fetches fresh settings with the newly activated profile's LLM config+ SettingsService.invalidateCache();+ // Invalidate profiles list to refresh active_profile+ await queryClient.invalidateQueries({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ // Use personal() scope for consistency with other settings hooks+ 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-llm-profile.ts b/src/hooks/mutation/use-delete-llm-profile.tsnew file mode 100644index 0000000000..d4d1094579--- /dev/null+++ b/src/hooks/mutation/use-delete-llm-profile.ts@@ -0,0 +1,30 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ LLM_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++export function useDeleteLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: (name: string) => ProfilesService.deleteProfile(name),+ onSuccess: async () => {+ // Invalidate the SettingsService internal cache so getSettingsForConversation+ // fetches fresh settings after the profile is deleted (backend may have+ // deactivated it or reset agent_settings.llm)+ SettingsService.invalidateCache();+ await queryClient.invalidateQueries({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ // Use personal() scope for consistency with other settings hooks+ 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-rename-llm-profile.ts b/src/hooks/mutation/use-rename-llm-profile.tsnew file mode 100644index 0000000000..1a8059fc42--- /dev/null+++ b/src/hooks/mutation/use-rename-llm-profile.ts@@ -0,0 +1,35 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ LLM_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++interface RenameLlmProfileVariables {+ name: string;+ newName: string;+}++export function useRenameLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({ name, newName }: RenameLlmProfileVariables) =>+ ProfilesService.renameProfile(name, newName),+ onSuccess: async () => {+ // Invalidate SettingsService internal cache to ensure fresh settings+ // (backend references in agent_settings may change when renaming active profile)+ SettingsService.invalidateCache();+ await queryClient.invalidateQueries({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ // Use personal() scope for consistency with other settings hooks+ 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-llm-profile.ts b/src/hooks/mutation/use-save-llm-profile.tsnew file mode 100644index 0000000000..c63a35bb05--- /dev/null+++ b/src/hooks/mutation/use-save-llm-profile.ts@@ -0,0 +1,37 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import ProfilesService, {+ type SaveProfileRequest,+} from "#/api/profiles-service/profiles-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ LLM_PROFILES_QUERY_KEYS,+ SETTINGS_QUERY_KEYS,+} from "#/hooks/query/query-keys";++interface SaveLlmProfileVariables {+ name: string;+ request: SaveProfileRequest;+}++export function useSaveLlmProfile() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({ name, request }: SaveLlmProfileVariables) =>+ ProfilesService.saveProfile(name, request),+ onSuccess: async () => {+ // Invalidate SettingsService internal cache to ensure fresh settings+ // for new conversations (especially if saving the active profile)+ SettingsService.invalidateCache();+ await queryClient.invalidateQueries({+ queryKey: LLM_PROFILES_QUERY_KEYS.all,+ });+ // Use personal() scope for consistency with other settings hooks+ 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/query/query-keys.ts b/src/hooks/query/query-keys.tsindex d797d94cf4..6b45f8f899 100644--- a/src/hooks/query/query-keys.ts+++ b/src/hooks/query/query-keys.ts@@ -16,6 +16,10 @@ export const SETTINGS_QUERY_KEYS = {personal: () => ["settings", "personal"] as const,} as const;+export const LLM_PROFILES_QUERY_KEYS = {+ all: ["llm-profiles"] as const,+} as const;+/** Cache configuration shared across all config-related queries */export const CONFIG_CACHE_OPTIONS = {staleTime: 1000 * 60 * 5, // 5 minutesdiff --git a/src/hooks/query/use-llm-profiles.ts b/src/hooks/query/use-llm-profiles.tsnew file mode 100644index 0000000000..cb88e9c709--- /dev/null+++ b/src/hooks/query/use-llm-profiles.ts@@ -0,0 +1,18 @@+import { useQuery } from "@tanstack/react-query";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { CONFIG_CACHE_OPTIONS, LLM_PROFILES_QUERY_KEYS } from "./query-keys";++export { LLM_PROFILES_QUERY_KEYS };++export function useLlmProfiles() {+ const { backend, orgId } = useActiveBackend();++ return useQuery({+ // Include backend identity to prevent cache pollution when switching backends+ queryKey: [...LLM_PROFILES_QUERY_KEYS.all, backend.id, orgId],+ queryFn: ProfilesService.listProfiles,+ ...CONFIG_CACHE_OPTIONS,+ meta: { disableToast: true },+ });+}diff --git a/src/utils/derive-profile-name.ts b/src/utils/derive-profile-name.tsnew file mode 100644index 0000000000..5a9b26eec6--- /dev/null+++ b/src/utils/derive-profile-name.ts@@ -0,0 +1,36 @@+/**+ * Profile name validation pattern.+ * Profile names: 1-64 chars, must start with alphanumeric, then alphanumerics+ * or '.', '_', '-'. Blocks empty names, path separators, leading dots+ * (hidden files / path traversal), and shell-special characters.+ */+export const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;++/**+ * Derive a profile name from a model string.+ * Extracts the model portion after the provider prefix (e.g., "openai/gpt-4" -> "gpt-4")+ * and sanitizes it to match the profile name pattern.+ */+export function deriveProfileNameFromModel(model: string): string {+ // Extract the model name after the last slash (provider/model format)+ const parts = model.split("/");+ const modelName = parts[parts.length - 1] || model;++ // Sanitize: replace invalid characters with dashes+ let sanitized = modelName+ .replace(/[^A-Za-z0-9._-]/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-+|-+$/g, "");++ // Ensure it starts with alphanumeric+ if (sanitized && !/^[A-Za-z0-9]/.test(sanitized)) {+ sanitized = `profile-${sanitized}`;+ }++ // Truncate to 64 characters+ if (sanitized.length > 64) {+ sanitized = sanitized.substring(0, 64).replace(/-+$/, "");+ }++ return sanitized || "default-profile";+}