π OpenHands: AI-Driven Development
fix(frontend): hydrate the LLM profile edit form from the selected profile (#14789)
Alonaba615cadac54
diff --git a/enterprise/server/routes/org_profiles.py b/enterprise/server/routes/org_profiles.pyindex 398fa3e198..6150a19684 100644--- a/enterprise/server/routes/org_profiles.py+++ b/enterprise/server/routes/org_profiles.py@@ -37,6 +37,7 @@ from openhands.app_server.settings.settings_models import ()from openhands.app_server.utils.llm import MASKED_API_KEY, is_openhands_modelfrom openhands.app_server.utils.logger import openhands_logger as logger+from openhands.sdk.llm import LLMfrom ..auth.authorization import Permission, require_permission@@ -89,6 +90,9 @@ class SaveProfileRequest(BaseModel):include_secrets: bool = Truellm: StrictLLM | None = None+ # Set when the caller has no new key (UI key field left blank), so an+ # existing profile's stored key survives instead of the snapshotted one.+ preserve_existing_api_key: bool = Falseclass RenameProfileRequest(BaseModel):@@ -211,19 +215,26 @@ async def save_profile(If ``llm`` is omitted, saves a copy of the current org LLM defaults."""async with _org_profiles_transaction(org_id, user_id) as (_session, org, profiles):+ existing = profiles.get(name)+ llm: LLM+ if request.llm is not None:+ llm = request.llm+ # Preserve the stored api_key when an update omits it (e.g. a+ # round-tripped GET response) β mirrors the personal profiles route.+ if llm.api_key is None and existing is not None:+ if existing.api_key is not None:+ llm = llm.model_copy(update={'api_key': existing.api_key})+ else:+ # Snapshot current org LLM settings. Route through the persisted+ # loader so legacy/canonical ``agent_kind`` discriminator values+ # ('llm' vs 'openhands') both validate.+ llm = _load_persisted_agent_settings(org.agent_settings).llm+ if request.preserve_existing_api_key and existing is not None:+ # Caller has no new key: keep the profile's stored key (even "no+ # key") instead of the snapshotted one.+ llm = llm.model_copy(update={'api_key': existing.api_key})try:- if request.llm is not None:- profiles.save(- name, request.llm, include_secrets=request.include_secrets- )- else:- # Snapshot current org LLM settings. Route through the persisted- # loader so legacy/canonical ``agent_kind`` discriminator values- # ('llm' vs 'openhands') both validate.- agent_settings = _load_persisted_agent_settings(org.agent_settings)- profiles.save(- name, agent_settings.llm, include_secrets=request.include_secrets- )+ profiles.save(name, llm, include_secrets=request.include_secrets)except ProfileLimitExceededError as exc:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))diff --git a/enterprise/tests/unit/test_org_profiles.py b/enterprise/tests/unit/test_org_profiles.pyindex 8bdfa4a5a5..fd18bafad6 100644--- a/enterprise/tests/unit/test_org_profiles.py+++ b/enterprise/tests/unit/test_org_profiles.py@@ -397,6 +397,172 @@ class TestProfileErrorPaths:assert exc.value.status_code == 404+async def _set_org_agent_settings(async_session_maker, org_id, agent_settings):+ async with async_session_maker() as session:+ result = await session.execute(select(Org).where(Org.id == org_id))+ org = result.scalars().first()+ org.agent_settings = agent_settings+ await session.commit()+++class TestSaveApiKeyPreservation:+ """No-new-key saves must not clobber a profile's stored api_key."""++ @pytest.mark.asyncio+ async def test_snapshot_save_with_preserve_flag_keeps_existing_key(+ self, async_session_maker, patch_route_db+ ):+ """The UI edit-save snapshots org defaults (active key included);+ the flag keeps the profile's own key while the snapshot's model lands.+ """+ org_id = patch_route_db+ await _set_org_agent_settings(+ async_session_maker,+ org_id,+ {'llm': {'model': 'openai/gpt-4o', 'api_key': 'org-active-key'}},+ )+ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(+ model='anthropic/claude-3-5-sonnet', api_key='profile-key'+ )+ ),+ user_id=str(ADMIN_USER_ID),+ )++ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(preserve_existing_api_key=True),+ user_id=str(ADMIN_USER_ID),+ )++ org = await _read_org(async_session_maker, org_id)+ saved = _load_profiles(org).get('work')+ assert saved.model == 'openai/gpt-4o'+ assert saved.api_key.get_secret_value() == 'profile-key'++ @pytest.mark.asyncio+ async def test_snapshot_save_without_flag_keeps_snapshot_key(+ self, async_session_maker, patch_route_db+ ):+ """Counter-test: a plain snapshot save still captures the org key."""+ org_id = patch_route_db+ await _set_org_agent_settings(+ async_session_maker,+ org_id,+ {'llm': {'model': 'openai/gpt-4o', 'api_key': 'org-active-key'}},+ )+ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(+ model='anthropic/claude-3-5-sonnet', api_key='profile-key'+ )+ ),+ user_id=str(ADMIN_USER_ID),+ )++ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(),+ user_id=str(ADMIN_USER_ID),+ )++ org = await _read_org(async_session_maker, org_id)+ saved = _load_profiles(org).get('work')+ assert saved.api_key.get_secret_value() == 'org-active-key'++ @pytest.mark.asyncio+ async def test_snapshot_save_with_preserve_flag_keeps_profile_keyless(+ self, async_session_maker, patch_route_db+ ):+ """A keyless profile must not silently inherit the org's active key."""+ org_id = patch_route_db+ await _set_org_agent_settings(+ async_session_maker,+ org_id,+ {'llm': {'model': 'openai/gpt-4o', 'api_key': 'org-active-key'}},+ )+ await save_profile(+ org_id=org_id,+ name='keyless',+ request=SaveProfileRequest(llm=StrictLLM(model='openai/gpt-4o')),+ user_id=str(ADMIN_USER_ID),+ )++ await save_profile(+ org_id=org_id,+ name='keyless',+ request=SaveProfileRequest(preserve_existing_api_key=True),+ user_id=str(ADMIN_USER_ID),+ )++ org = await _read_org(async_session_maker, org_id)+ assert _load_profiles(org).get('keyless').api_key is None++ @pytest.mark.asyncio+ async def test_explicit_llm_without_key_preserves_stored_key(+ self, async_session_maker, patch_route_db+ ):+ """GETβeditβPOST round-trips null the key; the update must keep the+ stored one (parity with the personal profiles route)."""+ org_id = patch_route_db+ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(model='openai/gpt-4o', api_key='stored-key')+ ),+ user_id=str(ADMIN_USER_ID),+ )++ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(model='anthropic/claude-3-5-sonnet')+ ),+ user_id=str(ADMIN_USER_ID),+ )++ org = await _read_org(async_session_maker, org_id)+ saved = _load_profiles(org).get('work')+ assert saved.model == 'anthropic/claude-3-5-sonnet'+ assert saved.api_key.get_secret_value() == 'stored-key'++ @pytest.mark.asyncio+ async def test_explicit_llm_with_new_key_replaces_stored_key(+ self, async_session_maker, patch_route_db+ ):+ """Counter-test: an intentionally supplied key still wins."""+ org_id = patch_route_db+ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(model='openai/gpt-4o', api_key='old-key')+ ),+ user_id=str(ADMIN_USER_ID),+ )++ await save_profile(+ org_id=org_id,+ name='work',+ request=SaveProfileRequest(+ llm=StrictLLM(model='openai/gpt-4o', api_key='new-key')+ ),+ user_id=str(ADMIN_USER_ID),+ )++ org = await _read_org(async_session_maker, org_id)+ assert _load_profiles(org).get('work').api_key.get_secret_value() == 'new-key'++class TestActivateTransactionAtomicity:"""Activate must commit the org marker and the member diff together."""diff --git a/frontend/__tests__/routes/llm-settings.test.tsx b/frontend/__tests__/routes/llm-settings.test.tsxindex bfb183f61c..39f9f967c2 100644--- a/frontend/__tests__/routes/llm-settings.test.tsx+++ b/frontend/__tests__/routes/llm-settings.test.tsx@@ -6,7 +6,9 @@ import { MemoryRouter } from "react-router";import OrgProfilesService from "#/api/organization-service/org-profiles-service.api";import { organizationService } from "#/api/organization-service/organization-service.api";-import ProfilesService from "#/api/settings-service/profiles-service.api";+import ProfilesService, {+ LlmProfileSummary,+} from "#/api/settings-service/profiles-service.api";import SettingsService from "#/api/settings-service/settings-service.api";import {MOCK_DEFAULT_USER_SETTINGS,@@ -238,6 +240,30 @@ function getPayloadAgentSettings(return (payload.agent_settings_diff as Record<string, unknown>) ?? {};}+// Read the mocked settings through the spy's implementation directly so the+// helper can mirror them into the seeded profile without bumping the+// getSettings call counts that several tests pin.+async function readMockedActiveSettings(+ scope: "personal" | "org",+): Promise<Settings | null> {+ const settingsFn =+ scope === "org"+ ? organizationService.getOrganizationSettings+ : SettingsService.getSettings;+ if (!vi.isMockFunction(settingsFn)) return null;+ const impl = settingsFn.getMockImplementation();+ if (!impl) return null;+ try {+ return (+ ((await (impl as (orgId?: string) => Promise<unknown>)(+ "1",+ )) as Settings) ?? null+ );+ } catch {+ return null;+ }+}+async function renderLlmSettingsScreen({appMode = "oss",organizationId = "1",@@ -245,6 +271,7 @@ async function renderLlmSettingsScreen({organizations,scope = "personal",view = "form",+ profile,}: {appMode?: "oss" | "saas";organizationId?: string;@@ -253,11 +280,15 @@ async function renderLlmSettingsScreen({scope?: "personal" | "org";// Profile-enabled scopes land on the Available Models list by default; set// ``view`` to ``"form"`` (the default) to auto-click into the SDK form via- // Edit on a seeded active profile β the form then hydrates from the mocked- // settings, so existing form-oriented assertions keep working unchanged.+ // Edit on a seeded active profile. The seeded profile mirrors the mocked+ // settings, so the (now profile-hydrated) edit form keeps showing the same+ // values as before and existing form-oriented assertions keep working.// ``"create"`` clicks Add Profile instead (blank create form), and// ``"profiles"`` tests the list view itself.view?: "form" | "create" | "profiles";+ // Override fields on the seeded edit profile when a test needs it to+ // *differ* from the active settings.+ profile?: Partial<LlmProfileSummary>;} = {}) {const queryClient = new QueryClient({defaultOptions: {@@ -286,14 +317,27 @@ async function renderLlmSettingsScreen({}if (view === "form") {- // One active profile to Edit into. Its name matches the model-derived- // default for the mocked settings, so auto-profile assertions that- // expect the derived name keep working under the edit flow.- const seededProfile = {+ // One active profile to Edit into, mirroring the mocked settings so+ // the profile-hydrated edit form shows the same values the+ // settings-hydrated form used to. The name stays fixed so auto-profile+ // assertions that expect a derived name keep working.+ const activeSettings = await readMockedActiveSettings(scope);+ const activeLlm = (activeSettings?.agent_settings?.llm ?? {}) as Record<+ string,+ unknown+ >;+ const seededProfile: LlmProfileSummary = {name: "openai_gpt-4o",- model: "openai/gpt-4o",- base_url: null,- api_key_set: false,+ model:+ ((activeLlm.model as string | undefined) ??+ activeSettings?.llm_model) ||+ null,+ base_url:+ ((activeLlm.base_url as string | undefined) ??+ activeSettings?.llm_base_url) ||+ null,+ api_key_set: activeSettings?.llm_api_key_set ?? false,+ ...profile,};vi.mocked(ProfilesService.listProfiles).mockResolvedValue({profiles: [seededProfile],@@ -1013,7 +1057,9 @@ describe("LlmSettingsScreen", () => {string,unknown>;- expect(llmPayload).not.toHaveProperty("base_url");+ // Edit-save now persists the profile-hydrated base_url explicitly+ // (instead of omitting it), preserving the existing custom value.+ expect(llmPayload.base_url).toBe("https://custom.example/v1");expect(getPayloadAgentSettings(payload)).not.toHaveProperty("agent");});@@ -1386,7 +1432,9 @@ describe("LlmSettingsScreen", () => {const llmPayload = (payload.settings.agent_settings_diff as Record<string, unknown>).llm as Record<string, unknown>;- expect(llmPayload).not.toHaveProperty("base_url");+ // Edit-save now persists the profile-hydrated base_url explicitly+ // (instead of omitting it), preserving the existing custom value.+ expect(llmPayload.base_url).toBe("https://custom.example/v1");expect(payload.settings).not.toHaveProperty("search_api_key");await waitFor(() => {@@ -1487,7 +1535,9 @@ describe("LlmSettingsScreen", () => {string,unknown>;- expect(llmPayload).not.toHaveProperty("base_url");+ // Edit-save now persists the profile-hydrated base_url explicitly+ // (instead of omitting it), preserving the existing custom value.+ expect(llmPayload.base_url).toBe("https://stale.example/v1");await waitFor(() => {expect(getSettingsSpy).toHaveBeenCalledTimes(2);@@ -2406,7 +2456,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(ProfilesService.saveProfile).toHaveBeenCalledWith("openai_gpt-4o",- { include_secrets: true },+ { include_secrets: true, preserve_existing_api_key: false },);});await waitFor(() => {@@ -2416,6 +2466,72 @@ describe("LlmSettingsScreen", () => {});});+ it("asks the backend to preserve the stored profile key when no key is typed", async () => {+ // A save with a blank key field must not snapshot the active settings'+ // api_key into the profile β that silently swaps the profile's own key.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openai/gpt-4o",+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);++ await renderLlmSettingsScreen({ appMode: "oss" });++ await screen.findByTestId("llm-api-key-input");+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith(+ "openai_gpt-4o",+ { include_secrets: true, preserve_existing_api_key: true },+ );+ });+ });++ it("asks the backend to preserve the stored org profile key when no key is typed", async () => {+ vi.spyOn(+ organizationService,+ "getOrganizationSettings",+ ).mockResolvedValue(+ buildSettings({+ agent_settings: { llm: { model: "openai/gpt-4o" } },+ }),+ );+ vi.spyOn(+ organizationService,+ "saveOrganizationSettings",+ ).mockResolvedValue({+ agent_settings: {},+ conversation_settings: {},+ search_api_key: undefined,+ llm_api_key_set: false,+ });++ await renderLlmSettingsScreen({+ appMode: "saas",+ scope: "org",+ organizationId: "3",+ meData: buildOrganizationMember({ org_id: "3", role: "admin" }),+ });++ const orgProfileNameInput = await screen.findByTestId(+ "llm-profile-name-input",+ );+ await userEvent.clear(orgProfileNameInput);+ await userEvent.type(orgProfileNameInput, "team-profile");+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(OrgProfilesService.saveProfile).toHaveBeenCalledWith(+ "3",+ "team-profile",+ { include_secrets: true, preserve_existing_api_key: true },+ );+ });+ });+it("saves + activates an org profile on the org-default settings screen", async () => {vi.spyOn(organizationService,@@ -2460,7 +2576,7 @@ describe("LlmSettingsScreen", () => {expect(OrgProfilesService.saveProfile).toHaveBeenCalledWith("3","team-profile",- { include_secrets: true },+ { include_secrets: true, preserve_existing_api_key: false },);});await waitFor(() => {@@ -2498,7 +2614,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(ProfilesService.saveProfile).toHaveBeenCalledWith("my-custom-name",- { include_secrets: true },+ { include_secrets: true, preserve_existing_api_key: false },);});await waitFor(() => {@@ -2537,7 +2653,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(ProfilesService.saveProfile).toHaveBeenCalledWith("openai_gpt-4o",- { include_secrets: true },+ { include_secrets: true, preserve_existing_api_key: false },);});});@@ -2752,7 +2868,7 @@ describe("LlmSettingsScreen", () => {await waitFor(() => {expect(ProfilesService.saveProfile).toHaveBeenCalledWith("openai_gpt-4o",- { include_secrets: true },+ { include_secrets: true, preserve_existing_api_key: false },);});await waitFor(() => {@@ -2787,6 +2903,182 @@ describe("LlmSettingsScreen", () => {expect(screen.getByTestId("base-url-input")).toHaveValue("");});+ it("hydrates the edit form from a non-active profile instead of the active settings", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openhands/claude-opus-4-5-20251101",+ agent_settings: {+ llm: { model: "openhands/claude-opus-4-5-20251101" },+ },+ }),+ );+ const saveSettingsSpy = vi+ .spyOn(SettingsService, "saveSettings")+ .mockResolvedValue(true);+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({+ profiles: [+ {+ name: "active-profile",+ model: "openhands/claude-opus-4-5-20251101",+ base_url: null,+ api_key_set: false,+ },+ {+ name: "other-profile",+ model: "openai/gpt-4o-mini",+ base_url: null,+ api_key_set: false,+ },+ ],+ active_profile: "active-profile",+ });++ await renderLlmSettingsScreen({ appMode: "oss", view: "profiles" });++ const triggers = await screen.findAllByTestId("profile-menu-trigger");+ await userEvent.click(triggers[1]);+ await userEvent.click(await screen.findByTestId("profile-edit"));++ await screen.findByTestId("llm-settings-form-basic");+ await waitFor(() => {+ expect(screen.getByTestId("llm-provider-input")).toHaveValue("OpenAI");+ expect(screen.getByTestId("llm-model-input")).toHaveValue(+ "gpt-4o-mini",+ );+ });++ // Saving without changes must persist the edited profile's values+ // instead of snapshotting the active settings over it.+ await userEvent.click(screen.getByTestId("save-button"));+ await waitFor(() => {+ expect(saveSettingsSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ agent_settings_diff: expect.objectContaining({+ llm: expect.objectContaining({ model: "openai/gpt-4o-mini" }),+ }),+ }),+ );+ });+ await waitFor(() => {+ expect(ProfilesService.saveProfile).toHaveBeenCalledWith(+ "other-profile",+ // No key typed on this pristine edit-save, so the profile's+ // stored key must survive the snapshot.+ { include_secrets: true, preserve_existing_api_key: true },+ );+ });+ });++ it("opens edit on advanced with the profile's custom base URL while the active settings are plain", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ llm_model: "openhands/claude-opus-4-5-20251101",+ agent_settings: {+ llm: { model: "openhands/claude-opus-4-5-20251101" },+ },+ }),+ );++ await renderLlmSettingsScreen({+ appMode: "oss",+ profile: {+ name: "proxy-profile",+ model: "litellm_proxy/custom-model",+ base_url: "https://proxy.example/v1",+ api_key_set: true,+ },+ });++ await screen.findByTestId("llm-settings-form-advanced");+ expect(screen.getByTestId("llm-custom-model-input")).toHaveValue(+ "litellm_proxy/custom-model",+ );+ expect(screen.getByTestId("base-url-input")).toHaveValue(+ "https://proxy.example/v1",+ );+ // The set-but-hidden key indicator mirrors the profile, not the+ // active settings (whose llm_api_key_set is false here).+ expect(screen.getByTestId("llm-api-key-input")).toHaveAttribute(+ "placeholder",+ "<hidden>",+ );+ });++ it("opens edit on basic for a plain profile while the active settings have a custom base URL", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ settingsWithCustomModelAndBaseUrl(),+ );++ await renderLlmSettingsScreen({+ appMode: "oss",+ profile: {+ name: "plain-profile",+ model: "openai/gpt-4o",+ base_url: null,+ },+ });++ await screen.findByTestId("llm-settings-form-basic");+ expect(+ screen.queryByTestId("llm-settings-form-advanced"),+ ).not.toBeInTheDocument();+ await waitFor(() => {+ expect(screen.getByTestId("llm-provider-input")).toHaveValue("OpenAI");+ expect(screen.getByTestId("llm-model-input")).toHaveValue("gpt-4o");+ });+ });++ it("hydrates the org edit form from a non-active org profile", async () => {+ vi.spyOn(+ organizationService,+ "getOrganizationSettings",+ ).mockResolvedValue(+ buildSettings({+ llm_model: "openhands/claude-opus-4-5-20251101",+ agent_settings: {+ llm: { model: "openhands/claude-opus-4-5-20251101" },+ },+ }),+ );+ vi.mocked(OrgProfilesService.listProfiles).mockResolvedValue({+ profiles: [+ {+ name: "org-active",+ model: "openhands/claude-opus-4-5-20251101",+ base_url: null,+ api_key_set: false,+ },+ {+ name: "org-other",+ model: "openai/gpt-4o-mini",+ base_url: null,+ api_key_set: false,+ },+ ],+ active_profile: "org-active",+ });++ await renderLlmSettingsScreen({+ appMode: "saas",+ scope: "org",+ organizationId: "3",+ meData: buildOrganizationMember({ org_id: "3", role: "admin" }),+ view: "profiles",+ });++ const triggers = await screen.findAllByTestId("profile-menu-trigger");+ await userEvent.click(triggers[1]);+ await userEvent.click(await screen.findByTestId("profile-edit"));++ await screen.findByTestId("llm-settings-form-basic");+ await waitFor(() => {+ expect(screen.getByTestId("llm-provider-input")).toHaveValue("OpenAI");+ expect(screen.getByTestId("llm-model-input")).toHaveValue(+ "gpt-4o-mini",+ );+ });+ });+it("still opens the edit form on advanced view with stored values for a profile with custom fields", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(settingsWithCustomModelAndBaseUrl(),diff --git a/frontend/src/api/organization-service/org-profiles-service.api.ts b/frontend/src/api/organization-service/org-profiles-service.api.tsindex dce728584f..f951bbd19b 100644--- a/frontend/src/api/organization-service/org-profiles-service.api.ts+++ b/frontend/src/api/organization-service/org-profiles-service.api.ts@@ -14,6 +14,9 @@ interface OrgLlmProfileListResponse {export interface SaveOrgLlmProfileRequest {include_secrets?: boolean;+ // True when the user typed no new key, so the backend keeps the profile's+ // stored key instead of snapshotting the active settings' key.+ preserve_existing_api_key?: boolean;llm?: {model: string;base_url?: string | null;diff --git a/frontend/src/api/settings-service/profiles-service.api.ts b/frontend/src/api/settings-service/profiles-service.api.tsindex d7d9cdca37..8b7ffaa3fb 100644--- a/frontend/src/api/settings-service/profiles-service.api.ts+++ b/frontend/src/api/settings-service/profiles-service.api.ts@@ -15,6 +15,9 @@ interface LlmProfileListResponse {export interface SaveLlmProfileRequest {include_secrets?: boolean;+ // True when the user typed no new key, so the backend keeps the profile's+ // stored key instead of snapshotting the active settings' key.+ preserve_existing_api_key?: boolean;llm?: {model: string;base_url?: string | null;diff --git a/frontend/src/routes/llm-settings.tsx b/frontend/src/routes/llm-settings.tsxindex c6e3267c4f..ddb1c7c108 100644--- a/frontend/src/routes/llm-settings.tsx+++ b/frontend/src/routes/llm-settings.tsx@@ -28,6 +28,7 @@ import {type SettingsView,} from "#/utils/sdk-settings-schema";import { DEFAULT_SETTINGS } from "#/services/settings";+import { LlmProfileSummary } from "#/api/settings-service/profiles-service.api";import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";import { useActivateLlmProfile } from "#/hooks/mutation/use-activate-llm-profile";import { useRenameLlmProfile } from "#/hooks/mutation/use-rename-llm-profile";@@ -127,6 +128,9 @@ export function LlmSettingsScreen({// Captured during buildPayload so onSaveSuccess can derive a profile name// from the exact model that was just persisted.const lastSavedModelRef = React.useRef<string | null>(null);+ // Whether the user typed a new API key this save β drives the backend's+ // preserve_existing_api_key so a blank key field keeps the profile's key.+ const lastSavedApiKeyTypedRef = React.useRef(false);// Personal profile hooks (for OSS mode)const saveProfile = useSaveLlmProfile();@@ -154,9 +158,13 @@ export function LlmSettingsScreen({// previous Add doesn't leak in.const [profileName, setProfileName] = React.useState("");// Distinguishes Add Profile (blank create form, opens on basic) from Edit- // (form hydrated from the persisted settings). Null when no form is open.+ // (form hydrated from the clicked profile). Null when no form is open.const [profileFormMode, setProfileFormMode] =React.useState<ProfileFormMode | null>(null);+ // The profile summary the edit form was opened with β the source of truth+ // for the form's initial model/base_url instead of the active settings.+ const [editingProfile, setEditingProfile] =+ React.useState<LlmProfileSummary | null>(null);// Snapshotted on form open so we can flag the form dirty when the user// edits *only* the name β the SDK section page tracks the LLM fields but// not the profile-name input that lives outside its schema.@@ -179,9 +187,9 @@ export function LlmSettingsScreen({const isSaasMode = config?.app_mode === "saas";React.useEffect(() => {- // A freshly opened Add Profile form starts blank β don't let the active- // settings re-select a provider underneath it.- if (profileFormMode === "create" && !showProfiles) {+ // An open profile form owns the provider selection (blank for create,+ // profile-derived for edit) β don't let the active settings override it.+ if (profileFormMode !== null && !showProfiles) {return;}if (settings?.llm_model) {@@ -220,6 +228,17 @@ export function LlmSettingsScreen({return initialViewHint;}+ // Edit opens on the tier the clicked profile needs β its values, not+ // the active settings, are what the form is hydrated with.+ if (profileFormMode === "edit" && editingProfile) {+ const profileModel = editingProfile.model ?? "";+ const profileBaseUrl = editingProfile.base_url?.trim() ?? "";+ const hasCustomProfileBaseUrl =+ profileBaseUrl.length > 0 &&+ !isProviderDefaultBaseUrl(profileModel, profileBaseUrl);+ return hasCustomProfileBaseUrl ? "advanced" : "basic";+ }+// Personal SaaS users now land on Available Models first; the form// is mounted on-demand (Add / Edit). The first form mount per session// should still default to basic so users aren't dropped straight into@@ -253,7 +272,7 @@ export function LlmSettingsScreen({return hasCustomBaseUrl ? "all" : "basic";},- [initialViewHint, isSaasMode, profileFormMode, scope],+ [editingProfile, initialViewHint, isSaasMode, profileFormMode, scope],);const buildHeader = React.useCallback(@@ -274,6 +293,12 @@ export function LlmSettingsScreen({const shouldUseOpenHandsKey =isSaasMode && activeProvider === "openhands";const showOpenHandsApiKeyHelp = modelValue.startsWith("openhands/");+ // While editing, the set-but-unfetchable key indicator must reflect+ // the clicked profile, not whichever profile is currently active.+ const apiKeySet =+ profileFormMode === "edit" && editingProfile+ ? editingProfile.api_key_set+ : settings?.llm_api_key_set;const renderApiKeyInput = (testId: string, helpTestId: string) => {if (shouldUseOpenHandsKey) {@@ -292,13 +317,11 @@ export function LlmSettingsScreen({? values["llm.api_key"]: ""}- placeholder={settings?.llm_api_key_set ? "<hidden>" : ""}+ placeholder={apiKeySet ? "<hidden>" : ""}onChange={(value) => onChange("llm.api_key", value)}isDisabled={isDisabled}startContent={- settings?.llm_api_key_set ? (- <KeyStatusIcon isSet={settings.llm_api_key_set} />- ) : undefined+ apiKeySet ? <KeyStatusIcon isSet={apiKeySet} /> : undefined}/>@@ -411,9 +434,11 @@ export function LlmSettingsScreen({);},[+ editingProfile,infoMessageKey,isSaasMode,defaultModel,+ profileFormMode,profileName,scope,selectedProvider,@@ -463,6 +488,26 @@ export function LlmSettingsScreen({agentSettings.llm = llm;}+ // Edit hydrates from the profile without marking fields dirty, so a+ // diff-only save would snapshot the *active* settings over the profile.+ // Persist the form's model/base_url explicitly when they aren't dirty.+ if (profileFormMode === "edit") {+ if (llm.model === undefined && modelValue) {+ llm.model = modelValue;+ }+ if (llm.base_url === undefined) {+ const baseUrlValue =+ typeof context.values["llm.base_url"] === "string"+ ? context.values["llm.base_url"].trim()+ : "";+ llm.base_url = baseUrlValue || null;+ }+ if (shouldUseOpenHandsKey && llm.api_key === undefined) {+ llm.api_key = "";+ }+ agentSettings.llm = llm;+ }+// Remember the model currently shown in the form β this is what the// user is saving regardless of whether `llm.model` was toggled dirty// this turn. ``defaultPayload`` only includes dirty fields, so@@ -470,10 +515,18 @@ export function LlmSettingsScreen({// fire on same-value re-saves (e.g. save β delete profile β save// again).lastSavedModelRef.current = modelValue || null;+ // OpenHands-managed saves force api_key to "" above β that's not a+ // user-typed key, so it must not defeat key preservation.+ const typedApiKey =+ typeof context.values["llm.api_key"] === "string"+ ? context.values["llm.api_key"].trim()+ : "";+ lastSavedApiKeyTypedRef.current =+ !shouldUseOpenHandsKey && typedApiKey.length > 0;return { agent_settings_diff: agentSettings };},- [isSaasMode, schema, scope, selectedProvider],+ [isSaasMode, profileFormMode, schema, scope, selectedProvider],);const handleSaveSuccess = React.useCallback(async () => {@@ -515,20 +568,18 @@ export function LlmSettingsScreen({});}}- // Omit `llm` β backend snapshots the just-saved agent_settings.llm- // (api_key and all). Saves us from having to hand-reconstruct the- // config and risk mangling the secret placeholder handling.+ // Omit `llm` β backend snapshots the just-saved agent_settings.llm.+ // When the user typed no key, the snapshot would carry the *active*+ // settings' key β preserve_existing_api_key keeps the profile's own.+ const request = {+ include_secrets: true,+ preserve_existing_api_key: !lastSavedApiKeyTypedRef.current,+ };if (useOrgHooks) {- await saveOrgProfile.mutateAsync({- name,- request: { include_secrets: true },- });+ await saveOrgProfile.mutateAsync({ name, request });await activateOrgProfile.mutateAsync(name);} else {- await saveProfile.mutateAsync({- name,- request: { include_secrets: true },- });+ await saveProfile.mutateAsync({ name, request });await activateProfile.mutateAsync(name);}} catch {@@ -541,6 +592,7 @@ export function LlmSettingsScreen({setInitialProfileName("");setInitialViewHint(null);setProfileFormMode(null);+ setEditingProfile(null);setShowProfiles(true);}, [activateProfile,@@ -556,35 +608,55 @@ export function LlmSettingsScreen({scope,]);- const openForm = (view: SettingsView | null, name = "") => {- // The profiles list passes a name only when editing; Add Profile+ const openForm = (+ view: SettingsView | null,+ profile: LlmProfileSummary | null = null,+ ) => {+ // The profiles list passes the profile only when editing; Add Profile// opens a blank create form.- const isEdit = Boolean(name);+ const isEdit = profile !== null;setProfileFormMode(isEdit ? "edit" : "create");- setProfileName(name);- setInitialProfileName(name);+ setEditingProfile(profile);+ setProfileName(profile?.name ?? "");+ setInitialProfileName(profile?.name ?? "");setInitialViewHint(view);- if (!isEdit) {- setSelectedProvider(null);- }+ // Blank for create; the edited profile's provider for edit.+ setSelectedProvider(+ profile?.model+ ? extractModelAndProvider(profile.model).provider || null+ : null,+ );setShowProfiles(false);};- // Create starts from a clean slate; editing keeps the settings-derived- // initial values (no overrides).- const createProfileInitialValueOverrides = React.useMemo(- () =>- profileFormMode === "create"- ? {- agent_settings: {- "llm.model": "",- "llm.api_key": "",- "llm.base_url": "",- },- }- : undefined,- [profileFormMode],- );+ // Create starts from a clean slate; edit hydrates from the clicked+ // profile rather than from the active settings.+ const profileFormInitialValueOverrides = React.useMemo(() => {+ if (profileFormMode === "create") {+ return {+ agent_settings: {+ "llm.model": "",+ "llm.api_key": "",+ "llm.base_url": "",+ },+ };+ }+ if (profileFormMode === "edit" && editingProfile) {+ const fieldDefault = (fieldKey: string) =>+ String(getSchemaFieldDefaultValue(schema, fieldKey) ?? "");+ return {+ agent_settings: {+ "llm.model": editingProfile.model ?? fieldDefault("llm.model"),+ // The stored key can't be fetched; the profile's api_key_set+ // drives the <hidden> placeholder instead.+ "llm.api_key": "",+ "llm.base_url":+ editingProfile.base_url ?? fieldDefault("llm.base_url"),+ },+ };+ }+ return undefined;+ }, [editingProfile, profileFormMode, schema]);if (isProfilesView) {if (isOrgProfileMode) {@@ -600,7 +672,7 @@ export function LlmSettingsScreen({}onEditProfile={canManageProfilesForScope- ? (profile) => openForm(null, profile.name)+ ? (profile) => openForm(null, profile): undefined}/>@@ -610,7 +682,7 @@ export function LlmSettingsScreen({return (<LlmProfilesManageronAddProfile={() => openForm(null)}- onEditProfile={(profile) => openForm(null, profile.name)}+ onEditProfile={(profile) => openForm(null, profile)}/>);}@@ -625,6 +697,7 @@ export function LlmSettingsScreen({onClick={() => {setInitialViewHint(null);setProfileFormMode(null);+ setEditingProfile(null);setShowProfiles(true);}}className="flex items-center gap-2 self-start text-sm text-gray-300 hover:text-white cursor-pointer"@@ -657,7 +730,7 @@ export function LlmSettingsScreen({extraDirty={canManageProfilesForScope}onSaveSuccess={handleSaveSuccess}getInitialView={getInitialView}- initialValueOverrides={createProfileInitialValueOverrides}+ initialValueOverrides={profileFormInitialValueOverrides}// A new profile starts blank and can't be saved until a model is// chosen β saving a model-less create form would only churn the// active settings without producing a profile.diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.pyindex 4d925a8fcb..2cf8a3ea37 100644--- a/openhands/app_server/settings/settings_router.py+++ b/openhands/app_server/settings/settings_router.py@@ -407,6 +407,9 @@ class SaveProfileRequest(BaseModel):include_secrets: bool = Truellm: StrictLLM | None = None+ # Set when the caller has no new key (UI key field left blank), so an+ # existing profile's stored key survives instead of the snapshotted active one.+ preserve_existing_api_key: bool = False@router.get('/profiles', response_model=ProfileListResponse)@@ -485,6 +488,7 @@ async def save_profile(detail='Settings not found',)+ existing = settings.llm_profiles.get(name)llm: LLMif request.llm is not None:llm = request.llm@@ -492,12 +496,15 @@ async def save_profile(# update (e.g. a frontend round-tripping a GET response where# the key was nulled out). Mirrors the deep-merge behaviour# the main ``POST /api/v1/settings`` relies on.- if llm.api_key is None:- existing = settings.llm_profiles.get(name)- if existing is not None and existing.api_key is not None:+ if llm.api_key is None and existing is not None:+ if existing.api_key is not None:llm = llm.model_copy(update={'api_key': existing.api_key})else:llm = settings.agent_settings.llm+ if request.preserve_existing_api_key and existing is not None:+ # Caller has no new key: keep the profile's stored key (even "no+ # key") instead of the snapshotted active-settings key.+ llm = llm.model_copy(update={'api_key': existing.api_key})try:settings.llm_profiles.save(diff --git a/tests/unit/app_server/test_profiles_api.py b/tests/unit/app_server/test_profiles_api.pyindex 5169c833df..d4c9630037 100644--- a/tests/unit/app_server/test_profiles_api.py+++ b/tests/unit/app_server/test_profiles_api.py@@ -418,6 +418,116 @@ async def test_edit_profile_with_new_api_key_replaces_old(test_client, settings_assert stored.llm_profiles.get('p').api_key.get_secret_value() == 'NEW-KEY'+async def test_snapshot_save_with_preserve_flag_keeps_existing_profile_key(+ test_client, settings_store+):+ """The UI's no-key edit-save: settings are saved first (active key kept),+ then the profile is snapshotted. ``preserve_existing_api_key`` must stop+ the snapshot from replacing the profile's stored key with the active one,+ while the rest of the snapshot (model etc.) still lands.+ """+ settings = _base_settings() # active llm: openai/gpt-4o + sk-current+ settings.llm_profiles.save(+ 'p', LLM(model='anthropic/claude-opus-4', api_key=SecretStr('sk-profile'))+ )+ await _seed(settings_store, settings)++ resp = test_client.post(+ '/api/v1/settings/profiles/p',+ json={'include_secrets': True, 'preserve_existing_api_key': True},+ )+ assert resp.status_code == 201++ stored = await settings_store.load()+ saved = stored.llm_profiles.get('p')+ assert saved.model == 'openai/gpt-4o' # snapshot of active settings+ assert saved.api_key.get_secret_value() == 'sk-profile' # key preserved+++async def test_snapshot_save_with_preserve_flag_keeps_profile_keyless(+ test_client, settings_store+):+ """A keyless profile must stay keyless on a no-key edit-save β it must+ not silently inherit the active settings' key."""+ settings = _base_settings()+ settings.llm_profiles.save('p', LLM(model='anthropic/claude-opus-4'))+ await _seed(settings_store, settings)++ resp = test_client.post(+ '/api/v1/settings/profiles/p',+ json={'preserve_existing_api_key': True},+ )+ assert resp.status_code == 201++ stored = await settings_store.load()+ assert stored.llm_profiles.get('p').api_key is None+++async def test_snapshot_save_preserve_flag_noop_for_new_profile(+ test_client, settings_store+):+ """With no existing profile there is nothing to preserve β the snapshot+ keeps its key (current create behaviour, unchanged)."""+ await _seed(settings_store, _base_settings())++ resp = test_client.post(+ '/api/v1/settings/profiles/fresh',+ json={'preserve_existing_api_key': True},+ )+ assert resp.status_code == 201++ stored = await settings_store.load()+ assert stored.llm_profiles.get('fresh').api_key.get_secret_value() == 'sk-current'+++async def test_preserve_flag_wins_over_explicit_llm_key(test_client, settings_store):+ """The flag declares 'no new key from the user'; a key smuggled in the+ body alongside it is ignored in favour of the stored one."""+ await _seed(settings_store, _base_settings())+ test_client.post(+ '/api/v1/settings/profiles/p',+ json={'llm': {'model': 'openai/gpt-4o', 'api_key': 'OLD-KEY'}},+ )++ resp = test_client.post(+ '/api/v1/settings/profiles/p',+ json={+ 'preserve_existing_api_key': True,+ 'llm': {'model': 'openai/gpt-4o', 'api_key': 'NEW-KEY'},+ },+ )+ assert resp.status_code == 201++ stored = await settings_store.load()+ assert stored.llm_profiles.get('p').api_key.get_secret_value() == 'OLD-KEY'+++async def test_preserve_flag_then_include_secrets_false_still_clears_key(+ test_client, settings_store+):+ """``include_secrets: false`` is the explicit 'store no secret' switch and+ must win over key preservation."""+ settings = _base_settings()+ settings.llm_profiles.save(+ 'p', LLM(model='openai/gpt-4o', api_key=SecretStr('sk-profile'))+ )+ await _seed(settings_store, settings)++ resp = test_client.post(+ '/api/v1/settings/profiles/p',+ json={'include_secrets': False, 'preserve_existing_api_key': True},+ )+ assert resp.status_code == 201++ stored = await settings_store.load()+ assert stored.llm_profiles.get('p').api_key is None++@pytest.mark.asyncioasync def test_list_profiles_reports_api_key_set_per_row(test_client, settings_store):settings = _base_settings()