π OpenHands: AI-Driven Development
fix(settings): disable save when edits are reverted (#16120)
Shashwat Pratap Singh1098d73df423
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.tsxindex e3838d366c..019186189b 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@@ -322,6 +322,115 @@ describe("SdkSectionPage", () => {});});+ it("keeps embedded editor tab and edits across settings refetch", async () => {+ const schema: NonNullable<Settings["agent_settings_schema"]> = {+ model_name: "AgentSettings",+ sections: [+ {+ key: "llm",+ label: "LLM",+ fields: [+ {+ key: "llm.model",+ label: "Model",+ section: "llm",+ section_label: "LLM",+ value_type: "string",+ default: "openhands/claude-opus-4-5-20251101",+ choices: [],+ depends_on: [],+ prominence: "critical",+ secret: false,+ required: true,+ },+ {+ key: "llm.base_url",+ label: "Base URL",+ section: "llm",+ section_label: "LLM",+ value_type: "string",+ default: null,+ choices: [],+ depends_on: [],+ prominence: "major",+ secret: false,+ required: false,+ },+ ],+ },+ ],+ };++ const getSettingsSpy = vi+ .spyOn(SettingsService, "getSettings")+ .mockResolvedValue(+ buildSettings({+ agent_settings_schema: schema,+ agent_settings: {+ "llm.model": "openhands/claude-opus-4-5-20251101",+ },+ }),+ );++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ });++ let latestControl: SdkSectionSaveControl | null = null;++ mockUseConfig.mockReturnValue({+ data: {},+ isLoading: false,+ });+ mockUseSearchParams.mockReturnValue([{ get: () => null }, vi.fn()]);++ render(+ <QueryClientProvider client={queryClient}>+ <SdkSectionPage+ settingsSources={[+ { settingsSource: "agent_settings", sectionKeys: ["llm"] },+ ]}+ hideSaveButton+ markInitialOverridesDirty={false}+ initialValueOverrides={{+ "llm.model": "",+ "llm.base_url": "",+ }}+ onSaveControlChange={(control) => {+ latestControl = control;+ }}+ />+ </QueryClientProvider>,+ );++ await screen.findByTestId("sdk-section-advanced-toggle");+ await userEvent.click(screen.getByTestId("sdk-section-advanced-toggle"));+ const baseUrlInput = await screen.findByTestId("sdk-settings-llm.base_url");+ await userEvent.clear(baseUrlInput);+ await userEvent.type(baseUrlInput, "http://127.0.0.1:9999");++ getSettingsSpy.mockResolvedValue(+ buildSettings({+ agent_settings_schema: schema,+ agent_settings: {+ "llm.model": "openhands/claude-opus-4-5-20251101",+ "llm.base_url": null,+ },+ }),+ );+ await queryClient.invalidateQueries({ queryKey: ["settings"] });++ await waitFor(() => {+ expect(screen.getByTestId("sdk-settings-llm.base_url")).toHaveValue(+ "http://127.0.0.1:9999",+ );+ expect(latestControl?.view).toBe("advanced");+ expect(latestControl?.isDirty).toBe(true);+ });+ });+it("resets from advanced to the inferred basic view after saving when advanced settings match defaults", async () => {const schema: NonNullable<Settings["agent_settings_schema"]> = {model_name: "AgentSettings",@@ -984,4 +1093,119 @@ describe("SdkSectionPage", () => {});});});++ it("disables Save after a boolean field is changed and then reverted", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ conversation_settings_schema: {+ model_name: "ConversationSettings",+ sections: [+ {+ key: "verification",+ label: "Verification",+ fields: [+ {+ key: "confirmation_mode",+ label: "Confirmation mode",+ section: "verification",+ section_label: "Verification",+ value_type: "boolean",+ default: false,+ choices: [],+ depends_on: [],+ prominence: "critical",+ secret: false,+ required: false,+ },+ ],+ },+ ],+ },+ conversation_settings: {+ confirmation_mode: false,+ },+ }),+ );++ renderSdkSectionPage({+ settingsSources: [+ {+ settingsSource: "conversation_settings",+ sectionKeys: ["verification"],+ },+ ],+ });++ const confirmationInput = await screen.findByTestId(+ "sdk-settings-confirmation_mode",+ );+ const saveButton = screen.getByTestId("save-button") as HTMLButtonElement;+ expect(saveButton).toBeDisabled();++ await userEvent.click(confirmationInput.closest("label")!);+ expect(saveButton).not.toBeDisabled();++ await userEvent.click(confirmationInput.closest("label")!);+ expect(saveButton).toBeDisabled();+ });++ it("disables Save after a string field is edited back to the loaded value", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSavableSettings(),+ );++ renderSdkSectionPage({+ settingsSources: [+ { settingsSource: "agent_settings", sectionKeys: ["llm"] },+ ],+ });++ const endpointInput = await screen.findByTestId(+ "sdk-settings-llm.endpoint",+ );+ const saveButton = screen.getByTestId("save-button") as HTMLButtonElement;+ expect(saveButton).toBeDisabled();++ await userEvent.clear(endpointInput);+ await userEvent.type(endpointInput, "https://changed.example.com");+ expect(saveButton).not.toBeDisabled();++ await userEvent.clear(endpointInput);+ await userEvent.type(endpointInput, "https://api.example.com");+ await waitFor(() => {+ expect(saveButton).toBeDisabled();+ });+ });++ it("does not force-dirty override fields when markInitialOverridesDirty is false", async () => {+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSavableSettings(),+ );++ renderSdkSectionPage({+ settingsSources: [+ { settingsSource: "agent_settings", sectionKeys: ["llm"] },+ ],+ initialValueOverrides: {+ "llm.endpoint": "https://seeded.example.com",+ },+ markInitialOverridesDirty: false,+ });++ const endpointInput = await screen.findByTestId(+ "sdk-settings-llm.endpoint",+ );+ expect(endpointInput).toHaveValue("https://seeded.example.com");+ expect(screen.getByTestId("save-button")).toBeDisabled();++ await userEvent.clear(endpointInput);+ await userEvent.type(endpointInput, "https://changed.example.com");+ expect(screen.getByTestId("save-button")).not.toBeDisabled();++ await userEvent.clear(endpointInput);+ await userEvent.type(endpointInput, "https://seeded.example.com");+ await waitFor(() => {+ expect(screen.getByTestId("save-button")).toBeDisabled();+ });+ });});diff --git a/__tests__/components/features/settings/secrets-settings/secret-form.test.tsx b/__tests__/components/features/settings/secrets-settings/secret-form.test.tsxindex c95b85bdb0..8f366aba18 100644--- a/__tests__/components/features/settings/secrets-settings/secret-form.test.tsx+++ b/__tests__/components/features/settings/secrets-settings/secret-form.test.tsx@@ -45,7 +45,11 @@ describe("SecretForm in edit mode", () => {// Arrangeconst { updateSecret } = await renderEditForm();- // Act+ // Act β submit is dirty-gated, so change description while leaving value blank+ await userEvent.type(+ screen.getByTestId("description-input"),+ " (unchanged value)",+ );await userEvent.click(screen.getByTestId("submit-button"));// Assert@@ -53,7 +57,7 @@ describe("SecretForm in edit mode", () => {expect(updateSecret).toHaveBeenCalledWith("API_KEY","API_KEY",- "Demo secret",+ "Demo secret (unchanged value)",undefined,),);diff --git a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsxindex c3884a3dbc..4af8be9cdb 100644--- a/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx+++ b/__tests__/components/settings/agent-profiles/agent-profiles-local-view.test.tsx@@ -131,6 +131,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: true,@@ -157,6 +158,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "acp",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "acp",acp_server: "claude-code",@@ -212,6 +214,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: true,@@ -286,6 +289,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: false,@@ -322,6 +326,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "acp",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "acp",acp_server: "claude-code",@@ -372,6 +377,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: false,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: false,@@ -383,6 +389,9 @@ describe("AgentProfilesLocalView save mapping", () => {const user = userEvent.setup();await user.click(screen.getByTestId("edit-agent-profile"));await screen.findByTestId("mock-agent-settings");+ await waitFor(() => {+ expect(screen.getByTestId("save-agent-profile-btn")).not.toBeDisabled();+ });await user.click(screen.getByTestId("save-agent-profile-btn"));await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));@@ -406,6 +415,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: false,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: false,@@ -417,11 +427,7 @@ describe("AgentProfilesLocalView save mapping", () => {const user = userEvent.setup();await user.click(screen.getByTestId("edit-agent-profile"));await screen.findByTestId("mock-agent-settings");- await user.click(screen.getByTestId("save-agent-profile-btn"));-- await waitFor(() => expect(saveMutate).toHaveBeenCalledTimes(1));- const { profile } = saveMutate.mock.calls[0][0];- expect(profile.llm_profile_ref).toBe("default");+ expect(screen.getByTestId("save-agent-profile-btn")).toBeDisabled();});it("blocks an OpenHands save when no LLM profile is available", async () => {@@ -429,6 +435,7 @@ describe("AgentProfilesLocalView save mapping", () => {emitControl = {agentType: "openhands",isValid: true,+ isDirty: true,buildAgentProfileFields: () => ({agent_kind: "openhands",enable_sub_agents: false,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.tsxindex 93732de9a2..add36ddf8f 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@@ -63,6 +63,9 @@ vi.mock("#/routes/llm-settings", async () => {String(initialValuesRef.current["llm.base_url"] ?? ""),);const [temperature, setTemperature] = React.useState("0.2");+ const isDirty =+ model !== String(initialValuesRef.current["llm.model"] ?? "") ||+ temperature !== "0.2";React.useEffect(() => {const values = {...(initialValueOverridesRef.current ?? {}),@@ -73,7 +76,7 @@ vi.mock("#/routes/llm-settings", async () => {onSaveControlChange?.({save: vi.fn(),isSaving: false,- isDirty: true,+ isDirty,view,values,getDirtyPayload: () => {@@ -89,7 +92,15 @@ vi.mock("#/routes/llm-settings", async () => {};},});- }, [apiKey, baseUrl, model, onSaveControlChange, temperature, view]);+ }, [+ apiKey,+ baseUrl,+ isDirty,+ model,+ onSaveControlChange,+ temperature,+ view,+ ]);return (<div data-testid="mock-llm-settings-screen">@@ -486,6 +497,39 @@ describe("LlmSettingsLocalView", () => {// Verify we're in edit mode (back button and save button visible)expect(screen.getByTestId("back-to-profiles")).toBeInTheDocument();expect(screen.getByTestId("save-profile-btn")).toBeInTheDocument();+ // Seeded profile values must not count as dirty β Save stays off.+ expect(screen.getByTestId("save-profile-btn")).toBeDisabled();+ });++ it("enables Save after an edit-mode form field changes", async () => {+ const user = userEvent.setup();+ vi.mocked(ProfilesService.getProfile).mockResolvedValue({+ name: "gpt-4-profile",+ api_key_set: true,+ config: {+ model: "openai/gpt-4",+ api_key: "encrypted-key-123",+ base_url: "https://api.openai.com/v1",+ },+ });++ renderWithProviders(<LlmSettingsLocalView />);++ 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",+ );+ });+ expect(screen.getByTestId("save-profile-btn")).toBeDisabled();++ const modelInput = await screen.findByTestId("mock-basic-model-input");+ await user.clear(modelInput);+ await user.type(modelInput, "openai/gpt-4o");+ await waitFor(() => {+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();+ });});});@@ -640,6 +684,15 @@ describe("LlmSettingsLocalView", () => {);}+ async function makeEditDirty(user: ReturnType<typeof userEvent.setup>) {+ const modelInput = await screen.findByTestId("mock-basic-model-input");+ await user.clear(modelInput);+ await user.type(modelInput, "openai/gpt-4o");+ await waitFor(() => {+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();+ });+ }+it("blocks saving when validation returns an invalid verdict", async () => {const user = userEvent.setup();vi.mocked(ProfilesService.validateProfile).mockResolvedValue({@@ -648,6 +701,7 @@ describe("LlmSettingsLocalView", () => {});renderWithProviders(<LlmSettingsLocalView />);await openEditView(user);+ await makeEditDirty(user);await user.click(screen.getByTestId("save-profile-btn"));await waitFor(() =>@@ -664,6 +718,7 @@ describe("LlmSettingsLocalView", () => {mockSaveMutateAsync.mockResolvedValue({ success: true });renderWithProviders(<LlmSettingsLocalView />);await openEditView(user);+ await makeEditDirty(user);await user.click(screen.getByTestId("save-profile-btn"));await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());@@ -685,9 +740,7 @@ describe("LlmSettingsLocalView", () => {mockSaveMutateAsync.mockResolvedValue({ success: true });renderWithProviders(<LlmSettingsLocalView />);await openEditView(user);- await waitFor(() => {- expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();- });+ await makeEditDirty(user);await user.click(screen.getByTestId("save-profile-btn"));await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());@@ -722,6 +775,14 @@ describe("LlmSettingsLocalView", () => {);});await user.click(await screen.findByTestId("sdk-section-basic-toggle"));+ // Touch a non-model field so Save enables without changing the model.+ 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.3");+ await user.click(await screen.findByTestId("sdk-section-basic-toggle"));await waitFor(() => {expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();});@@ -761,6 +822,13 @@ describe("LlmSettingsLocalView", () => {);});await user.click(await screen.findByTestId("sdk-section-basic-toggle"));+ 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.3");+ await user.click(await screen.findByTestId("sdk-section-basic-toggle"));await waitFor(() => {expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();});diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 4470869a78..943029fd8d 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -792,13 +792,11 @@ describe("AgentSettingsScreen", () => {"npx -y @agentclientprotocol/[email protected] --extra-arg",);- // Touch the form to mark it dirty (Save is disabled until isDirty),- // then submit. The data the form sends has to carry the registry-- // default prefix the user can now SEE in the textarea, not the bare- // ``--extra-arg`` that was stored.+ // Make a real edit so Save enables, then submit. The payload must+ // carry the registry-default prefix the user can SEE in the textarea,+ // not the bare ``--extra-arg`` that was stored.await user.click(cmd);- await user.keyboard("{End} ");- await user.keyboard("{Backspace}");+ await user.keyboard("{End} --saved");await user.click(screen.getByTestId("agent-save-button"));await waitFor(() => {@@ -813,12 +811,44 @@ describe("AgentSettingsScreen", () => {"-y","@agentclientprotocol/[email protected]","--extra-arg",+ "--saved",]);// ``acp_args: []`` resets the API-set args so they don't double up// at spawn time.expect(call.agent_settings_diff?.acp_args).toEqual([]);});+ it("disables Save after reverting an agent-type dropdown change", async () => {+ const user = userEvent.setup();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettings({+ agent_settings: {+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,+ agent_kind: "openhands",+ },+ }),+ );++ renderAgentSettingsScreen();+ await screen.findByTestId("agent-type-selector");+ const save = screen.getByTestId("agent-save-button") as HTMLButtonElement;+ expect(save).toBeDisabled();++ await user.click(screen.getByTestId("agent-type-selector"));+ await user.click(+ await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),+ );+ expect(save).not.toBeDisabled();++ await user.click(screen.getByTestId("agent-type-selector"));+ await user.click(+ await screen.findByRole("option", {+ name: "SETTINGS$AGENT_TYPE_OPENHANDS",+ }),+ );+ expect(save).toBeDisabled();+ });+it("preserves an unknown loaded acp_server when the user saves without editing", async () => {// Data-corruption regression: a user with an ``acp_server`` value// canvas's registry doesn't know about (e.g. set via the API for a@@ -852,12 +882,10 @@ describe("AgentSettingsScreen", () => {)) as HTMLTextAreaElement;expect(cmd.value).toBe("npx -y @some-future/amp-acp");- // Touch + revert the textarea to flip isDirty without changing- // the persisted command text β matches "user opens settings and- // hits Save without intending to change anything."- await user.click(cmd);- await user.keyboard("{End} ");- await user.keyboard("{Backspace}");+ // Change only the model so Save enables while the command stays+ // identical to what was loaded β preserves the unknown acp_server path.+ const modelInput = await screen.findByTestId("agent-model-input");+ await user.type(modelInput, "future-model");await user.click(screen.getByTestId("agent-save-button"));await waitFor(() => {diff --git a/__tests__/routes/secrets-settings.test.tsx b/__tests__/routes/secrets-settings.test.tsxindex 76b0c0c231..2c5d0016f8 100644--- a/__tests__/routes/secrets-settings.test.tsx+++ b/__tests__/routes/secrets-settings.test.tsx@@ -1,5 +1,6 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { SecretsSettingsScreen } from "#/routes/secrets-settings";import { SecretsService } from "#/api/secrets-service";@@ -38,4 +39,50 @@ describe("SecretsSettingsScreen", () => {expect(await screen.findByText("MY_SECRET")).toBeInTheDocument();expect(screen.getByTestId("add-secret-button")).toBeInTheDocument();});++ it("disables Add Secret submit until required fields are filled", async () => {+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);+ const user = userEvent.setup();++ renderSecretsSettingsScreen();++ await screen.findByTestId("secrets-settings-screen");+ await user.click(screen.getByTestId("add-secret-button"));++ const submitButton = screen.getByTestId("submit-button");+ const nameInput = screen.getByTestId("name-input");+ const valueInput = screen.getByTestId("value-input");++ expect(submitButton).toBeDisabled();++ await user.type(nameInput, "MY_SECRET");+ expect(submitButton).toBeDisabled();++ await user.type(valueInput, "super-secret");+ expect(submitButton).not.toBeDisabled();+ });++ it("disables Edit Secret submit until a field changes", async () => {+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([+ {+ name: "MY_SECRET",+ description: "Demo secret",+ },+ ]);+ const user = userEvent.setup();++ renderSecretsSettingsScreen();++ await screen.findByTestId("secrets-settings-screen");+ await screen.findByText("MY_SECRET");+ await user.click(screen.getByTestId("edit-secret-button"));++ const submitButton = screen.getByTestId("submit-button");+ const descriptionInput = screen.getByTestId("description-input");++ expect(submitButton).toBeDisabled();++ await user.type(descriptionInput, " updated");+ expect(submitButton).not.toBeDisabled();+ });});\ No newline at end of filediff --git a/__tests__/utils/sdk-settings-schema.test.ts b/__tests__/utils/sdk-settings-schema.test.tsindex 3ca1c29960..5f58e12d35 100644--- a/__tests__/utils/sdk-settings-schema.test.ts+++ b/__tests__/utils/sdk-settings-schema.test.ts@@ -8,10 +8,11 @@ import {hasAdvancedSettingsOverrides,inferInitialView,isValidSettingsSchema,+ normalizeComparableValue,SPECIALLY_RENDERED_KEYS,} from "#/utils/sdk-settings-schema";import { DEFAULT_SETTINGS } from "#/services/settings";-import { Settings, SettingsSchema } from "#/types/settings";+import { Settings, SettingsFieldSchema, SettingsSchema } from "#/types/settings";const BASE_SETTINGS: Settings = {...DEFAULT_SETTINGS,@@ -375,4 +376,52 @@ describe("sdk settings schema helpers", () => {expect(getVisibleSettingsSections(malformed, {}, "basic")).toEqual([]);});});++ describe("normalizeComparableValue", () => {+ const numberField: SettingsFieldSchema = {+ key: "llm.temperature",+ label: "Temperature",+ section: "llm",+ section_label: "LLM",+ value_type: "number",+ default: 0.5,+ choices: [],+ depends_on: [],+ prominence: "major",+ secret: false,+ required: false,+ };++ const objectField: SettingsFieldSchema = {+ key: "llm.litellm_extra_body",+ label: "Extra Body",+ section: "llm",+ section_label: "LLM",+ value_type: "object",+ default: {},+ choices: [],+ depends_on: [],+ prominence: "minor",+ secret: false,+ required: false,+ };++ it("treats equivalent number strings as equal", () => {+ expect(normalizeComparableValue(numberField, "5")).toBe(+ normalizeComparableValue(numberField, "5.0"),+ );+ expect(normalizeComparableValue(numberField, "5")).toBe(+ normalizeComparableValue(numberField, "05"),+ );+ });++ it("treats JSON values equal when only formatting differs", () => {+ const initial = JSON.stringify({ a: 1, b: 2 }, null, 2);+ const reformatted = '{\n "b": 2,\n "a": 1\n}';++ expect(normalizeComparableValue(objectField, initial)).toBe(+ normalizeComparableValue(objectField, reformatted),+ );+ });+ });});diff --git a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsxindex ee30894a88..519d8ca4f7 100644--- a/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx+++ b/src/components/features/settings/agent-profiles/agent-profiles-local-view.tsx@@ -280,6 +280,18 @@ export function AgentProfilesLocalView() {? t(I18nKey.SETTINGS$PROFILE_LOADED, { name: editingProfile.name }): t(I18nKey.SETTINGS$PROFILE_SAVE_HINT);const isOpenHands = saveControl?.agentType !== "acp";+ const nameDirty = viewMode === "edit" && profileName !== editingProfile?.name;+ const loadedLlmRef =+ editingProfile?.agent_kind === "openhands"+ ? editingProfile.llm_profile_ref+ : "";+ const llmRefDirty =+ viewMode === "edit" && isOpenHands && llmProfileRef !== loadedLlmRef;+ const hasUnsavedChanges =+ viewMode === "create" ||+ Boolean(saveControl?.isDirty) ||+ nameDirty ||+ llmRefDirty;return (<div className="flex flex-col gap-6">@@ -353,7 +365,12 @@ export function AgentProfilesLocalView() {type="button"variant="primary"onClick={handleSave}- isDisabled={!isNameValid || isSaving || !saveControl?.isValid}+ isDisabled={+ !isNameValid ||+ isSaving ||+ !saveControl?.isValid ||+ !hasUnsavedChanges+ }aria-busy={isSaving}>{isSaving ? t(I18nKey.SETTINGS$SAVING) : t(I18nKey.BUTTON$SAVE)}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.tsxindex 9535c550c2..f7a1607063 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@@ -492,6 +492,7 @@ export function LlmSettingsLocalView() {}embeddedhideSaveButton+ markInitialOverridesDirty={false}initialValueOverrides={viewMode === "edit" && editingProfile?.initialValues? // Edit mode: use the existing profile values@@ -526,7 +527,17 @@ export function LlmSettingsLocalView() {type="button"variant="primary"onClick={handleSave}- isDisabled={!isNameValid || isSaving || isValidating || !saveControl}+ isDisabled={+ !isNameValid ||+ isSaving ||+ isValidating ||+ !saveControl ||+ !(+ viewMode === "create" ||+ saveControl.isDirty ||+ profileName !== editingProfile?.profile.name+ )+ }aria-busy={isSaving || isValidating}>{isValidatingdiff --git a/src/components/features/settings/sdk-settings/sdk-section-page.tsx b/src/components/features/settings/sdk-settings/sdk-section-page.tsxindex 76e41f954e..deba5f62eb 100644--- a/src/components/features/settings/sdk-settings/sdk-section-page.tsx+++ b/src/components/features/settings/sdk-settings/sdk-section-page.tsx@@ -10,7 +10,12 @@ import {} from "#/hooks/query/use-agent-settings-schema";import { useSettings } from "#/hooks/query/use-settings";import { I18nKey } from "#/i18n/declaration";-import { Settings, SettingsSchema, SettingsScope } from "#/types/settings";+import {+ Settings,+ SettingsFieldSchema,+ SettingsSchema,+ SettingsScope,+} from "#/types/settings";import { extensionModuleEmptyStateClassName } from "#/utils/extension-module-card-classes";import {displayErrorToast,@@ -27,6 +32,7 @@ import {hasMinorSettings,inferInitialView,isValidSettingsSchema,+ normalizeComparableValue,SettingsDirtyState,SettingsFormValues,type SettingsValueSource,@@ -188,6 +194,7 @@ export function SdkSectionPage({forceShowAdvancedView = false,allowAllView = true,initialValueOverrides,+ markInitialOverridesDirty = true,embedded = false,hideSaveButton = false,suppressSuccessToast = false,@@ -220,14 +227,15 @@ export function SdkSectionPage({forceShowAdvancedView?: boolean;allowAllView?: boolean;/**- * Per-field initial value overrides that win over the values- * derived from `useSettings`. The keys of each override are also- * marked dirty on hydration so the user can save the form without- * having to touch the prefilled fields. Useful when the page is- * embedded in a flow that wants to nudge brand-new users toward a- * particular default (e.g. onboarding pre-filling OpenHands/Opus).+ * Per-field initial value overrides that win over the values derived from+ * `useSettings`. When {@link markInitialOverridesDirty} is true (default),+ * override keys also start dirty so onboarding can save a prefill without+ * a touch. Profile editors should pass `false` so Save stays off until the+ * user changes something.*/initialValueOverrides?: SettingsFormValues;+ /** @default true */+ markInitialOverridesDirty?: boolean;embedded?: boolean;hideSaveButton?: boolean;/** Suppress the default success toast after save completes. */@@ -355,6 +363,7 @@ export function SdkSectionPage({() => (initialValueOverrides ? JSON.stringify(initialValueOverrides) : ""),[initialValueOverrides],);+ const firstSettingsSource = resolvedSources[0]?.settingsSource;const [view, setView] = React.useState<SettingsView>("basic");const [valuesBySource, setValuesBySource] = React.useState<@@ -423,10 +432,13 @@ export function SdkSectionPage({React.useEffect(() => {if (!initialValuesBySource || !initialView) return;+ if (hideSaveButton && hasHydratedViewRef.current) {+ return;+ }setValuesBySource(initialValuesBySource);- if (initialValueOverrides) {- const firstSource = resolvedSources[0]?.settingsSource;+ if (initialValueOverrides && markInitialOverridesDirty) {+ const firstSource = firstSettingsSource;if (firstSource) {const overrideDirty: SettingsDirtyState = Object.fromEntries(Object.keys(initialValueOverrides).map((key) => [key, true]),@@ -447,7 +459,14 @@ export function SdkSectionPage({} else {setView((currentView) => getLessDetailedView(currentView, initialView));}- }, [initialValuesBySource, initialView]);+ }, [+ initialValuesBySource,+ initialView,+ overridesSignature,+ markInitialOverridesDirty,+ firstSettingsSource,+ hideSaveButton,+ ]);const fieldKeyToSource = React.useMemo(() => {const map = new Map<string, SettingsValueSource>();@@ -481,6 +500,30 @@ export function SdkSectionPage({return merged;}, [resolvedSources, dirtyBySource]);+ const fieldsByKey = React.useMemo(() => {+ const map = new Map<string, SettingsFieldSchema>();+ for (const src of resolvedSources) {+ if (!src.filteredSchema) continue;+ for (const section of src.filteredSchema.sections) {+ for (const field of section.fields) {+ if (!map.has(field.key)) {+ map.set(field.key, field);+ }+ }+ }+ }+ return map;+ }, [resolvedSources]);++ const initialValuesBySourceRef = React.useRef(initialValuesBySource);+ initialValuesBySourceRef.current = initialValuesBySource;+ const initialValueOverridesRef = React.useRef(initialValueOverrides);+ initialValueOverridesRef.current = initialValueOverrides;+ const markInitialOverridesDirtyRef = React.useRef(markInitialOverridesDirty);+ markInitialOverridesDirtyRef.current = markInitialOverridesDirty;+ const fieldsByKeyRef = React.useRef(fieldsByKey);+ fieldsByKeyRef.current = fieldsByKey;+const handleFieldChange = React.useCallback((fieldKey: string, nextValue: string | boolean) => {const sourceKey = fieldKeyToSource.get(fieldKey);@@ -492,13 +535,32 @@ export function SdkSectionPage({[fieldKey]: nextValue,},}));- setDirtyBySource((prev) => ({- ...prev,- [sourceKey]: {- ...(prev[sourceKey] ?? {}),- [fieldKey]: true,- },- }));+ setDirtyBySource((prev) => {+ const initialVal =+ initialValuesBySourceRef.current?.[sourceKey]?.[fieldKey];+ const stickyOverride =+ markInitialOverridesDirtyRef.current &&+ !!initialValueOverridesRef.current &&+ fieldKey in initialValueOverridesRef.current;+ const field = fieldsByKeyRef.current.get(fieldKey);+ const valuesMatch = field+ ? normalizeComparableValue(field, nextValue) ===+ normalizeComparableValue(field, initialVal)+ : nextValue === initialVal;++ if (valuesMatch && !stickyOverride) {+ if (!prev[sourceKey]?.[fieldKey]) return prev;+ const sourceDirty = { ...(prev[sourceKey] ?? {}) };+ delete sourceDirty[fieldKey];+ return { ...prev, [sourceKey]: sourceDirty };+ }++ if (prev[sourceKey]?.[fieldKey]) return prev;+ return {+ ...prev,+ [sourceKey]: { ...(prev[sourceKey] ?? {}), [fieldKey]: true },+ };+ });},[fieldKeyToSource],);diff --git a/src/components/features/settings/secrets-settings/secret-form.tsx b/src/components/features/settings/secrets-settings/secret-form.tsxindex 9371339bb5..08ff2c7548 100644--- a/src/components/features/settings/secrets-settings/secret-form.tsx+++ b/src/components/features/settings/secrets-settings/secret-form.tsx@@ -33,6 +33,11 @@ export function SecretForm({const { mutate: updateSecret } = useUpdateSecret();const [error, setError] = React.useState<string | null>(null);+ const [name, setName] = React.useState(+ mode === "edit" && selectedSecret ? selectedSecret : "",+ );+ const [value, setValue] = React.useState("");+ const [description, setDescription] = React.useState("");const secretDescription =(mode === "edit" &&@@ -41,6 +46,14 @@ export function SecretForm({?.find((secret) => secret.name === selectedSecret)?.description?.trim()) ||"";+ const initialName = mode === "edit" && selectedSecret ? selectedSecret : "";++ React.useEffect(() => {+ setName(mode === "edit" && selectedSecret ? selectedSecret : "");+ setValue("");+ setDescription(secretDescription);+ setError(null);+ }, [mode, selectedSecret, secretDescription]);const invalidateSecrets = () => {queryClient.invalidateQueries({@@ -83,16 +96,16 @@ export function SecretForm({const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();- const formData = new FormData(event.currentTarget);- const name = formData.get("secret-name")?.toString();- const value = formData.get("secret-value")?.toString().trim();- const description = formData.get("secret-description")?.toString();+ const trimmedName = name.trim();+ const trimmedValue = value.trim();+ const normalizedDescription = description || undefined;- if (name) {+ if (trimmedName) {setError(null);const isNameAlreadyUsed = secrets?.some(- (secret) => secret.name === name && secret.name !== selectedSecret,+ (secret) =>+ secret.name === trimmedName && secret.name !== selectedSecret,);if (isNameAlreadyUsed) {setError(t(I18nKey.SECRETS$SECRET_ALREADY_EXISTS));@@ -100,24 +113,37 @@ export function SecretForm({}if (mode === "add") {- if (!value) {+ if (!trimmedValue) {setError(t(I18nKey.SECRETS$SECRET_VALUE_REQUIRED));return;}- handleCreateSecret(name, value, description || undefined);+ handleCreateSecret(trimmedName, trimmedValue, normalizedDescription);} else if (mode === "edit" && selectedSecret) {+ // Blank value means "keep the existing secret"; only send a value when+ // the user typed a replacement (#16134).handleEditSecret(selectedSecret,- name,- description || undefined,- value || undefined,+ trimmedName,+ normalizedDescription,+ trimmedValue || undefined,);}}};const formTestId = mode === "add" ? "add-secret-form" : "edit-secret-form";+ const isEditDirty =+ mode === "edit" &&+ (name.trim() !== initialName.trim() ||+ description !== secretDescription ||+ value.trim() !== "");+ const isSubmitDisabled =+ mode === "add"+ ? !name.trim() || !value.trim()+ : mode === "edit"+ ? !isEditDirty+ : false;return (<form@@ -132,7 +158,8 @@ export function SecretForm({label={t(I18nKey.SETTINGS$NAME)}className="w-full min-w-0"required- defaultValue={mode === "edit" && selectedSecret ? selectedSecret : ""}+ value={name}+ onChange={setName}placeholder={t(I18nKey.SECRETS$API_KEY_EXAMPLE)}pattern="^[a-zA-Z][a-zA-Z0-9_]{0,63}$"title={t(I18nKey.SETTINGS$SECRET_NAME_PATTERN_TITLE)}@@ -149,6 +176,8 @@ export function SecretForm({data-testid="value-input"name="secret-value"required={mode === "add"}+ value={value}+ onChange={(event) => setValue(event.currentTarget.value)}className={cn("resize-none",formControlMultilineFieldClassName,@@ -167,7 +196,8 @@ export function SecretForm({<inputdata-testid="description-input"name="secret-description"- defaultValue={secretDescription}+ value={description}+ onChange={(event) => setDescription(event.currentTarget.value)}className={cn(formControlSettingsFieldClassName,"disabled:bg-[var(--oh-surface-raised)] disabled:border-[var(--oh-border-subtle)]",@@ -184,7 +214,12 @@ export function SecretForm({>{t(I18nKey.BUTTON$CANCEL)}</BrandButton>- <BrandButton testId="submit-button" type="submit" variant="primary">+ <BrandButton+ testId="submit-button"+ type="submit"+ variant="primary"+ isDisabled={isSubmitDisabled}+ >{mode === "add" && t(I18nKey.SECRETS$ADD_SECRET)}{mode === "edit" && t(I18nKey.SECRETS$EDIT_SECRET)}</BrandButton>diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex 33b56ab17a..dcd502ae39 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -45,11 +45,24 @@ export const handle = { hideTitle: true };type AgentType = "openhands" | "acp";+type AgentSettingsSnapshot = {+ agentType: AgentType;+ commandText: string;+ acpModel: string;+ isCustomAcpModel: boolean;+};+const ENABLE_SUB_AGENTS_FIELD_KEY = "enable_sub_agents";const ENABLE_SWITCH_LLM_TOOL_FIELD_KEY = "enable_switch_llm_tool";const TOOL_CONCURRENCY_FIELD_KEY = "tool_concurrency_limit";const COMMAND_PLACEHOLDER_FALLBACK = "npx -y <package-name>";const ACP_CUSTOM_MODEL_KEY = "__custom_model__";+const EMPTY_AGENT_SETTINGS_SNAPSHOT: AgentSettingsSnapshot = {+ agentType: "openhands",+ commandText: "",+ acpModel: "",+ isCustomAcpModel: false,+};function toStringArray(value: unknown): string[] {return Array.isArray(value)@@ -228,6 +241,8 @@ export interface AgentSettingsSaveControl {agentType: AgentType;/** False when the current form can't be saved (e.g. an empty ACP command). */isValid: boolean;+ /** True when the form differs from the hydrated snapshot. */+ isDirty: boolean;/*** Build the variant-specific AgentProfile fields from the live form state.* Throws a user-facing Error on invalid input (e.g. a bad concurrency value).@@ -338,7 +353,6 @@ export function AgentSettingsScreen({const [commandText, setCommandText] = useState("");const [acpModel, setAcpModel] = useState("");const [isCustomAcpModel, setIsCustomAcpModel] = useState(false);- const [isDirty, setIsDirty] = useState(false);// ACP credentials live alongside the agent spec, so the page owns the// credential form and a single Save persists both. Called unconditionally@@ -356,6 +370,9 @@ export function AgentSettingsScreen({const lastInitializedSettingsRef = useRef<unknown>(null);const loadedAcpServerRef = useRef<string | null>(null);const loadedCommandTextRef = useRef<string>("");+ const [loadedSnapshot, setLoadedSnapshot] = useState<AgentSettingsSnapshot>(+ EMPTY_AGENT_SETTINGS_SNAPSHOT,+ );useEffect(() => {// Seed from the profile override (embedded) or the live global settings.@@ -392,13 +409,19 @@ export function AgentSettingsScreen({const savedModel = source?.acp_model;const normalizedSavedModel =typeof savedModel === "string" ? savedModel.trim() : "";- setAcpModel(- normalizedSavedModel || getAcpPreferredDefaultModel(acpServer) || "",- );- setIsCustomAcpModel(+ const nextAcpModel =+ normalizedSavedModel || getAcpPreferredDefaultModel(acpServer) || "";+ const nextIsCustomAcpModel =!!normalizedSavedModel &&- (!provider || !isKnownAcpModel(provider, normalizedSavedModel)),- );+ (!provider || !isKnownAcpModel(provider, normalizedSavedModel));+ setAcpModel(nextAcpModel);+ setIsCustomAcpModel(nextIsCustomAcpModel);+ setLoadedSnapshot({+ agentType: "acp",+ commandText: renderedCommandText,+ acpModel: nextAcpModel,+ isCustomAcpModel: nextIsCustomAcpModel,+ });} else {setAgentType("openhands");setCommandText("");@@ -406,8 +429,8 @@ export function AgentSettingsScreen({loadedAcpServerRef.current = null;loadedCommandTextRef.current = "";setIsCustomAcpModel(false);+ setLoadedSnapshot(EMPTY_AGENT_SETTINGS_SNAPSHOT);}- setIsDirty(false);}, [settings, agentSettingsOverride]);// Sync the sub-agents toggle when settings reload@@ -442,19 +465,30 @@ export function AgentSettingsScreen({);const stableCredReset = useCallback(() => credFormRef.current.reset(), []);- // Validity/kind are computed here (before the loading early-return) so the- // emit effect can depend on them; the full ACP derivation lives after it.+ // Validity/kind/dirty are computed here (before the loading early-return) so+ // the emit effect can depend on them; the full ACP derivation lives after it.const acpCommandEmpty =agentType === "acp" && parseCommand(commandText).length === 0;- const embeddedCredentialsDirty = acpCredentialForm.isDirty;+ const settingsDirty =+ agentType !== loadedSnapshot.agentType ||+ (agentType === "acp"+ ? commandText !== loadedSnapshot.commandText ||+ acpModel !== loadedSnapshot.acpModel ||+ isCustomAcpModel !== loadedSnapshot.isCustomAcpModel+ : subAgentsEnabled !== initialSubAgentsEnabled ||+ switchLlmToolEnabled !== initialSwitchLlmToolEnabled ||+ toolConcurrency !== initialToolConcurrency);+ const credentialsDirty = acpCredentialForm.isDirty;+ const isAnyDirty = settingsDirty || credentialsDirty;useEffect(() => {if (!embedded || !onSaveControlChange) return;onSaveControlChange({agentType,isValid: !acpCommandEmpty,+ isDirty: isAnyDirty,buildAgentProfileFields: stableBuildFields,credentials: {- isDirty: embeddedCredentialsDirty,+ isDirty: credentialsDirty,save: stableCredSave,reset: stableCredReset,},@@ -464,7 +498,8 @@ export function AgentSettingsScreen({onSaveControlChange,agentType,acpCommandEmpty,- embeddedCredentialsDirty,+ isAnyDirty,+ credentialsDirty,stableBuildFields,stableCredSave,stableCredReset,@@ -510,20 +545,6 @@ export function AgentSettingsScreen({toolConcurrency,});- // Dirty tracking: for OpenHands path, also check the sub-agents and- // LLM-switching toggles and the parallel-tool-calls input.- const isOpenHandsDirty =- !isAcp &&- (subAgentsEnabled !== initialSubAgentsEnabled ||- switchLlmToolEnabled !== initialSwitchLlmToolEnabled ||- toolConcurrency !== initialToolConcurrency);- const settingsDirty = isDirty || isOpenHandsDirty;- // The single Save covers both the agent spec and ACP credentials, so it is- // active when either changed, and shows "Savingβ¦" while either is in flight.- // ``isDirty`` is already false off the ACP path (no credential fields), so no- // ``isAcp`` guard is needed.- const credentialsDirty = acpCredentialForm.isDirty;- const isAnyDirty = settingsDirty || credentialsDirty;const isSavingAny = isSaving || acpCredentialForm.isSaving;const handleSave = async () => {@@ -577,7 +598,13 @@ export function AgentSettingsScreen({},onSuccess: () => {displaySuccessToast(t(I18nKey.SETTINGS$SAVED));- setIsDirty(false);+ setLoadedSnapshot({+ agentType,+ commandText,+ acpModel,+ isCustomAcpModel,+ });+ loadedCommandTextRef.current = commandText;},},);@@ -626,7 +653,12 @@ export function AgentSettingsScreen({},onSuccess: () => {displaySuccessToast(t(I18nKey.SETTINGS$SAVED));- setIsDirty(false);+ setLoadedSnapshot({+ agentType: "openhands",+ commandText: "",+ acpModel: "",+ isCustomAcpModel: false,+ });},},);@@ -703,7 +735,6 @@ export function AgentSettingsScreen({} else if (newType === "openhands") {setIsCustomAcpModel(false);}- setIsDirty(true);}}/>@@ -800,7 +831,6 @@ export function AgentSettingsScreen({setAcpModel("");setIsCustomAcpModel(true);}- setIsDirty(true);}}/>@@ -832,7 +862,6 @@ export function AgentSettingsScreen({setIsCustomAcpModel(false);}setCommandText(nextCommandText);- setIsDirty(true);}}/><Typography.Text className="text-xs text-[#717888]">@@ -867,7 +896,6 @@ export function AgentSettingsScreen({setIsCustomAcpModel(false);setAcpModel(modelKey);}- setIsDirty(true);}}/>)}@@ -885,7 +913,6 @@ export function AgentSettingsScreen({showOptionalTagonChange={(value) => {setAcpModel(value);- setIsDirty(true);}}/>)}diff --git a/src/routes/llm-settings.tsx b/src/routes/llm-settings.tsxindex 945d6fd9d1..7206ab17c1 100644--- a/src/routes/llm-settings.tsx+++ b/src/routes/llm-settings.tsx@@ -137,6 +137,7 @@ export function LlmSettingsScreen({scope = "personal",onSaveSuccess,initialValueOverrides,+ markInitialOverridesDirty,embedded,hideSaveButton,suppressSuccessToast,@@ -149,6 +150,8 @@ export function LlmSettingsScreen({/** Forwarded to {@link SdkSectionPage}. */initialValueOverrides?: SettingsFormValues;/** Forwarded to {@link SdkSectionPage}. */+ markInitialOverridesDirty?: boolean;+ /** Forwarded to {@link SdkSectionPage}. */embedded?: boolean;/** Forwarded to {@link SdkSectionPage}. */hideSaveButton?: boolean;@@ -640,6 +643,7 @@ export function LlmSettingsScreen({allowAllViewonSaveSuccess={onSaveSuccess}initialValueOverrides={initialValueOverrides}+ markInitialOverridesDirty={markInitialOverridesDirty}embedded={embedded}hideSaveButton={hideSaveButton}suppressSuccessToast={suppressSuccessToast}diff --git a/src/utils/sdk-settings-schema.ts b/src/utils/sdk-settings-schema.tsindex 19a9cd2475..1086c62679 100644--- a/src/utils/sdk-settings-schema.ts+++ b/src/utils/sdk-settings-schema.ts@@ -158,7 +158,28 @@ export function normalizeFieldValue(return String(resolvedValue);}-function normalizeComparableValue(+function stableJsonStringify(value: unknown): string {+ if (value === null || typeof value !== "object") {+ return JSON.stringify(value);+ }++ if (Array.isArray(value)) {+ return `[${value.map(stableJsonStringify).join(",")}]`;+ }++ const sortedEntries = Object.entries(value as Record<string, unknown>).sort(+ ([leftKey], [rightKey]) => leftKey.localeCompare(rightKey),+ );++ return `{${sortedEntries+ .map(+ ([key, entryValue]) =>+ `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`,+ )+ .join(",")}}`;+}++export function normalizeComparableValue(field: SettingsFieldSchema,rawValue: unknown,): boolean | number | string | null {@@ -225,13 +246,13 @@ function normalizeComparableValue() {return null;}- return JSON.stringify(parsed);+ return stableJsonStringify(parsed);} catch {return trimmedValue;}}- return JSON.stringify(rawValue);+ return stableJsonStringify(rawValue);}if (rawValue === null) {diff --git a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.tsindex 8297d22f06..7139e7225d 100644--- a/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts+++ b/tests/e2e/mock-llm/settings/mock-llm-profile-management.spec.ts@@ -483,6 +483,11 @@ test.describe("OpenHands provider hidden base_url preservation", () => {await basicToggle.click();}+ const apiKeyInput = page.getByTestId("llm-api-key-input");+ await expect(apiKeyInput).toBeVisible({ timeout: 10_000 });+ await apiKeyInput.click();+ await apiKeyInput.fill("mock-api-key-for-basic-resave");+const saveButton = page.getByTestId("save-profile-btn");await expect(saveButton).toBeEnabled({ timeout: 10_000 });await saveButton.click();diff --git a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts b/tests/e2e/mock-llm/utils/mock-llm-helpers.tsindex 61c94e0f8e..6043178e32 100644--- a/tests/e2e/mock-llm/utils/mock-llm-helpers.ts+++ b/tests/e2e/mock-llm/utils/mock-llm-helpers.ts@@ -632,7 +632,12 @@ async function fillLlmProfileEditorAndSave(await apiKeyInput.click();await apiKeyInput.fill(apiKey);- await page.getByTestId("save-profile-btn").click();+ const saveButton = page.getByTestId("save-profile-btn");+ if (await saveButton.isEnabled()) {+ await saveButton.click();+ } else {+ await page.getByTestId("back-to-profiles").click();+ }await waitForTestId(page, "add-llm-profile");}