Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: persist LLM profile changes from all tabs and fix OpenHands round-trip (#970)

Hiep Le032b76198407
diff --git a/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx b/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx
index 6447b8ddf8..f8c006255f 100644
--- a/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx
+++ b/__tests__/components/features/settings/sdk-settings/sdk-section-page.test.tsx
@@ -6,7 +6,10 @@ import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import SettingsService from "#/api/settings-service/settings-service.api";
-import { SdkSectionPage } from "#/components/features/settings/sdk-settings/sdk-section-page";
+import {
+ SdkSectionPage,
+ type SdkSectionSaveControl,
+} from "#/components/features/settings/sdk-settings/sdk-section-page";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { Settings } from "#/types/settings";
import * as ToastHandlers from "#/utils/custom-toast-handlers";
@@ -665,4 +668,34 @@ describe("SdkSectionPage", () => {
);
});
});
+
+ it("exposes the active view and a coerced, dirty-only payload on the save control", async () => {
+ // Arrange β€” a basic-tier schema with a single editable field.
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSavableSettings(),
+ );
+ let latestControl: SdkSectionSaveControl | null = null;
+
+ renderSdkSectionPage({
+ sectionKeys: ["llm"],
+ onSaveControlChange: (control) => {
+ latestControl = control;
+ },
+ });
+
+ // Act β€” change one field so it becomes dirty.
+ const endpointInput = await screen.findByTestId("sdk-settings-llm.endpoint");
+ await userEvent.clear(endpointInput);
+ await userEvent.type(endpointInput, "https://new.example.com");
+
+ // Assert β€” the control reports the basic view and returns only the dirty
+ // field, nested under its section. Consumers (e.g. the local profile
+ // editor) rely on both to drive a custom save.
+ await waitFor(() => {
+ expect(latestControl?.view).toBe("basic");
+ expect(latestControl?.getDirtyPayload()).toEqual({
+ llm: { endpoint: "https://new.example.com" },
+ });
+ });
+ });
});
diff --git a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
index c48a4449ae..0d8ea3febe 100644
--- a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
+++ b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
@@ -537,4 +537,97 @@ describe("LlmSettingsLocalView", () => {
expect(true).toBe(true);
});
});
+
+ describe("Basic tab save", () => {
+ it("omits base_url so an OpenHands model round-trips on reload", async () => {
+ // Arrange β€” a profile whose stored config pairs an OpenHands model with a
+ // stale, non-proxy base_url. Persisting that base_url is exactly what
+ // makes the provider reload as "litellm_proxy" with an empty model; the
+ // Basic tab must drop it so the backend re-derives the All-Hands proxy.
+ const user = userEvent.setup();
+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({
+ name: "gpt-4-profile",
+ api_key_set: true,
+ config: {
+ model: "openhands/claude-opus-4-5-20251101",
+ api_key: "gAAAA_encrypted_key",
+ base_url: "https://stale.example.com/v1",
+ },
+ });
+ mockSaveMutateAsync.mockResolvedValueOnce({ success: true });
+
+ renderWithProviders(<LlmSettingsLocalView />);
+
+ // Act β€” open the profile in edit mode, force the Basic tab, and save.
+ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);
+ await user.click(screen.getByTestId("profile-edit"));
+ await waitFor(() => {
+ expect(screen.getByTestId("profile-name-input")).toHaveValue(
+ "gpt-4-profile",
+ );
+ });
+ await user.click(await screen.findByTestId("sdk-section-basic-toggle"));
+ await waitFor(() => {
+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();
+ });
+ await user.click(screen.getByTestId("save-profile-btn"));
+
+ // Assert β€” the saved LLM config keeps the OpenHands model but no longer
+ // carries the stale base_url.
+ await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());
+ const savedLlm = mockSaveMutateAsync.mock.calls[0][0].request.llm;
+ expect(savedLlm.model).toBe("openhands/claude-opus-4-5-20251101");
+ expect(savedLlm).not.toHaveProperty("base_url");
+ });
+ });
+
+ describe("All tab save", () => {
+ it("persists a changed minor field without wiping untouched fields", async () => {
+ // Arrange β€” a profile with a minor field (temperature) plus fields the
+ // user will not touch. Saving the All tab must persist the edited minor
+ // field (typed β†’ coerced to a number) while preserving the rest, instead
+ // of resetting everything to LLM defaults via the full-replace save.
+ const user = userEvent.setup();
+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({
+ name: "gpt-4-profile",
+ api_key_set: true,
+ config: {
+ model: "anthropic/claude-opus-4-5-20251101",
+ api_key: "gAAAA_encrypted_key",
+ base_url: null,
+ temperature: 0.2,
+ },
+ });
+ mockSaveMutateAsync.mockResolvedValueOnce({ success: true });
+
+ renderWithProviders(<LlmSettingsLocalView />);
+
+ // Act β€” open the profile, switch to the All tab, edit temperature, save.
+ await user.click(screen.getAllByTestId("profile-menu-trigger")[0]);
+ await user.click(screen.getByTestId("profile-edit"));
+ await waitFor(() => {
+ expect(screen.getByTestId("profile-name-input")).toHaveValue(
+ "gpt-4-profile",
+ );
+ });
+ await user.click(await screen.findByTestId("sdk-section-all-toggle"));
+ const temperatureInput = await screen.findByTestId(
+ "sdk-settings-llm.temperature",
+ );
+ await user.clear(temperatureInput);
+ await user.type(temperatureInput, "0.7");
+ await waitFor(() => {
+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();
+ });
+ await user.click(screen.getByTestId("save-profile-btn"));
+
+ // Assert β€” the edited minor field is persisted as a number, and the
+ // untouched model and API key survive.
+ await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());
+ const savedLlm = mockSaveMutateAsync.mock.calls[0][0].request.llm;
+ expect(savedLlm.temperature).toBe(0.7);
+ expect(savedLlm.model).toBe("anthropic/claude-opus-4-5-20251101");
+ expect(savedLlm.api_key).toBe("gAAAA_encrypted_key");
+ });
+ });
});
diff --git a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
index d83a237577..d30615eb31 100644
--- a/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
+++ b/src/components/features/settings/llm-profiles/llm-settings-local-view.tsx
@@ -1,4 +1,10 @@
-import React, { useState, useCallback, useMemo, useEffect } from "react";
+import React, {
+ useState,
+ useCallback,
+ useMemo,
+ useEffect,
+ useRef,
+} from "react";
import { useTranslation } from "react-i18next";
import { LlmProfilesManager } from "./llm-profiles-manager";
import { ProfileNameInput } from "./profile-name-input";
@@ -6,6 +12,8 @@ import { BrandButton } from "#/components/features/settings/brand-button";
import { LlmSettingsScreen } from "#/routes/llm-settings";
import { useSaveLlmProfile } from "#/hooks/mutation/use-save-llm-profile";
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
+import { useSettings } from "#/hooks/query/use-settings";
+import { useAgentSettingsSchema } from "#/hooks/query/use-agent-settings-schema";
import ProfilesService, {
ProfileInfo,
} from "#/api/profiles-service/profiles-service.api";
@@ -19,7 +27,10 @@ import {
isProfileNameValid,
} from "#/utils/derive-profile-name";
import { SdkSectionSaveControl } from "../sdk-settings/sdk-section-page";
-import { SettingsFormValues } from "#/utils/sdk-settings-schema";
+import {
+ normalizeFieldValue,
+ SettingsFormValues,
+} from "#/utils/sdk-settings-schema";
import { ArrowLeft } from "lucide-react";
import { Typography } from "#/ui/typography";
import { useSettingsSectionHeader } from "#/contexts/settings-section-header-context";
@@ -29,6 +40,13 @@ type ViewMode = "list" | "create" | "edit";
interface EditingProfile {
profile: ProfileInfo;
initialValues: SettingsFormValues;
+ /**
+ * The profile's full LLM config (flat keys; `api_key` is the encrypted
+ * token). Used as the merge base on save so fields the user did not touch β€”
+ * including ones hidden in the current tab or absent from the schema β€” are
+ * preserved instead of being reset to LLM defaults by the full-replace save.
+ */
+ baseConfig: Record<string, unknown>;
}
/**
@@ -46,6 +64,19 @@ export function LlmSettingsLocalView() {
const { setHideSectionHeader } = useSettingsSectionHeader();
const saveProfile = useSaveLlmProfile();
const { data: profilesData } = useLlmProfiles();
+ const { data: settings } = useSettings();
+ const { data: agentSchema } = useAgentSettingsSchema(
+ settings?.agent_settings_schema,
+ );
+
+ // Always hold the freshest schema. `handleEditProfile` awaits a network
+ // round-trip before seeding the form, so reading the schema from a ref
+ // (rather than the value captured in the callback's closure) picks up a
+ // schema that finished loading during that await. This closes the brief
+ // first-load window where the schema is still pending when Edit is clicked
+ // and would otherwise seed only the three hard-coded keys.
+ const agentSchemaRef = useRef(agentSchema);
+ agentSchemaRef.current = agentSchema;
const [viewMode, setViewMode] = useState<ViewMode>("list");
const [profileName, setProfileName] = useState("");
@@ -105,13 +136,35 @@ export function LlmSettingsLocalView() {
// (NOT nested under a "llm" key)
const config = (detail.config ?? {}) as Record<string, unknown>;
- const initialValues: SettingsFormValues = {
- "llm.model": (config.model as string) ?? "",
- "llm.api_key": (config.api_key as string) ?? "",
- "llm.base_url": (config.base_url as string) ?? "",
- };
+ // Seed every llm.* form field from the profile config so all tabs β€”
+ // including "All" β€” reflect the profile's real values rather than the
+ // active settings. Fields absent from the schema are still preserved
+ // on save via `baseConfig`. Read the schema from the ref so a schema
+ // that loaded during the `getProfile` await above is used.
+ const schema = agentSchemaRef.current;
+ const llmFields =
+ schema?.sections.find((section) => section.key === "llm")?.fields ??
+ [];
+ const initialValues: SettingsFormValues = {};
+ for (const field of llmFields) {
+ const flatKey = field.key.startsWith("llm.")
+ ? field.key.slice("llm.".length)
+ : field.key;
+ initialValues[field.key] = normalizeFieldValue(
+ field,
+ config[flatKey],
+ );
+ }
+
+ // Safety net for the specially-rendered keys when the schema is
+ // unavailable, so editing still works without it.
+ if (llmFields.length === 0) {
+ initialValues["llm.model"] = (config.model as string) ?? "";
+ initialValues["llm.api_key"] = (config.api_key as string) ?? "";
+ initialValues["llm.base_url"] = (config.base_url as string) ?? "";
+ }
- setEditingProfile({ profile, initialValues });
+ setEditingProfile({ profile, initialValues, baseConfig: config });
setProfileName(profile.name);
setViewMode("edit");
} catch (error) {
@@ -156,14 +209,57 @@ export function LlmSettingsLocalView() {
const handleSave = useCallback(async () => {
if (!saveControl || !isNameValid) return;
- const values = saveControl.values;
- const model =
- typeof values["llm.model"] === "string" ? values["llm.model"] : "";
- const apiKey =
- typeof values["llm.api_key"] === "string" ? values["llm.api_key"] : "";
- const baseUrl =
- typeof values["llm.base_url"] === "string" ? values["llm.base_url"] : "";
+ // Coerced, dirty-only changes from the embedded form. Merging these over
+ // the profile's existing full config preserves fields the user did not
+ // touch (incl. ones hidden in the current tab or absent from the schema);
+ // the backend replaces the whole LLM object, so a partial payload would
+ // otherwise reset everything else to defaults.
+ let dirtyLlm: Record<string, unknown>;
+ try {
+ dirtyLlm = (saveControl.getDirtyPayload().llm ?? {}) as Record<
+ string,
+ unknown
+ >;
+ } catch (error) {
+ displayErrorToast(
+ error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC),
+ );
+ return;
+ }
+
+ const baseConfig =
+ viewMode === "edit" && editingProfile?.baseConfig
+ ? { ...editingProfile.baseConfig }
+ : {};
+ const llmConfig: Record<string, unknown> = { ...baseConfig, ...dirtyLlm };
+
+ // The Basic tab has no base_url field; the provider implies it. Drop any
+ // (possibly stale, non-proxy) base_url so the backend derives the correct
+ // one β€” e.g. the All-Hands proxy for openhands/* models, which is required
+ // for the provider to round-trip back to "OpenHands" on reload. Mirrors
+ // LlmSettingsScreen.buildPayload's Basic-view reset.
+ if (saveControl.view === "basic") {
+ delete llmConfig.base_url;
+ }
+ // API key handling: an empty value means "no change" (the UX doesn't
+ // support clearing a key). In edit mode preserve the existing encrypted
+ // key from the profile; in create mode omit api_key entirely. A newly
+ // typed key arrives in `dirtyLlm` and wins.
+ if (
+ typeof llmConfig.api_key !== "string" ||
+ llmConfig.api_key.trim() === ""
+ ) {
+ const existingKey =
+ typeof baseConfig.api_key === "string" ? baseConfig.api_key : "";
+ if (existingKey) {
+ llmConfig.api_key = existingKey;
+ } else {
+ delete llmConfig.api_key;
+ }
+ }
+
+ const model = typeof llmConfig.model === "string" ? llmConfig.model : "";
if (!model) {
displayErrorToast(t(I18nKey.SETTINGS$MODEL_REQUIRED));
return;
@@ -182,32 +278,6 @@ export function LlmSettingsLocalView() {
await ProfilesService.renameProfile(originalName, trimmedName);
}
- // Build the LLM config object
- const llmConfig: Record<string, unknown> = { model };
-
- // API key handling:
- // - If user entered a new key, use it
- // - In edit mode with no new key, preserve the existing encrypted key
- // (fetched with exposeSecrets='encrypted' and passed back to server)
- // - In create mode with no key, omit api_key entirely
- //
- // Note: The current UX doesn't support explicitly clearing an API key.
- // If needed, a future enhancement could add a "Clear API Key" option.
- // The encrypted key format is stable and can be round-tripped to the server.
- if (apiKey) {
- llmConfig.api_key = apiKey;
- } else if (
- viewMode === "edit" &&
- editingProfile?.initialValues["llm.api_key"]
- ) {
- llmConfig.api_key = editingProfile.initialValues["llm.api_key"];
- }
-
- // Only include base_url if set
- if (baseUrl) {
- llmConfig.base_url = baseUrl;
- }
-
await saveProfile.mutateAsync({
name: trimmedName,
request: {
diff --git a/src/components/features/settings/sdk-settings/sdk-section-page.tsx b/src/components/features/settings/sdk-settings/sdk-section-page.tsx
index 9e37f16440..de7835a57c 100644
--- a/src/components/features/settings/sdk-settings/sdk-section-page.tsx
+++ b/src/components/features/settings/sdk-settings/sdk-section-page.tsx
@@ -19,6 +19,7 @@ import {
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
import {
buildInitialSettingsFormValues,
+ buildSdkSettingsPayload,
buildSdkSettingsPayloadForView,
getVisibleSettingsSections,
hasAdvancedSettings,
@@ -117,6 +118,15 @@ export interface SdkSectionSaveControl {
isDirty: boolean;
/** Current form values (for custom save flows). */
values: SettingsFormValues;
+ /** The active view tier (basic/advanced/all) the form is rendering. */
+ view: SettingsView;
+ /**
+ * Returns the coerced, dirty-only payload as a nested object
+ * (e.g. `{ llm: { temperature: 0.7 } }`). Lets a custom save flow persist
+ * exactly the fields the user changed, with proper types, without
+ * re-implementing schema-driven coercion. Throws if a field fails coercion.
+ */
+ getDirtyPayload: () => Record<string, unknown>;
}
/**
@@ -360,6 +370,17 @@ export function SdkSectionPage({
handleSaveRef.current();
}, []);
+ // Stable accessor for the coerced, dirty-only payload. Mirrors the
+ // `handleSaveRef` pattern so the exposed function reference stays stable
+ // across renders while always reading the latest closure at call time.
+ const buildDirtyPayloadRef = React.useRef<() => Record<string, unknown>>(
+ () => ({}),
+ );
+ const stableGetDirtyPayload = React.useCallback(
+ () => buildDirtyPayloadRef.current(),
+ [],
+ );
+
const handleSave = () => {
if (!filteredSchema || isReadOnly) return;
@@ -400,6 +421,14 @@ export function SdkSectionPage({
};
handleSaveRef.current = handleSave;
+ // Dirty-only (NOT view-filtered): we must never inject defaults for
+ // non-visible fields here, or a custom save flow would reset fields the
+ // user never touched. `buildSdkSettingsPayloadForView` is reserved for the
+ // built-in full-replace save above.
+ buildDirtyPayloadRef.current = () =>
+ filteredSchema
+ ? buildSdkSettingsPayload(filteredSchema, values, dirty)
+ : {};
// Surface save state to the parent. Hooks must run before any
// conditional early-returns below, so this lives here rather than
@@ -415,8 +444,10 @@ export function SdkSectionPage({
isSaving: isPending,
isDirty: saveControlIsDirty,
values,
+ view,
+ getDirtyPayload: stableGetDirtyPayload,
});
- }, [isPending, saveControlIsDirty, values]);
+ }, [isPending, saveControlIsDirty, values, view]);
if (isLoading || isFetching || isSchemaLoading) {
return <LlmSettingsInputsSkeleton />;
diff --git a/src/utils/sdk-settings-schema.ts b/src/utils/sdk-settings-schema.ts
index bc81445849..8abea191a3 100644
--- a/src/utils/sdk-settings-schema.ts
+++ b/src/utils/sdk-settings-schema.ts
@@ -125,7 +125,7 @@ function isMinorField(field: SettingsFieldSchema): boolean {
return field.prominence === "minor";
}
-function normalizeFieldValue(
+export function normalizeFieldValue(
field: SettingsFieldSchema,
rawValue: unknown,
): string | boolean {