π OpenHands: AI-Driven Development
fix: persist app-level settings from /settings/app save flow (#304)
Hiep Leccefb6cb04c9
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.tsindex 737cab1fcf..5d676667cb 100644--- a/__tests__/api/settings-service.test.ts+++ b/__tests__/api/settings-service.test.ts@@ -1,17 +1,52 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { http, HttpResponse } from "msw";import SettingsService from "#/api/settings-service/settings-service.api";+import { APP_PREFERENCES_STORAGE_KEY } from "#/api/app-preferences-store";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import { server } from "#/mocks/node";import { resetTestHandlersMockSettings } from "#/mocks/settings-handlers";+import type { Settings } from "#/types/settings";++const mockSaveCloudSettings = vi.fn();+const mockFetchCloudSettings = vi.fn();++vi.mock("#/api/cloud/settings-service.api", () => ({+ saveCloudSettings: (args: unknown) => mockSaveCloudSettings(args),+ fetchCloudSettings: () => mockFetchCloudSettings(),+ fetchCloudSettingsSchema: vi.fn(),+ fetchCloudConversationSettingsSchema: vi.fn(),+}));++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-token",+ kind: "cloud",+};describe("SettingsService", () => {beforeEach(() => {// Clear localStorage and reset mock settings statewindow.localStorage.clear();resetTestHandlersMockSettings();+ __resetActiveStoreForTests();+ mockSaveCloudSettings.mockReset().mockResolvedValue(undefined);+ mockFetchCloudSettings.mockReset();// Invalidate the in-memory cacheSettingsService.invalidateCache();});+ afterEach(() => {+ __resetActiveStoreForTests();+ });+it("fetches settings from the API and normalizes derived fields", async () => {// The mock handler returns default settingsconst settings = await SettingsService.getSettings();@@ -124,6 +159,123 @@ describe("SettingsService", () => {fetchSpy.mockRestore();});+ it("persists app-level preferences to localStorage when saving on a local backend", async () => {+ // Arrange: no diffs, only the 5 app-level preference fields.+ const appPrefs = {+ language: "fr",+ git_user_name: "Alice",+ git_user_email: "[email protected]",+ enable_sound_notifications: true,+ user_consents_to_analytics: true,+ };++ // Act+ await SettingsService.saveSettings(appPrefs);++ // Assert: localStorage holds the saved fields under the dedicated key.+ const raw = window.localStorage.getItem(APP_PREFERENCES_STORAGE_KEY);+ expect(raw && JSON.parse(raw)).toEqual(appPrefs);+ });++ it("surfaces stored app-level preferences in getSettings on a local backend", async () => {+ // Arrange: pre-seed localStorage as if a previous save had persisted them.+ const appPrefs = {+ language: "fr",+ git_user_name: "Alice",+ git_user_email: "[email protected]",+ enable_sound_notifications: true,+ user_consents_to_analytics: true,+ };+ window.localStorage.setItem(+ APP_PREFERENCES_STORAGE_KEY,+ JSON.stringify(appPrefs),+ );++ // Act+ const settings = await SettingsService.getSettings();++ // Assert: each stored field is reflected on the returned Settings.+ expect({+ language: settings.language,+ git_user_name: settings.git_user_name,+ git_user_email: settings.git_user_email,+ enable_sound_notifications: settings.enable_sound_notifications,+ user_consents_to_analytics: settings.user_consents_to_analytics,+ }).toEqual(appPrefs);+ });++ it("excludes app-level fields from the local PATCH body when mixed with diffs", async () => {+ // Arrange: capture the PATCH body the local agent-server would receive.+ // The handler must echo a valid response so saveSettings does not throw.+ const patchBodies: Array<Record<string, unknown>> = [];+ server.use(+ http.patch("/api/settings", async ({ request }) => {+ patchBodies.push((await request.json()) as Record<string, unknown>);+ return HttpResponse.json({+ agent_settings: {},+ conversation_settings: {},+ llm_api_key_is_set: false,+ });+ }),+ );++ // Act: send both an agent diff and an app-level field in the same save.+ await SettingsService.saveSettings({+ git_user_name: "Alice",+ agent_settings_diff: { agent: "CodeActAgent" },+ });++ // Assert: the local backend only sees the diff; the app field is+ // confined to localStorage.+ expect(patchBodies).toEqual([+ { agent_settings_diff: { agent: "CodeActAgent" } },+ ]);+ expect(+ JSON.parse(+ window.localStorage.getItem(APP_PREFERENCES_STORAGE_KEY) ?? "{}",+ ),+ ).toEqual({ git_user_name: "Alice" });+ });++ it("forwards app-level preferences as flat top-level fields to the cloud save", async () => {+ // Arrange: switch the active backend to cloud so saveSettings routes+ // through saveCloudSettings (mocked).+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ // Act+ await SettingsService.saveSettings({+ language: "fr",+ git_user_name: "Alice",+ });++ // Assert: cloud save received the fields under `app_preferences` so+ // `saveCloudSettings` can spread them into the POST body as flat keys.+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ app_preferences: { language: "fr", git_user_name: "Alice" },+ });+ });++ it("lets the cloud response override locally-stored app preferences", async () => {+ // Arrange: localStorage holds a stale "fr" while the cloud is the+ // authoritative source and returns "ja".+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });+ window.localStorage.setItem(+ APP_PREFERENCES_STORAGE_KEY,+ JSON.stringify({ language: "fr" }),+ );+ mockFetchCloudSettings.mockResolvedValue({+ language: "ja",+ } as Partial<Settings>);++ // Act+ const settings = await SettingsService.getSettings();++ // Assert: the server wins.+ expect(settings.language).toBe("ja");+ });+it("derives provider_tokens_set from locally stored git provider tokens", async () => {// Arrange: simulate post-save state. SecretsService.addGitProvider writes to// this localStorage key after the server PUT /api/settings/secrets succeeds.diff --git a/src/api/app-preferences-store.ts b/src/api/app-preferences-store.tsnew file mode 100644index 0000000000..2e465d177a--- /dev/null+++ b/src/api/app-preferences-store.ts@@ -0,0 +1,138 @@+import { Settings } from "#/types/settings";++/**+ * The local agent-server's PATCH /api/settings only persists+ * `agent_settings_diff` and `conversation_settings_diff`. App-level user+ * preferences (language, sound notifications, analytics consent, git+ * identity) have no native home there, so we persist them in localStorage+ * β the same approach `secrets-service.ts` uses for git provider tokens.+ *+ * In cloud mode the SaaS backend accepts these fields as flat top-level+ * keys at POST /api/v1/settings, and the cloud fetch returns them. We+ * still write through to localStorage so the values survive momentary+ * fetch failures and so the merge logic in `syncDerivedSettings` has a+ * single source for both modes.+ */+export const APP_PREFERENCES_STORAGE_KEY =+ "openhands-agent-server-app-preferences";++export const APP_PREFERENCE_FIELDS = [+ "language",+ "user_consents_to_analytics",+ "enable_sound_notifications",+ "git_user_name",+ "git_user_email",+] as const;++export type AppPreferenceField = (typeof APP_PREFERENCE_FIELDS)[number];++export type StoredAppPreferences = Partial<Pick<Settings, AppPreferenceField>>;++const APP_PREFERENCE_FIELD_SET: ReadonlySet<string> = new Set(+ APP_PREFERENCE_FIELDS,+);++const isAppPreferenceField = (key: string): key is AppPreferenceField =>+ APP_PREFERENCE_FIELD_SET.has(key);++const coerceValue = (+ key: AppPreferenceField,+ value: unknown,+): StoredAppPreferences[AppPreferenceField] | undefined => {+ switch (key) {+ case "language":+ case "git_user_name":+ case "git_user_email":+ return typeof value === "string" ? value : undefined;+ case "enable_sound_notifications":+ return typeof value === "boolean" ? value : undefined;+ case "user_consents_to_analytics":+ if (value === null) return null;+ return typeof value === "boolean" ? value : undefined;+ default:+ return undefined;+ }+};++const sanitize = (input: Record<string, unknown>): StoredAppPreferences => {+ const out: StoredAppPreferences = {};+ for (const key of APP_PREFERENCE_FIELDS) {+ if (key in input) {+ const coerced = coerceValue(key, input[key]);+ if (coerced !== undefined) {+ // TS can't narrow per-key writes through a discriminated assignment,+ // so funnel through a single record write.+ (out as Record<string, unknown>)[key] = coerced;+ }+ }+ }+ return out;+};++export const readStoredAppPreferences = (): StoredAppPreferences => {+ if (typeof window === "undefined") {+ return {};+ }++ try {+ const raw = window.localStorage.getItem(APP_PREFERENCES_STORAGE_KEY);+ if (!raw) return {};+ const parsed = JSON.parse(raw) as unknown;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return {};+ }+ return sanitize(parsed as Record<string, unknown>);+ } catch {+ return {};+ }+};++export const writeStoredAppPreferences = (+ partial: StoredAppPreferences,+): void => {+ if (typeof window === "undefined") return;++ const sanitized = sanitize(partial as Record<string, unknown>);+ const existing = readStoredAppPreferences();+ const merged: StoredAppPreferences = { ...existing, ...sanitized };++ if (Object.keys(merged).length === 0) {+ window.localStorage.removeItem(APP_PREFERENCES_STORAGE_KEY);+ return;+ }++ window.localStorage.setItem(+ APP_PREFERENCES_STORAGE_KEY,+ JSON.stringify(merged),+ );+};++export const clearStoredAppPreferences = (): void => {+ if (typeof window === "undefined") return;+ window.localStorage.removeItem(APP_PREFERENCES_STORAGE_KEY);+};++/**+ * Split known app-preference keys out of a save payload. Used by+ * `SettingsService.saveSettings` so the local PATCH only ever sees the+ * diff fields the agent-server accepts.+ */+export const extractAppPreferences = (+ input: Record<string, unknown>,+): { extracted: StoredAppPreferences; rest: Record<string, unknown> } => {+ const extracted: StoredAppPreferences = {};+ const rest: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(input)) {+ if (isAppPreferenceField(key)) {+ const coerced = coerceValue(key, value);+ if (coerced !== undefined) {+ (extracted as Record<string, unknown>)[key] = coerced;+ }+ } else {+ rest[key] = value;+ }+ }++ return { extracted, rest };+};diff --git a/src/api/cloud/settings-service.api.ts b/src/api/cloud/settings-service.api.tsindex a020c68934..9515a31bc0 100644--- a/src/api/cloud/settings-service.api.ts+++ b/src/api/cloud/settings-service.api.ts@@ -4,6 +4,7 @@ import {type Settings,type SettingsValue,} from "#/types/settings";+import { type StoredAppPreferences } from "../app-preferences-store";import { getActiveBackend } from "../backend-registry/active-store";import type { Backend } from "../backend-registry/types";import { callCloudProxy } from "./proxy";@@ -149,6 +150,7 @@ export async function saveCloudSettings(diff: {agent_settings_diff?: Record<string, SettingsValue>;conversation_settings_diff?: Record<string, SettingsValue>;disabled_skills?: string[];+ app_preferences?: StoredAppPreferences;}): Promise<void> {const backend = getActiveCloudBackend();const body: Record<string, unknown> = {};@@ -168,6 +170,15 @@ export async function saveCloudSettings(diff: {if (diff.disabled_skills !== undefined) {body.disabled_skills = diff.disabled_skills;}+ // Flat top-level app-preference fields (language, git_user_name, β¦).+ // The cloud POST /api/v1/settings stores these directly; see+ // `CloudSettingsResponse` and the MSW handler in+ // `src/mocks/settings-handlers.ts` for the accepted shape.+ if (diff.app_preferences) {+ for (const [key, value] of Object.entries(diff.app_preferences)) {+ body[key] = value;+ }+ }await callCloudProxy<unknown>({backend,method: "POST",diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.tsindex 312e3ec0e9..d51ebd96dc 100644--- a/src/api/settings-service/settings-service.api.ts+++ b/src/api/settings-service/settings-service.api.ts@@ -5,6 +5,11 @@ import {SettingsSchema,SettingsValue,} from "#/types/settings";+import {+ extractAppPreferences,+ readStoredAppPreferences,+ writeStoredAppPreferences,+} from "../app-preferences-store";import { getStoredGitProviders } from "../secrets-service";import { getActiveBackend } from "../backend-registry/active-store";import {@@ -144,8 +149,14 @@ const syncDerivedSettings = (settings: Partial<Settings>): Settings => {]),) as Partial<Record<Provider, string | null>>;+ // App-level user preferences (language, git identity, sound notifications,+ // analytics consent) live in localStorage in local mode. In cloud mode the+ // server response carries them and overrides the local cache.+ const storedAppPrefs = readStoredAppPreferences();+const merged = {...deepClone(DEFAULT_SETTINGS),+ ...storedAppPrefs,...settings,provider_tokens_set: {...(DEFAULT_SETTINGS.provider_tokens_set ?? {}),@@ -321,10 +332,23 @@ class SettingsService {static async saveSettings(settings: Partial<Settings> & Record<string, unknown>,): Promise<boolean> {+ // Split app-level user-preference fields (language, git identity, sound+ // notifications, analytics consent) off before building the diff payload.+ // The local agent-server's PATCH /api/settings has no schema for these+ // and Pydantic would drop them silently; persist them in localStorage+ // instead, and forward them as flat top-level keys to the cloud POST.+ const { extracted: appPreferences, rest } = extractAppPreferences(+ settings as Record<string, unknown>,+ );+ const hasAppPreferences = Object.keys(appPreferences).length > 0;+ if (hasAppPreferences) {+ writeStoredAppPreferences(appPreferences);+ }+const payload: SettingsUpdateRequest = {};// Extract agent_settings_diff- const agentSettingsDiff = settings.agent_settings_diff as+ const agentSettingsDiff = rest.agent_settings_diff as| Record<string, SettingsValue>| undefined;if (agentSettingsDiff && Object.keys(agentSettingsDiff).length > 0) {@@ -332,7 +356,7 @@ class SettingsService {}// Extract conversation_settings_diff- const conversationSettingsDiff = settings.conversation_settings_diff as+ const conversationSettingsDiff = rest.conversation_settings_diff as| Record<string, SettingsValue>| undefined;if (@@ -343,32 +367,44 @@ class SettingsService {}// Extract disabled_skills (cloud-only β local agent-server has no skills concept)- const disabledSkills = settings.disabled_skills as string[] | undefined;+ const disabledSkills = rest.disabled_skills as string[] | undefined;if (Array.isArray(disabledSkills)) {payload.disabled_skills = disabledSkills;}- // Only call API if we have something to update- if (- !payload.agent_settings_diff &&- !payload.conversation_settings_diff &&- payload.disabled_skills === undefined- ) {- return true;- }+ const isCloud = getActiveBackend().backend.kind === "cloud";- if (getActiveBackend().backend.kind === "cloud") {- await withRetry(() => saveCloudSettings(payload));+ if (isCloud) {+ const hasCloudWork =+ !!payload.agent_settings_diff ||+ !!payload.conversation_settings_diff ||+ payload.disabled_skills !== undefined ||+ hasAppPreferences;+ if (!hasCloudWork) {+ return true;+ }+ await withRetry(() =>+ saveCloudSettings({+ ...payload,+ ...(hasAppPreferences ? { app_preferences: appPreferences } : {}),+ }),+ );} else {// The local agent-server PATCH /api/settings rejects unknown fields and// requires at least one of the two diff fields. Strip disabled_skills- // and skip the request entirely if nothing else was changed.+ // and skip the request entirely if no diffs remain. App preferences+ // are persisted to localStorage above and never sent to this endpoint.const localPayload = { ...payload };delete localPayload.disabled_skills;- if (- !localPayload.agent_settings_diff &&- !localPayload.conversation_settings_diff- ) {+ const hasLocalDiffs =+ !!localPayload.agent_settings_diff ||+ !!localPayload.conversation_settings_diff;+ if (!hasLocalDiffs) {+ if (hasAppPreferences) {+ // The localStorage write changed user-visible settings; clear the+ // in-memory cache so the next getSettings() re-derives from disk.+ clearCache();+ }return true;}await withRetry(() =>