🙌 OpenHands: AI-Driven Development
feat(agent-profiles): edit condenser and verification per profile (#18679)
simonrosenbergeb490715a598
diff --git a/.pr/profile-condenser.png b/.pr/profile-condenser.pngnew file mode 100644index 0000000000..1f6cfc8093Binary files /dev/null and b/.pr/profile-condenser.png differdiff --git a/.pr/profile-default-note.png b/.pr/profile-default-note.pngnew file mode 100644index 0000000000..8a3b3c4129Binary files /dev/null and b/.pr/profile-default-note.png differdiff --git a/.pr/profile-verification.png b/.pr/profile-verification.pngnew file mode 100644index 0000000000..58c9866db6Binary files /dev/null and b/.pr/profile-verification.png differdiff --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 b1252a1de0..4a1ec17469 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@@ -316,6 +316,9 @@ describe("AgentProfilesLocalView save mapping", () => {// profile's scope back to every configured server.mcp_server_refs: ["github"],secret_refs: null,+ // The editor's Condenser and Verification sections open on these.+ condenser: { kind: "NoOpCondenserSettings" },+ verification: { critic_enabled: true },});await user.click(screen.getByTestId("save-agent-profile-btn"));diff --git a/__tests__/components/settings/agent-profiles/profile-behavior-form.test.ts b/__tests__/components/settings/agent-profiles/profile-behavior-form.test.tsnew file mode 100644index 0000000000..c12a436bee--- /dev/null+++ b/__tests__/components/settings/agent-profiles/profile-behavior-form.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";+import {+ fromBehaviorFormValues,+ toBehaviorFormValues,+} from "#/components/features/settings/agent-profiles/profile-behavior-form";+import type { SettingsFieldSchema, SettingsSchema } from "#/types/settings";++const field = (+ key: string,+ value_type: SettingsFieldSchema["value_type"],+ defaultValue: SettingsFieldSchema["default"],+): SettingsFieldSchema =>+ ({+ key,+ label: key,+ section: key.split(".")[0],+ section_label: key.split(".")[0],+ value_type,+ default: defaultValue,+ choices: [],+ depends_on: [],+ prominence: "critical",+ secret: false,+ required: false,+ }) as SettingsFieldSchema;++const SCHEMA: SettingsSchema = {+ model_name: "AgentSettings",+ sections: [+ {+ key: "verification",+ label: "Verification",+ fields: [+ field("verification.critic_enabled", "boolean", false),+ field("verification.critic_threshold", "number", 0.6),+ field("verification.critic_api_key", "string", null),+ ],+ },+ ],+};++describe("profile behavior form", () => {+ it("round-trips a stored section, filling a missing field with its default", () => {+ const values = toBehaviorFormValues(SCHEMA, "verification", {+ critic_enabled: true,+ });++ expect(fromBehaviorFormValues(SCHEMA, "verification", values)).toEqual({+ critic_enabled: true,+ critic_threshold: 0.6,+ });+ });++ it("never reads or writes the shared critic API key", () => {+ const values = toBehaviorFormValues(SCHEMA, "verification", {+ critic_api_key: "sk-stored",+ });++ expect(values).not.toHaveProperty("verification.critic_api_key");+ expect(+ fromBehaviorFormValues(SCHEMA, "verification", {+ ...values,+ "verification.critic_api_key": "sk-typed",+ }),+ ).not.toHaveProperty("critic_api_key");+ });+});diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 267a484cb9..69dbf684e3 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -686,13 +686,18 @@ describe("AgentSettingsScreen", () => {}),);- expect(control().buildAgentProfileFields()).toEqual({+ const fields = control().buildAgentProfileFields();+ expect(fields).not.toHaveProperty("acp_server");+ expect(fields).toMatchObject({agent_kind: "openhands",mcp_server_refs: null,secret_refs: null,tools: null,tool_concurrency_limit: 1,});+ // Like a new profile, the OpenHands variant starts from the global values.+ expect(fields).toHaveProperty("condenser");+ expect(fields).toHaveProperty("verification");});it.each(["", " \t "])(@@ -1537,6 +1542,133 @@ describe("AgentSettingsScreen — skills", () => {});});+describe("AgentSettingsScreen — condenser and verification", () => {+ const STORED = {+ agent_kind: "openhands",+ mcp_server_refs: null,+ condenser: { enable_default_condenser: true, condenser_max_size: 100 },+ verification: {+ critic_enabled: true,+ critic_mode: "finish_and_message",+ enable_iterative_refinement: false,+ critic_threshold: 0.6,+ max_refinement_iterations: 3,+ critic_server_url: null,+ critic_model_name: null,+ },+ };++ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);+ acpAuthStatusMock.mockReturnValue({+ status: "unknown",+ isChecking: false,+ isSupported: true,+ });+ acpModelDiscoveryMock.mockReturnValue(NO_DISCOVERY);+ });++ it("opens on the profile's values and saves an edit to them", async () => {+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: STORED,+ });+ const maxSize = await screen.findByTestId(+ "sdk-settings-condenser.condenser_max_size",+ );+ expect(maxSize).toHaveValue(100);+ expect(control().isDirty).toBe(false);+ expect(control().buildAgentProfileFields()).not.toHaveProperty("condenser");++ const user = userEvent.setup();+ await user.clear(maxSize);+ await user.type(maxSize, "120");++ await waitFor(() => expect(control().isDirty).toBe(true));+ expect(control().buildAgentProfileFields()).toMatchObject({+ condenser: { enable_default_condenser: true, condenser_max_size: 120 },+ });+ expect(control().buildAgentProfileFields()).not.toHaveProperty(+ "verification",+ );+ });++ it("keeps the critic API key out of the profile", async () => {+ renderAgentSettingsScreen({ agentSettingsOverride: STORED });++ expect(+ await screen.findByTestId("sdk-settings-verification.critic_enabled"),+ ).toBeChecked();+ expect(+ screen.queryByTestId("sdk-settings-verification.critic_api_key"),+ ).not.toBeInTheDocument();+ });++ it("points the default profile to the global pages", async () => {+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: STORED,+ isDefaultProfile: true,+ });++ expect(+ await screen.findByTestId("agent-settings-condenser-default-profile"),+ ).toHaveTextContent("SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE");+ expect(+ screen.queryByTestId("sdk-settings-condenser.condenser_max_size"),+ ).not.toBeInTheDocument();+ expect(control().buildAgentProfileFields()).not.toHaveProperty("condenser");+ });++ it("lets the default profile edit its own values on a cloud backend", async () => {+ __resetActiveStoreForTests();+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.example.com",+ apiKey: "key",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1", orgId: null });+ try {+ render(+ <AgentSettingsScreen+ agentSettingsOverride={STORED}+ isDefaultProfile+ onSaveControlChange={() => {}}+ />,+ {+ wrapper: ({ children }) => (+ <MemoryRouter>+ <QueryClientProvider+ client={+ new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ }+ >+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ </MemoryRouter>+ ),+ },+ );++ expect(+ await screen.findByTestId("sdk-settings-condenser.condenser_max_size"),+ ).toHaveValue(100);+ expect(+ screen.queryByTestId("agent-settings-condenser-default-profile"),+ ).not.toBeInTheDocument();+ } finally {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ }+ });+});+describe("AgentSettingsScreen — system prompt", () => {beforeEach(() => {vi.restoreAllMocks();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 2aa98d38ee..51ed0233cd 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@@ -73,6 +73,8 @@ function toAgentSettingsOverride((profile as { disabled_skills?: string[] }).disabled_skills ?? [],persona: profile.persona ?? null,system_message_suffix: profile.system_message_suffix ?? null,+ condenser: (profile.condenser as SettingsValue) ?? null,+ verification: (profile.verification as unknown as SettingsValue) ?? null,};}@@ -209,7 +211,10 @@ export function AgentProfilesLocalView() {displayErrorToast(t(I18nKey.SETTINGS$AGENT_PROFILE_LLM_REQUIRED));return;}- input = { ...fields, llm_profile_ref: llmProfileRef };+ input = {+ ...fields,+ llm_profile_ref: llmProfileRef,+ } as AgentProfileSaveInput;} else {input = fields as AgentProfileSaveInput;}diff --git a/src/components/features/settings/agent-profiles/profile-behavior-form.ts b/src/components/features/settings/agent-profiles/profile-behavior-form.tsnew file mode 100644index 0000000000..15ebea5e93--- /dev/null+++ b/src/components/features/settings/agent-profiles/profile-behavior-form.ts@@ -0,0 +1,63 @@+import type { SettingsSchema, SettingsValue } from "#/types/settings";+import {+ coerceFieldValue,+ normalizeFieldValue,+ type SettingsFormValues,+} from "#/utils/sdk-settings-schema";++/** Agent-settings sections an OpenHands agent profile stores as its own. */+export type ProfileBehaviorSection = "condenser" | "verification";++/**+ * Fields of those sections that stay global: every agent shares the critic API+ * key, and the confirmation controls belong to conversation settings.+ */+export const GLOBAL_BEHAVIOR_FIELD_KEYS = new Set([+ "verification.critic_api_key",+ "verification.confirmation_mode",+ "verification.security_analyzer",+]);++function profileFields(+ schema: SettingsSchema | null | undefined,+ section: ProfileBehaviorSection,+) {+ return (+ schema?.sections+ .find((candidate) => candidate.key === section)+ ?.fields.filter((field) => !GLOBAL_BEHAVIOR_FIELD_KEYS.has(field.key)) ??+ []+ );+}++/** A stored profile section as form values; fields it lacks take the schema default. */+export function toBehaviorFormValues(+ schema: SettingsSchema | null | undefined,+ section: ProfileBehaviorSection,+ stored: Record<string, unknown>,+): SettingsFormValues {+ const prefix = `${section}.`;+ return Object.fromEntries(+ profileFields(schema, section).map((field) => [+ field.key,+ normalizeFieldValue(field, stored[field.key.slice(prefix.length)]),+ ]),+ );+}++/** Form values as the profile section to store. Throws on a value that fails coercion. */+export function fromBehaviorFormValues(+ schema: SettingsSchema | null | undefined,+ section: ProfileBehaviorSection,+ values: SettingsFormValues,+): Record<string, SettingsValue> {+ const prefix = `${section}.`;+ return Object.fromEntries(+ profileFields(schema, section)+ .filter((field) => field.key in values)+ .map((field) => [+ field.key.slice(prefix.length),+ coerceFieldValue(field, values[field.key]),+ ]),+ );+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 6aef32fb6c..fd588e3529 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -52342,5 +52342,23 @@"uk": "Типовий профіль завжди запускається з навичками, вибраними на сторінці «Навички». Щоб вибрати власні, створіть іменований профіль.","ca": "El perfil predeterminat sempre s'inicia amb les habilitats seleccionades a la pàgina Habilitats. Crea un perfil amb nom per triar-ne les seves.","id": "Profil default selalu diluncurkan dengan skill yang dipilih di halaman Skill. Buat profil bernama untuk memilih skill-nya sendiri."+ },+ "SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE": {+ "en": "The default profile always launches with the global Condenser and Verification settings. Create a named profile to choose its own.",+ "ja": "デフォルトのプロファイルは常にグローバルなコンデンサーと検証の設定で起動します。独自の設定を選ぶには、名前付きのプロファイルを作成してください。",+ "zh-CN": "默认配置文件始终使用全局的压缩器和验证设置启动。如需单独设置,请创建一个命名配置文件。",+ "zh-TW": "預設設定檔一律以全域的壓縮器和驗證設定啟動。若要單獨設定,請建立具名設定檔。",+ "ko-KR": "기본 프로필은 항상 전역 압축기 및 검증 설정으로 시작됩니다. 별도로 설정하려면 이름이 있는 프로필을 만드세요.",+ "no": "Standardprofilen starter alltid med de globale innstillingene for kondensator og verifisering. Opprett en navngitt profil for å velge egne.",+ "it": "Il profilo predefinito si avvia sempre con le impostazioni globali di condensatore e verifica. Crea un profilo con nome per sceglierne di proprie.",+ "pt": "O perfil padrão sempre inicia com as configurações globais de condensador e verificação. Crie um perfil com nome para escolher as suas.",+ "es": "El perfil predeterminado siempre se inicia con la configuración global de condensador y verificación. Crea un perfil con nombre para elegir la suya.",+ "ar": "يبدأ الملف الشخصي الافتراضي دائمًا بإعدادات المكثف والتحقق العامة. أنشئ ملفًا شخصيًا باسم لاختيار إعداداته الخاصة.",+ "fr": "Le profil par défaut démarre toujours avec les paramètres globaux du condenseur et de la vérification. Créez un profil nommé pour choisir les siens.",+ "tr": "Varsayılan profil her zaman genel yoğunlaştırıcı ve doğrulama ayarlarıyla başlar. Kendi ayarlarını seçmek için adlandırılmış bir profil oluşturun.",+ "de": "Das Standardprofil startet immer mit den globalen Einstellungen für Kondensator und Verifizierung. Erstellen Sie ein benanntes Profil, um eigene festzulegen.",+ "uk": "Типовий профіль завжди запускається з глобальними налаштуваннями конденсатора та верифікації. Щоб вибрати власні, створіть іменований профіль.",+ "ca": "El perfil predeterminat sempre s’inicia amb la configuració global del condensador i la verificació. Crea un perfil amb nom per triar-ne la seva.",+ "id": "Profil default selalu diluncurkan dengan pengaturan Condenser dan Verifikasi global. Buat profil bernama untuk memilih pengaturannya sendiri."}}diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex 61c3210ab2..c665dd670a 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -6,6 +6,16 @@ import { useAgentSettingsSchema } from "#/hooks/query/use-agent-settings-schema"import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";import { SettingsInput } from "#/components/features/settings/settings-input";import { SchemaField } from "#/components/features/settings/sdk-settings/schema-field";+import {+ SdkSectionPage,+ type SdkSectionSaveControl,+} from "#/components/features/settings/sdk-settings/sdk-section-page";+import {+ fromBehaviorFormValues,+ GLOBAL_BEHAVIOR_FIELD_KEYS,+ toBehaviorFormValues,+ type ProfileBehaviorSection,+} from "#/components/features/settings/agent-profiles/profile-behavior-form";import { AcpCredentialsSection } from "#/components/features/settings/acp-credentials-section";import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";import { BrandButton } from "#/components/features/settings/brand-button";@@ -19,10 +29,17 @@ import { Typography } from "#/ui/typography";import { I18nKey } from "#/i18n/declaration";import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";import { cn } from "#/utils/utils";-import { SettingsFieldSchema, SettingsValue } from "#/types/settings";+import {+ Settings,+ SettingsFieldSchema,+ SettingsSchema,+ SettingsValue,+} from "#/types/settings";import {coerceFieldValue,+ inferInitialView,normalizeFieldValue,+ type SettingsView,} from "#/utils/sdk-settings-schema";import {ACP_CUSTOM_PRESET_KEY,@@ -65,6 +82,14 @@ import { useSearchSecrets } from "#/hooks/query/use-get-secrets";export const handle = { hideTitle: true };+const PROFILE_BEHAVIOR_BLOCKS: ReadonlyArray<{+ section: ProfileBehaviorSection;+ titleKey: I18nKey;+}> = [+ { section: "condenser", titleKey: I18nKey.SETTINGS$NAV_CONDENSER },+ { section: "verification", titleKey: I18nKey.SETTINGS$NAV_VERIFICATION },+];+type AgentType = "openhands" | "acp";type AgentSettingsSnapshot = {@@ -150,6 +175,8 @@ export type AgentProfileFieldsDraft =tools?: ProfileToolSpec[] | null;persona?: string | null;system_message_suffix?: string | null;+ condenser?: Record<string, SettingsValue>;+ verification?: Record<string, SettingsValue>;}| {agent_kind: "acp";@@ -190,6 +217,9 @@ export interface AgentProfileFieldsInput {systemPromptText: string;/** False when the section is hidden, so neither prompt field is written. */systemPromptEditable: boolean;+ /** Profile sections to store; an absent one keeps the stored value. */+ condenser?: Record<string, SettingsValue>;+ verification?: Record<string, SettingsValue>;}/**@@ -234,6 +264,8 @@ export function buildAgentProfileFields(systemPromptMode,systemPromptText,systemPromptEditable,+ condenser,+ verification,} = input;// Both are base-model fields, so they ride both variants. `mcp_server_refs`// needs no version gate — it has existed since agent profiles shipped, below@@ -272,6 +304,8 @@ export function buildAgentProfileFields(fields.system_message_suffix = systemPromptMode === "append" ? text : null;fields.persona = systemPromptMode === "custom" ? text : null;}+ if (condenser) fields.condenser = condenser;+ if (verification) fields.verification = verification;if (toolCatalogLoaded) {fields.tools = buildProfileToolsValue({mode: toolsMode,@@ -725,6 +759,98 @@ export function AgentSettingsScreen({setSelectedSecrets(initialSecretRefs.selected);}, [initialSecretRefs]);+ // --- Condenser and verification (OpenHands; stored on the profile) ---+ // A local `default` launches from the global settings, so its own copy would be ignored.+ const behaviorEditable = !isDefaultProfile || backendKind === "cloud";+ const [behaviorControls, setBehaviorControls] = useState<+ Partial<Record<ProfileBehaviorSection, SdkSectionSaveControl>>+ >({});+ const behaviorControlHandlers = React.useMemo(+ () =>+ Object.fromEntries(+ PROFILE_BEHAVIOR_BLOCKS.map(({ section }) => [+ section,+ (control: SdkSectionSaveControl) =>+ setBehaviorControls((previous) => ({+ ...previous,+ [section]: control,+ })),+ ]),+ ) as Record<+ ProfileBehaviorSection,+ (control: SdkSectionSaveControl) => void+ >,+ [],+ );+ // A new profile has no stored sections and starts from the global values.+ const storedBehavior = React.useMemo(() => {+ const asRecord = (value: unknown) =>+ value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+ return {+ condenser: asRecord(agentSettingsOverride?.condenser),+ verification: asRecord(agentSettingsOverride?.verification),+ };+ }, [agentSettingsOverride]);+ const behaviorInitialValues = React.useMemo(+ () => ({+ condenser: storedBehavior.condenser+ ? toBehaviorFormValues(schema, "condenser", storedBehavior.condenser)+ : undefined,+ verification: storedBehavior.verification+ ? toBehaviorFormValues(+ schema,+ "verification",+ storedBehavior.verification,+ )+ : undefined,+ }),+ [schema, storedBehavior],+ );+ // Open each section on the view its stored values need, not the global one.+ const behaviorInitialView = React.useMemo(+ () =>+ Object.fromEntries(+ PROFILE_BEHAVIOR_BLOCKS.map(({ section }) => {+ const stored = storedBehavior[section];+ return [+ section,+ stored+ ? (current: Settings, filteredSchema: SettingsSchema) =>+ inferInitialView(+ {+ ...current,+ agent_settings: {+ ...current.agent_settings,+ [section]: stored as SettingsValue,+ },+ },+ filteredSchema,+ )+ : undefined,+ ];+ }),+ ) as Record<+ ProfileBehaviorSection,+ | ((current: Settings, filteredSchema: SettingsSchema) => SettingsView)+ | undefined+ >,+ [storedBehavior],+ );+ const behaviorDirty =+ behaviorEditable &&+ Boolean(+ behaviorControls.condenser?.isDirty ||+ behaviorControls.verification?.isDirty,+ );+ const behaviorToSave = (section: ProfileBehaviorSection) => {+ const control = behaviorControls[section];+ if (!behaviorEditable || !control) return undefined;+ if (!control.isDirty && storedBehavior[section]) return undefined;+ return fromBehaviorFormValues(schema, section, control.values);+ };+// --- Save control ---// Ref-backed so the exposed builder/credential fns read the freshest state at// call time without re-emitting the control on every keystroke (mirrors@@ -778,7 +904,9 @@ export function AgentSettingsScreen({? commandText !== loadedSnapshot.commandText ||acpModel !== loadedSnapshot.acpModel ||isCustomAcpModel !== loadedSnapshot.isCustomAcpModel- : toolConcurrency !== initialToolConcurrency || systemPromptDirty);+ : toolConcurrency !== initialToolConcurrency ||+ systemPromptDirty ||+ behaviorDirty);const credentialsDirty = acpCredentialForm.isDirty;const isAnyDirty =settingsDirty ||@@ -901,6 +1029,8 @@ export function AgentSettingsScreen({systemPromptMode,systemPromptText,systemPromptEditable: showSystemPrompt,+ condenser: behaviorToSave("condenser"),+ verification: behaviorToSave("verification"),});const isSaving = acpCredentialForm.isSaving;@@ -1213,6 +1343,45 @@ export function AgentSettingsScreen({</Typography.Text></div>+ {!isAcp+ ? PROFILE_BEHAVIOR_BLOCKS.map(({ section, titleKey }) => (+ <div+ key={section}+ className="flex flex-col gap-2.5"+ data-testid={`agent-settings-${section}`}+ >+ <Typography.Text className="text-sm">+ {t(titleKey)}+ </Typography.Text>+ {behaviorEditable ? (+ <SdkSectionPage+ settingsSources={[+ {+ settingsSource: "agent_settings",+ sectionKeys: [section],+ excludeKeys: GLOBAL_BEHAVIOR_FIELD_KEYS,+ },+ ]}+ embedded+ hideSaveButton+ markInitialOverridesDirty={false}+ initialValueOverrides={behaviorInitialValues[section]}+ getInitialView={behaviorInitialView[section]}+ onSaveControlChange={behaviorControlHandlers[section]}+ testId={`agent-settings-${section}-fields`}+ />+ ) : (+ <Typography.Text+ testId={`agent-settings-${section}-default-profile`}+ className="text-xs text-tertiary-alt"+ >+ {t(I18nKey.SETTINGS$AGENT_PROFILE_BEHAVIOR_DEFAULT_PROFILE)}+ </Typography.Text>+ )}+ </div>+ ))+ : null}+{secretRefsSupportedOnProfile ? (<div className="flex flex-col gap-2.5"><Typography.Text className="text-sm">