🙌 OpenHands: AI-Driven Development
refactor(agent-settings): remove the unreachable non-embedded mode (#17825)
simonrosenbergc391626cdfeb
diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsxindex 10e520cf39..dbf60bd588 100644--- a/__tests__/routes/agent-settings.test.tsx+++ b/__tests__/routes/agent-settings.test.tsx@@ -1,5 +1,5 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { render, screen, waitFor } from "@testing-library/react";+import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { MemoryRouter } from "react-router";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -13,6 +13,7 @@ import { SecretsService } from "#/api/secrets-service";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import { Settings } from "#/types/settings";import { ACP_PROVIDERS } from "#/constants/acp-providers";+import { parseCommand } from "#/utils/acp-command";const CLAUDE_COMMAND = getClientAcpProvider("claude-code")!.default_command;const CODEX_COMMAND = getClientAcpProvider("codex")!.default_command;@@ -23,9 +24,9 @@ vi.mock("#/hooks/query/use-acp-auth-status", () => ({useAcpAuthStatus: (...args: unknown[]) => acpAuthStatusMock(...args),}));-// The profile editor gates the LLM-switching toggle on the backend's *profile*-// model, which gained the field later than the settings schema did. Stub the-// probe so both sides of that gate are reachable without a live server.+// The LLM-switching toggle is gated on the backend's *profile* model, which+// gained the field later than the settings schema did. Stub the probe so both+// sides of that gate are reachable without a live server.const profileSupportsSwitchLlmToolMock = vi.hoisted(() => vi.fn(() => true));const profileSupportsSecretRefsMock = vi.hoisted(() => vi.fn(() => true));vi.mock("#/api/agent-profiles-service/profile-field-support", () => ({@@ -42,8 +43,7 @@ vi.mock("#/hooks/query/use-get-secrets", () => ({useSearchSecrets: () => ({ data: savedSecretsMock() }),}));-// Observe save toasts so we can assert the single Save shows one confirmation,-// not one per persisted thing (agent spec + credentials).+// Observe toasts so a silent credential save can be asserted as silent.const toastMocks = vi.hoisted(() => ({success: vi.fn(),error: vi.fn(),@@ -65,29 +65,46 @@ function buildSettings(overrides: Partial<Settings> = {}): Settings {}function renderAgentSettingsScreen(- props: React.ComponentProps<typeof AgentSettingsScreen> = {},+ props: Partial<React.ComponentProps<typeof AgentSettingsScreen>> = {},) {- return render(<AgentSettingsScreen {...props} />, {- wrapper: ({ children }) => (- <MemoryRouter>- <QueryClientProvider- client={- new QueryClient({ defaultOptions: { queries: { retry: false } } })- }- >- {children}- </QueryClientProvider>- </MemoryRouter>- ),- });+ let control: AgentSettingsSaveControl | null = null;+ const view = render(+ <AgentSettingsScreen+ onSaveControlChange={(next) => {+ control = next;+ }}+ {...props}+ />,+ {+ wrapper: ({ children }) => (+ <MemoryRouter>+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ {children}+ </QueryClientProvider>+ </MemoryRouter>+ ),+ },+ );+ return { ...view, control: () => control! };}+const CLAUDE_PROFILE = {+ agent_kind: "acp",+ acp_server: "claude-code",+ acp_command: [],+ acp_args: [],+ acp_model: "",+};+describe("AgentSettingsScreen", () => {beforeEach(() => {vi.restoreAllMocks();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- // The page owns the ACP credential form (single Save), so it reads/writes- // secrets even on non-ACP renders.+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());+ // The form owns the ACP credential form, which reads secrets on mount.vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);vi.spyOn(SecretsService, "createSecret").mockResolvedValue();acpAuthStatusMock.mockReturnValue({@@ -108,125 +125,55 @@ describe("AgentSettingsScreen", () => {});it("renders the agent type selector defaulting to OpenHands with sub-agents toggle", async () => {- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- renderAgentSettingsScreen();+ renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-settings-screen");- expect(screen.getByTestId("agent-type-selector")).toBeInTheDocument();- // Sub-agents toggle visible on the OpenHands branch.++ expect(screen.getByLabelText("SETTINGS$NAV_AGENT")).toHaveValue(+ "SETTINGS$AGENT_TYPE_OPENHANDS",+ );expect(screen.getByTestId("agent-settings-enable-sub-agents"),).toBeInTheDocument();- // ACP-only fields stay hidden on the OpenHands branch.expect(screen.queryByTestId("agent-command-input")).not.toBeInTheDocument();});- it("labels the save button 'Save Changes' for consistency with other settings pages", async () => {- // Arrange — render with any valid settings; the label is independent- // of the form's state.- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- // Act- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");-- // Assert — t() is stubbed to return the key, so the rendered text is- // the translation key. SETTINGS$SAVE_CHANGES = "Save Changes" in- // public/locales/en/openhands.json; BUTTON$SAVE = "Save" (the bug).- expect(screen.getByTestId("agent-save-button")).toHaveTextContent(- "SETTINGS$SAVE_CHANGES",- );- });-- it("saves enable_sub_agents when toggling on the OpenHands path", async () => {+ it("builds enable_sub_agents from its toggle", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- enable_sub_agents: false,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_sub_agents: false,+ },+ });await screen.findByTestId("agent-settings-screen");- // Toggle sub-agents on via the enclosing labelconst toggle = screen.getByTestId("agent-settings-enable-sub-agents");- const label = toggle.closest("label")!;- await user.click(label);+ await user.click(toggle.closest("label")!);- await user.click(screen.getByTestId("agent-save-button"));-- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff).toEqual({- agent_kind: "openhands",+ expect(control().buildAgentProfileFields()).toMatchObject({enable_sub_agents: true,- enable_switch_llm_tool: true,- tool_concurrency_limit: 1,});});- it("renders the LLM-switching toggle on the OpenHands path and saves it when toggled off", async () => {+ it("builds enable_switch_llm_tool from its toggle", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- enable_switch_llm_tool: true,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: {+ agent_kind: "openhands",+ enable_switch_llm_tool: true,+ },+ });await screen.findByTestId("agent-settings-screen");- // The toggle renders (schema exposes the field) and starts on.const toggle = screen.getByTestId("agent-settings-enable-switch-llm-tool");expect(toggle).toBeChecked();+ await user.click(toggle.closest("label")!);- // Toggle it off via the enclosing label, then save.- const label = toggle.closest("label")!;- await user.click(label);expect(toggle).not.toBeChecked();-- await user.click(screen.getByTestId("agent-save-button"));-- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff).toEqual({- agent_kind: "openhands",- enable_sub_agents: false,+ expect(control().buildAgentProfileFields()).toMatchObject({enable_switch_llm_tool: false,- tool_concurrency_limit: 1,});});@@ -242,16 +189,12 @@ describe("AgentSettingsScreen", () => {})),};vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings_schema: schemaWithoutField,- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),+ buildSettings({ agent_settings_schema: schemaWithoutField }),);- renderAgentSettingsScreen();+ renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-settings-screen");// Older agent-servers without the field hide the toggle cleanly...@@ -264,22 +207,13 @@ describe("AgentSettingsScreen", () => {).toBeInTheDocument();});- it("hides the LLM-switching toggle in the profile editor when the profile model predates the field", async () => {+ it("hides the LLM-switching toggle when the profile model predates the field", async () => {// agent-server 1.29.0–1.30.x advertises the field in the settings schema// while `OpenHandsAgentProfile` still rejects it. Rendering the toggle// there would offer a control whose save the server refuses outright.profileSupportsSwitchLlmToolMock.mockReturnValue(false);- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: { agent_kind: "openhands" },});await screen.findByTestId("agent-settings-screen");@@ -292,135 +226,59 @@ describe("AgentSettingsScreen", () => {).toBeInTheDocument();});- it("renders the LLM-switching toggle in the profile editor once the profile model carries the field", async () => {- profileSupportsSwitchLlmToolMock.mockReturnValue(true);- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- renderAgentSettingsScreen({- embedded: true,- agentSettingsOverride: { agent_kind: "openhands" },- });- await screen.findByTestId("agent-settings-screen");-- expect(- screen.getByTestId("agent-settings-enable-switch-llm-tool"),- ).toBeInTheDocument();- });-- it("keeps the LLM-switching toggle in non-embedded mode even when the profile model predates the field", async () => {- // Non-embedded, the form writes `agent_settings`, which has accepted the- // key since 1.22.0. The profile-model gap must not reach back and hide it.- // (That mode has no route today — #1571 turned /settings/agent into a- // redirect — but the gate should stay scoped to what it actually knows.)- profileSupportsSwitchLlmToolMock.mockReturnValue(false);- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");-- expect(- screen.getByTestId("agent-settings-enable-switch-llm-tool"),- ).toBeInTheDocument();- });-- it("saves tool_concurrency_limit when changed on the OpenHands path", async () => {+ it("builds tool_concurrency_limit from the input on the OpenHands path", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- enable_sub_agents: false,- tool_concurrency_limit: 1,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: {+ agent_kind: "openhands",+ tool_concurrency_limit: 1,+ },+ });await screen.findByTestId("agent-settings-screen");const input = screen.getByTestId("sdk-settings-tool_concurrency_limit");await user.clear(input);await user.type(input, "4");- await user.click(screen.getByTestId("agent-save-button"));-- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };// Coerced to a number (not the raw input string) via the shared// schema-driven coercion.- expect(call.agent_settings_diff?.tool_concurrency_limit).toBe(4);+ expect(control().buildAgentProfileFields()).toMatchObject({+ tool_concurrency_limit: 4,+ });});- it("hides sub-agents toggle when ACP is selected", async () => {+ it("hides the sub-agents toggle when ACP is selected", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- renderAgentSettingsScreen();+ renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-settings-screen");-- // Sub-agents toggle should be visible initiallyexpect(screen.getByTestId("agent-settings-enable-sub-agents"),).toBeInTheDocument();- // Switch to ACPawait user.click(screen.getByTestId("agent-type-selector"));await user.click(await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),);- // Sub-agents toggle should be hidden, ACP fields should appearexpect(screen.queryByTestId("agent-settings-enable-sub-agents"),).not.toBeInTheDocument();expect(screen.getByTestId("agent-command-input")).toBeInTheDocument();});- it("shows the ACP form when the active agent_kind is acp", async () => {- // Use a model ID that isn't in CLAUDE_MODELS so the form falls through to- // the custom-input branch — that's the path this test is asserting (saved- // value round-trips into the visible input). Known IDs go through the- // dropdown instead and are covered separately.- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],- acp_model: "my-pinned-fork-model",- },- }),- );+ it("opens a stored ACP profile on its command and custom model", async () => {+ // A model ID outside the provider's suggestions falls through to the+ // custom input; known IDs go through the dropdown instead.+ renderAgentSettingsScreen({+ agentSettingsOverride: {+ ...CLAUDE_PROFILE,+ acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],+ acp_model: "my-pinned-fork-model",+ },+ });- renderAgentSettingsScreen();const commandInput = (await screen.findByTestId("agent-command-input",)) as HTMLTextAreaElement;@@ -434,19 +292,7 @@ describe("AgentSettingsScreen", () => {});it("defaults built-in ACP providers to a suggested model when none is saved", async () => {- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- acp_model: null,- },- }),- );-- renderAgentSettingsScreen();+ renderAgentSettingsScreen({ agentSettingsOverride: CLAUDE_PROFILE });await screen.findByTestId("agent-command-input");expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(@@ -454,159 +300,80 @@ describe("AgentSettingsScreen", () => {);});- it("saves the selected built-in ACP model", async () => {+ it("builds the selected built-in ACP model", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- acp_model: null,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });- renderAgentSettingsScreen();await screen.findByTestId("agent-command-input");await user.click(screen.getByLabelText("SETTINGS$AGENT_MODEL"));await user.click(await screen.findByText("Claude Haiku"));- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);+ expect(control().buildAgentProfileFields()).toMatchObject({+ acp_model: "haiku",});- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_model).toBe("haiku");});it("clears the model when switching from a built-in provider to Custom", async () => {- // F3 from review: built-ins seed ``acp_model`` to their registered- // ``default_model`` on load. Picking Custom must not leak that built-in- // default into custom settings — otherwise a user choosing Custom from- // Claude Code would silently save ``acp_model: "claude-opus-4-7"`` on an+ // Picking Custom must not leak the built-in default model onto an// unrelated wrapper.const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- acp_model: null,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });await screen.findByTestId("agent-command-input");- // Form loads with the Claude Code default visible.expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue("Claude Opus (1M)",);- // Switch to the Custom preset, then enter a different command — the- // form's ``selectedPreset`` re-derives from the command text, so the- // save path only treats it as Custom once the command no longer matches- // a built-in provider's default.await user.click(screen.getByTestId("agent-preset-selector"));await user.click(await screen.findByRole("option", {name: "SETTINGS$AGENT_PRESET_CUSTOM",}),);- const commandInput = screen.getByTestId(- "agent-command-input",- ) as HTMLTextAreaElement;+ const commandInput = screen.getByTestId("agent-command-input");await user.clear(commandInput);await user.type(commandInput, "my-custom-acp --flag");- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);+ expect(control().buildAgentProfileFields()).toMatchObject({+ acp_server: "custom",+ acp_command: "my-custom-acp --flag",+ acp_model: null,});-- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- // Custom preset has no registered default — saved acp_model must be null,- // not the inherited Claude Opus default.- expect(call.agent_settings_diff?.acp_server).toBe("custom");- expect(call.agent_settings_diff?.acp_model).toBeNull();});it("reconciles the model when the command is retyped to a different provider", async () => {- // Editing the command textarea (rather than the preset dropdown) into a- // different built-in provider must not leave the previous provider's model- // selected — otherwise Save would persist e.g. ``claude-opus-4-7`` against- // a Codex wrapper. The detected preset changes, so the model reconciles to- // the new provider's default.+ // The textarea is the other way to change provider, so it must drop the+ // previous provider's model just like the preset dropdown does.const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- acp_model: null,- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });await screen.findByTestId("agent-command-input");- expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(- "Claude Opus (1M)",- );- const commandInput = screen.getByTestId(- "agent-command-input",- ) as HTMLTextAreaElement;+ const commandInput = screen.getByTestId("agent-command-input");await user.clear(commandInput);await user.type(commandInput, CODEX_COMMAND.join(" "));- // The model field now reflects the Codex default, not the stale Claude one.expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue("GPT-5.5",);-- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);+ expect(control().buildAgentProfileFields()).toMatchObject({+ acp_server: "codex",+ acp_command: null,+ acp_model: "gpt-5.5",});-- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_server).toBe("codex");- expect(call.agent_settings_diff?.acp_model).toBe("gpt-5.5");});- it("saves an ACP diff when switching to ACP + Claude Code", async () => {+ it("prefills Claude Code when switching to ACP", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-settings-screen");- // Switching to ACP prefills the command from the first registered provider- // (Claude Code).await user.click(screen.getByTestId("agent-type-selector"));await user.click(await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),@@ -616,49 +383,24 @@ describe("AgentSettingsScreen", () => {"agent-command-input",)) as HTMLTextAreaElement;expect(commandInput.value).toBe(CLAUDE_COMMAND.join(" "));- expect(screen.getByLabelText("SETTINGS$AGENT_MODEL")).toHaveValue(- "Claude Opus (1M)",- );-- await user.click(screen.getByTestId("agent-save-button"));-- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff).toEqual({+ expect(control().buildAgentProfileFields()).toEqual({agent_kind: "acp",+ mcp_server_refs: null,+ secret_refs: null,acp_server: "claude-code",- // The default-command path stores acp_command: [] and lets the registry- // resolve it on the agent-server side. Round-tripping verbatim would- // pin a stale command if the registry default changes upstream.- acp_command: [],- // ``acp_args: []`` is reset on every save so an API-set- // ``acp_args`` can't survive and concatenate onto the spawn- // command at conversation-create time.- acp_args: [],+ // The default command is left to the registry rather than pinned.+ acp_command: null,+ acp_args: null,acp_model: "opus[1m]",});});- it("clears ACP fields when switching back to OpenHands", async () => {+ it("drops the ACP fields when switching back to OpenHands", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });+ await screen.findByTestId("agent-command-input");await user.click(screen.getByTestId("agent-type-selector"));await user.click(@@ -666,194 +408,88 @@ describe("AgentSettingsScreen", () => {name: "SETTINGS$AGENT_TYPE_OPENHANDS",}),);- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff).toEqual({+ expect(control().buildAgentProfileFields()).toEqual({agent_kind: "openhands",+ mcp_server_refs: null,+ secret_refs: null,enable_sub_agents: false,enable_switch_llm_tool: true,tool_concurrency_limit: 1,});});- it("disables Save when the user has cleared the command on the ACP path", async () => {- const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],- },- }),- );-- renderAgentSettingsScreen();- const cmd = (await screen.findByTestId(- "agent-command-input",- )) as HTMLTextAreaElement;- const save = screen.getByTestId("agent-save-button") as HTMLButtonElement;-- // Clear the field. Save should be disabled (the agent-server would- // crash on an empty acp_command and the adapter has no way to- // recover — better to block the save than silently submit garbage).- await user.clear(cmd);- expect(save).toBeDisabled();- });+ it.each(["", " \t "])(+ "is invalid when the ACP command is %j",+ async (command) => {+ // The agent-server cannot spawn an empty command.+ const user = userEvent.setup();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });+ const cmd = await screen.findByTestId("agent-command-input");+ expect(control().isValid).toBe(true);- it("treats whitespace-only as empty and keeps Save disabled", async () => {- const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],- },- }),- );+ await user.clear(cmd);+ if (command) await user.type(cmd, command);- renderAgentSettingsScreen();- const cmd = (await screen.findByTestId(- "agent-command-input",- )) as HTMLTextAreaElement;- const save = screen.getByTestId("agent-save-button") as HTMLButtonElement;- await user.clear(cmd);- await user.type(cmd, " \t ");- expect(save).toBeDisabled();- });+ expect(control().isValid).toBe(false);+ },+ );- it("preserves a Custom command with quoted args end-to-end", async () => {- // Regression guard for the .split-vs-shell-quote bug: a Custom- // command like ``bash -c "echo hi"`` used to get tokenised as- // ``["bash","-c","\"echo","hi\""]`` and silently fail at spawn.+ it("round-trips a Custom command with quoted args", async () => {+ // ``bash -c "echo hi"`` must not tokenise as+ // ``["bash","-c","\"echo","hi\""]``.const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");-- await user.click(screen.getByTestId("agent-type-selector"));- await user.click(- await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),- );- const cmd = (await screen.findByTestId(- "agent-command-input",- )) as HTMLTextAreaElement;+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });+ const cmd = await screen.findByTestId("agent-command-input");await user.clear(cmd);await user.type(cmd, 'bash -c "echo hi"');- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_command).toEqual([- "bash",- "-c",- "echo hi",- ]);- // Anything that diverges from a built-in default-command snaps to- // the Custom preset.- expect(call.agent_settings_diff?.acp_server).toBe("custom");+ const fields = control().buildAgentProfileFields();+ expect(fields).toMatchObject({ acp_server: "custom" });+ expect(+ parseCommand((fields as { acp_command: string }).acp_command),+ ).toEqual(["bash", "-c", "echo hi"]);});- it("preserves the registry default when acp_command:[] + non-empty acp_args is loaded", async () => {- // Regression guard for the data-corruption bug:- //- // stored: acp_server: 'claude-code', acp_command: [], acp_args:- // ['--extra-arg']- // actual spawn: ['npx', '-y', '@agentclientprotocol/claude-agent-acp',- // '--extra-arg']- //- // The form used to merge acp_command + acp_args literally and would- // show only ``--extra-arg`` in the textarea. Saving then sent- // ``acp_command: ['--extra-arg']`` and flipped the preset to- // ``custom``, silently dropping the registry-default prefix.- // The load path must expand the default *before* merging with args.+ it("keeps the registry default when a profile stores only acp_args", async () => {+ // The default command must be expanded before the args are appended, or+ // an edit would save the bare args and drop the provider's command.const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- acp_args: ["--extra-arg"],- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: { ...CLAUDE_PROFILE, acp_args: ["--extra-arg"] },+ });const cmd = (await screen.findByTestId("agent-command-input",)) as HTMLTextAreaElement;expect(cmd.value).toBe(`${CLAUDE_COMMAND.join(" ")} --extra-arg`);- // 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} --saved");- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_server).toBe("custom");- expect(call.agent_settings_diff?.acp_command).toEqual([- ...CLAUDE_COMMAND,- "--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([]);+ const fields = control().buildAgentProfileFields();+ expect(fields).toMatchObject({ acp_server: "custom", acp_args: null });+ expect(+ parseCommand((fields as { acp_command: string }).acp_command),+ ).toEqual([...CLAUDE_COMMAND, "--extra-arg", "--saved"]);});- it("disables Save after reverting an agent-type dropdown change", async () => {+ it("is clean again after reverting an agent-type change", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-type-selector");- const save = screen.getByTestId("agent-save-button") as HTMLButtonElement;- expect(save).toBeDisabled();+ expect(control().isDirty).toBe(false);await user.click(screen.getByTestId("agent-type-selector"));await user.click(await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),);- expect(save).not.toBeDisabled();+ expect(control().isDirty).toBe(true);await user.click(screen.getByTestId("agent-type-selector"));await user.click(@@ -861,126 +497,17 @@ describe("AgentSettingsScreen", () => {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- // future provider that hasn't been mirrored into ``ACP_PROVIDERS``- // yet) opens Settings → Agent and clicks Save. Without preservation- // the save flow demotes ``acp_server: "amp"`` → ``acp_server:- // "custom"`` because ``detectPreset`` returns ``custom`` for any- // unknown server. The original key name is silently lost.- //- // The fix is narrow: when the user hasn't touched the command since- // load AND the loaded server is non-empty, non-``"custom"``, and- // absent from ``ACP_PROVIDERS``, write the loaded key back verbatim- // via the ``allowUnknownServer`` pass-through.- const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "amp",- acp_command: ["npx", "-y", "@some-future/amp-acp"],- acp_args: [],- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();- const cmd = (await screen.findByTestId(- "agent-command-input",- )) as HTMLTextAreaElement;- expect(cmd.value).toBe("npx -y @some-future/amp-acp");-- // 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(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_server).toBe("amp");- expect(call.agent_settings_diff?.acp_command).toEqual([- "npx",- "-y",- "@some-future/amp-acp",- ]);- });-- it("demotes an unknown loaded acp_server to 'custom' when the user edits the command", async () => {- // Counterpart to the preserve test: editing the command is a- // material change of configuration, so it's correct to drop the- // unknown ``amp`` key and fall back to ``"custom"``. The user is- // configuring a new command, not preserving the prior one — so- // the preset name follows the command.- const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "amp",- acp_command: ["npx", "-y", "@some-future/amp-acp"],- acp_args: [],- },- }),- );- const save = vi.spyOn(SettingsService, "saveSettings");-- renderAgentSettingsScreen();- const cmd = (await screen.findByTestId(- "agent-command-input",- )) as HTMLTextAreaElement;-- // Actually change the command — append a flag so the textarea- // differs from the loaded value.- await user.click(cmd);- await user.keyboard("{End} --new-flag");-- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(save).toHaveBeenCalledTimes(1);- });- const call = save.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- };- expect(call.agent_settings_diff?.acp_server).toBe("custom");- expect(call.agent_settings_diff?.acp_command).toEqual([- "npx",- "-y",- "@some-future/amp-acp",- "--new-flag",- ]);+ expect(control().isDirty).toBe(false);});- it("a single Save persists ACP credentials together with the agent spec", async () => {+ it("saves typed ACP credentials through the save control", async () => {const user = userEvent.setup();- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- agent_kind: "openhands",- },- }),- );- const saveSettings = vi.spyOn(SettingsService, "saveSettings");const createSecret = vi.spyOn(SecretsService, "createSecret");-- renderAgentSettingsScreen();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: { agent_kind: "openhands" },+ });await screen.findByTestId("agent-settings-screen");- // Switch to ACP (Claude Code prefilled) and paste a credential, then click- // the single page-level Save button.await user.click(screen.getByTestId("agent-type-selector"));await user.click(await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),@@ -989,65 +516,37 @@ describe("AgentSettingsScreen", () => {await screen.findByTestId("settings-acp-secret-ANTHROPIC_API_KEY"),"sk-ant-xyz",);+ expect(control().credentials.isDirty).toBe(true);- await user.click(screen.getByTestId("agent-save-button"));-- // One click persists both: the credential as a secret AND the agent spec.- await waitFor(() => {- expect(createSecret).toHaveBeenCalledWith(- "ANTHROPIC_API_KEY",- "sk-ant-xyz",- undefined,- );- expect(saveSettings).toHaveBeenCalledTimes(1);+ let saved = false;+ await act(async () => {+ saved = await control().credentials.save({ silent: true });});- const diff = (- saveSettings.mock.calls[0]?.[0] as {- agent_settings_diff?: Record<string, unknown>;- }- ).agent_settings_diff;- expect(diff?.agent_kind).toBe("acp");- expect(diff?.acp_server).toBe("claude-code");-- // One click → one confirmation, even though it persisted both the spec and- // the credential (the credential save is silenced so it doesn't double up).- expect(toastMocks.success).toHaveBeenCalledTimes(1);- });- it("a credentials-only change saves the secret without re-writing settings", async () => {- const user = userEvent.setup();- // Already on ACP, so loading introduces no settings change.- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- },- }),+ expect(saved).toBe(true);+ expect(createSecret).toHaveBeenCalledWith(+ "ANTHROPIC_API_KEY",+ "sk-ant-xyz",+ undefined,);- const saveSettings = vi.spyOn(SettingsService, "saveSettings");- const createSecret = vi.spyOn(SecretsService, "createSecret");+ // The editor owns the single "saved" toast.+ expect(toastMocks.success).not.toHaveBeenCalled();+ });- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");+ it("a credentials-only edit marks the form dirty", async () => {+ const user = userEvent.setup();+ const { control } = renderAgentSettingsScreen({+ agentSettingsOverride: CLAUDE_PROFILE,+ });+ await screen.findByTestId("agent-command-input");+ expect(control().isDirty).toBe(false);await user.type(await screen.findByTestId("settings-acp-secret-ANTHROPIC_API_KEY"),"sk-ant-only",);- await user.click(screen.getByTestId("agent-save-button"));- await waitFor(() => {- expect(createSecret).toHaveBeenCalledWith(- "ANTHROPIC_API_KEY",- "sk-ant-only",- undefined,- );- });- // No spec change → no settings write (and no double toast).- expect(saveSettings).not.toHaveBeenCalled();+ expect(control().isDirty).toBe(true);});it("shows the 'already signed in' banner in the credentials section when authenticated", async () => {@@ -1056,18 +555,8 @@ describe("AgentSettingsScreen", () => {isChecking: false,isSupported: true,});- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- schema_version: 1,- agent_kind: "acp",- acp_server: "claude-code",- acp_command: [],- },- }),- );- renderAgentSettingsScreen();+ renderAgentSettingsScreen({ agentSettingsOverride: CLAUDE_PROFILE });await screen.findByTestId("agent-settings-screen");expect(@@ -1079,7 +568,6 @@ describe("AgentSettingsScreen", () => {describe("AgentSettingsScreen — MCP server scope", () => {beforeEach(() => {vi.restoreAllMocks();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);});function seedWithMcp(mcpConfig: Record<string, unknown>) {@@ -1105,7 +593,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {seedWithMcp(TWO_SERVERS);let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1129,7 +616,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {seedWithMcp(TWO_SERVERS);let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1154,7 +640,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {seedWithMcp(TWO_SERVERS);let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1188,7 +673,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {it("warns about a ref whose server is gone, which would fail the launch", async () => {seedWithMcp(TWO_SERVERS);renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1209,7 +693,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {seedWithMcp(TWO_SERVERS);let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "acp",acp_server: "claude-code",@@ -1231,7 +714,6 @@ describe("AgentSettingsScreen — MCP server scope", () => {it("explains the empty state when no server is configured", async () => {seedWithMcp({});renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1245,23 +727,11 @@ describe("AgentSettingsScreen — MCP server scope", () => {screen.getByText("SETTINGS$AGENT_PROFILE_MCP_NONE"),).toBeInTheDocument();});-- it("is hidden outside the profile editor", async () => {- // The global page saves `agent_settings`, which carries the resolved- // `mcp_config`, not refs.- seedWithMcp(TWO_SERVERS);- renderAgentSettingsScreen({});- await screen.findByTestId("agent-settings-screen");- expect(- screen.queryByTestId("agent-settings-mcp-mode"),- ).not.toBeInTheDocument();- });});describe("AgentSettingsScreen — MCP scope dirty tracking", () => {beforeEach(() => {vi.restoreAllMocks();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings({agent_settings: {@@ -1279,7 +749,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {async function dirtyForStoredRefs(refs: string[]) {let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1328,20 +797,10 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {);}- it("hides the control outside the profile editor", async () => {- seedOpenHandsSettings();- renderAgentSettingsScreen();- await screen.findByTestId("agent-settings-screen");- expect(- screen.queryByTestId("agent-settings-secrets-mode"),- ).not.toBeInTheDocument();- });-it("lists every saved secret read-only and persists null by default", async () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1371,7 +830,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1400,7 +858,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1430,7 +887,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "acp",acp_server: "claude-code",@@ -1474,7 +930,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {control = next;};const view = renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "acp",acp_server: "claude-code",@@ -1494,7 +949,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {expect(saved).toMatchObject({ secret_refs: ["PROD_DB_URL"] });view.unmount();renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: saved,onSaveControlChange,});@@ -1523,7 +977,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "acp",acp_server: "claude-code",@@ -1586,7 +1039,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {]);seedOpenHandsSettings();renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "acp",acp_server: "claude-code",@@ -1626,7 +1078,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1657,7 +1108,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {seedOpenHandsSettings();let control: AgentSettingsSaveControl | null = null;renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,@@ -1680,7 +1130,6 @@ describe("AgentSettingsScreen — MCP scope dirty tracking", () => {savedSecretsMock.mockReturnValue([]);seedOpenHandsSettings();renderAgentSettingsScreen({- embedded: true,agentSettingsOverride: {agent_kind: "openhands",enable_sub_agents: false,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 e6c92e4d00..1e9d577835 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@@ -330,7 +330,6 @@ export function AgentProfilesLocalView() {{/* Reuse the existing Agent settings form to define the agent. */}<AgentSettingsScreenkey={viewMode === "edit" ? `edit-${editingProfile?.id}` : "new-profile"}- embeddedagentSettingsOverride={override}onSaveControlChange={setSaveControl}/>diff --git a/src/constants/acp-providers.ts b/src/constants/acp-providers.tsindex cff1959845..9f9abc92b5 100644--- a/src/constants/acp-providers.ts+++ b/src/constants/acp-providers.ts@@ -478,32 +478,12 @@ export function labelForAcpModel(* Build the ``agent_settings_diff`` payload PATCH /api/settings expects* for the agent-kind/provider choice the user just made.*- * Used by both the Settings → Agent page and the onboarding "choose- * agent" step — keeping the shape in one helper means a future change- * (e.g. always seeding ``acp_command`` from the registry instead of- * sending ``[]``, or adding new ``acp_*`` reset fields) lands in both- * surfaces atomically.- *- * Returns ``null`` for an unknown ACP provider key by default — the- * caller can skip the save (the UI shouldn't surface unknown options,- * but the defensive path keeps a buggy preset list from corrupting- * settings).- *- * Pass ``allowUnknownServer: true`` to opt into pass-through for keys- * that aren't in {@link ACP_PROVIDERS} or ``ACP_CUSTOM_PRESET_KEY``.- * The Settings → Agent page uses this when the user opens settings- * that already carry an ``acp_server`` value canvas's registry- * doesn't know about (e.g. set out-of-band via the API for a provider- * we haven't mirrored yet) and saves without changing the command —- * otherwise the original key would be silently demoted to ``"custom"``.+ * Returns ``null`` for an unknown ACP provider key — the caller can skip+ * the save (the UI shouldn't surface unknown options, but the defensive+ * path keeps a buggy preset list from corrupting settings).*/export function buildAcpAgentSettingsDiff(providerKey: string,- options: {- command?: string[];- model?: string | null;- allowUnknownServer?: boolean;- } = {},): Record<string, unknown> | null {if (providerKey === "openhands") {// Switching back to OpenHands. The agent-server's ``Settings.update``@@ -514,29 +494,20 @@ export function buildAcpAgentSettingsDiff(}const isCustom = providerKey === ACP_CUSTOM_PRESET_KEY;- const provider = isCustom ? undefined : getAcpProvider(providerKey);- if (!isCustom && !provider && !options.allowUnknownServer) {+ if (!isCustom && !getAcpProvider(providerKey)) {return null;}- // Undefined model → the *preferred* default (Vertex-safe for Gemini), not- // the raw registry default — see getAcpPreferredDefaultModel.- const model =- options.model === undefined- ? getAcpPreferredDefaultModel(providerKey)- : options.model;-// ``acp_args: []`` resets any API-set ``acp_args`` that would// otherwise survive and concatenate to ``acp_command`` at spawn time- // (the agent-server merges the two before exec). Callers building the- // payload from a textarea that already shows the merged command- // (Settings → Agent) round-trip correctly — the merged tokens land in- // ``acp_command`` here, so no args are lost.+ // (the agent-server merges the two before exec).return {agent_kind: "acp",acp_server: providerKey,- acp_command: options.command ?? [],+ acp_command: [],acp_args: [],- acp_model: model ?? null,+ // The *preferred* default (Vertex-safe for Gemini), not the raw registry+ // default — see getAcpPreferredDefaultModel.+ acp_model: getAcpPreferredDefaultModel(providerKey) ?? null,};}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex c113f40dbf..51dad6af97 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -6221,23 +6221,6 @@"uk": "Метапрофілі доступні лише для локальних бекендів.","ca": "Els metaperfils només estan disponibles per a backends locals."},- "SETTINGS$AGENT_PAGE_DESCRIPTION": {- "en": "Choose between the built-in OpenHands agent and an external ACP (Agent Client Protocol) subprocess such as Claude Code, Codex, or Gemini CLI.",- "ja": "組み込みのOpenHandsエージェントと、Claude Code、Codex、Gemini CLIなどの外部ACP(Agent Client Protocol)サブプロセスのどちらかを選択します。",- "zh-CN": "在内置的 OpenHands 代理和外部 ACP(Agent Client Protocol)子进程(如 Claude Code、Codex 或 Gemini CLI)之间进行选择。",- "zh-TW": "在內建的 OpenHands 代理和外部 ACP(Agent Client Protocol)子處理程序(如 Claude Code、Codex 或 Gemini CLI)之間進行選擇。",- "ko-KR": "내장 OpenHands 에이전트와 Claude Code, Codex, Gemini CLI 같은 외부 ACP(Agent Client Protocol) 하위 프로세스 중에서 선택하세요.",- "no": "Velg mellom den innebygde OpenHands-agenten og en ekstern ACP-underprosess (Agent Client Protocol) som Claude Code, Codex eller Gemini CLI.",- "it": "Scegli tra l'agente OpenHands integrato e un sottoprocesso ACP (Agent Client Protocol) esterno come Claude Code, Codex o Gemini CLI.",- "pt": "Escolha entre o agente OpenHands integrado e um subprocesso ACP (Agent Client Protocol) externo, como Claude Code, Codex ou Gemini CLI.",- "es": "Elige entre el agente integrado de OpenHands y un subproceso ACP (Agent Client Protocol) externo como Claude Code, Codex o Gemini CLI.",- "ar": "اختر بين وكيل OpenHands المدمج وعملية فرعية خارجية عبر ACP (Agent Client Protocol) مثل Claude Code أو Codex أو Gemini CLI.",- "fr": "Choisissez entre l'agent OpenHands intégré et un sous-processus ACP (Agent Client Protocol) externe tel que Claude Code, Codex ou Gemini CLI.",- "tr": "Yerleşik OpenHands aracısı ile Claude Code, Codex veya Gemini CLI gibi harici bir ACP (Agent Client Protocol) alt süreci arasında seçim yapın.",- "de": "Wählen Sie zwischen dem integrierten OpenHands-Agenten und einem externen ACP-Subprozess (Agent Client Protocol) wie Claude Code, Codex oder Gemini CLI.",- "uk": "Оберіть між вбудованим агентом OpenHands і зовнішнім підпроцесом ACP (Agent Client Protocol), як-от Claude Code, Codex або Gemini CLI.",- "ca": "Tria entre l'agent OpenHands integrat i un subprocés ACP (Agent Client Protocol) extern com Claude Code, Codex o Gemini CLI."- },"SETTINGS$AGENT_TYPE_OPENHANDS": {"en": "OpenHands","ja": "OpenHands",diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsxindex f1d8a30146..917ab4484a 100644--- a/src/routes/agent-settings.tsx+++ b/src/routes/agent-settings.tsx@@ -1,9 +1,7 @@import React, { useCallback, useEffect, useRef, useState } from "react";import { Navigate } from "react-router";import { useTranslation } from "react-i18next";-import { AxiosError } from "axios";import { useSettings } from "#/hooks/query/use-settings";-import { useSaveSettings } from "#/hooks/mutation/use-save-settings";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";@@ -11,7 +9,6 @@ import { SettingsSwitch } from "#/components/features/settings/settings-switch";import { SchemaField } from "#/components/features/settings/sdk-settings/schema-field";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";import { ProfileScopeList } from "#/components/features/settings/agent-profiles/profile-scope-list";import { Typography } from "#/ui/typography";import { I18nKey } from "#/i18n/declaration";@@ -22,11 +19,6 @@ import {coerceFieldValue,normalizeFieldValue,} from "#/utils/sdk-settings-schema";-import {- displayErrorToast,- displaySuccessToast,-} from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";import {resolveSchemaFieldDescription,resolveSchemaFieldLabel,@@ -34,7 +26,6 @@ import {import {ACP_PROVIDERS,ACP_CUSTOM_PRESET_KEY,- buildAcpAgentSettingsDiff,getAcpPreferredDefaultModel,getAcpProvider,getAcpProviderSecrets,@@ -277,8 +268,8 @@ export function buildAgentProfileFields(}/**- * Handle the embedded form exposes to its parent (the Agent-profile editor) so- * it can read the current state and persist it as an AgentProfile.+ * Handle the form exposes to the Agent-profile editor so it can read the+ * current state and persist it as an AgentProfile.*/export interface AgentSettingsSaveControl {agentType: AgentType;@@ -300,34 +291,17 @@ export interface AgentSettingsSaveControl {}interface AgentSettingsScreenProps {- /**- * Embedded mode reuses this form as the Agent-profile editor: it hides the- * page header + the global Save button, seeds from `agentSettingsOverride`- * instead of the live global settings, and reports its state through- * `onSaveControlChange` so the parent can persist it as an AgentProfile.- */- embedded?: boolean;- /**- * When set (embedded mode), seed the form from this `agent_settings`-shaped- * object instead of the live global settings — lets the editor open on a- * stored profile's fields.- */+ /** `agent_settings`-shaped profile fields the form opens on. */agentSettingsOverride?: Record<string, SettingsValue> | null;- onSaveControlChange?: (control: AgentSettingsSaveControl) => void;+ onSaveControlChange: (control: AgentSettingsSaveControl) => void;}export function AgentSettingsScreen({- embedded = false,agentSettingsOverride = null,onSaveControlChange,-}: AgentSettingsScreenProps = {}) {+}: AgentSettingsScreenProps) {const { t } = useTranslation("openhands");const { data: settings, isLoading } = useSettings();- // In embedded (profile-editor) mode the parent seeds the form from a stored- // profile via `agentSettingsOverride`; otherwise use the live global settings.- const agentSettingsSource: Record<string, SettingsValue> | null =- agentSettingsOverride ?? settings?.agent_settings ?? null;- const { mutate: saveSettings, isPending: isSaving } = useSaveSettings();const { data: schema } = useAgentSettingsSchema(settings?.agent_settings_schema,);@@ -341,10 +315,10 @@ export function AgentSettingsScreen({const initialSubAgentsEnabled = React.useMemo(() =>getEnableSubAgentsValue(- agentSettingsSource?.[ENABLE_SUB_AGENTS_FIELD_KEY],+ agentSettingsOverride?.[ENABLE_SUB_AGENTS_FIELD_KEY],subAgentsField,),- [subAgentsField, agentSettingsSource],+ [subAgentsField, agentSettingsOverride],);const [subAgentsEnabled, setSubAgentsEnabled] = useState(initialSubAgentsEnabled,@@ -359,22 +333,17 @@ export function AgentSettingsScreen({const initialSwitchLlmToolEnabled = React.useMemo(() =>getEnableSwitchLlmToolValue(- agentSettingsSource?.[ENABLE_SWITCH_LLM_TOOL_FIELD_KEY],+ agentSettingsOverride?.[ENABLE_SWITCH_LLM_TOOL_FIELD_KEY],switchLlmToolField,),- [switchLlmToolField, agentSettingsSource],+ [switchLlmToolField, agentSettingsOverride],);const [switchLlmToolEnabled, setSwitchLlmToolEnabled] = useState(initialSwitchLlmToolEnabled,);- // Embedded mode saves an AgentProfile, not global settings, and the profile- // model gained this field four releases after the settings schema did. The- // global page is unaffected — that endpoint has accepted the key since- // 1.22.0 — so the extra gate applies to the profile editor alone.const switchLlmToolSupportedOnProfile = agentProfileSupportsSwitchLlmTool();const showSwitchLlmTool =- Boolean(switchLlmToolField) &&- (!embedded || switchLlmToolSupportedOnProfile);+ Boolean(switchLlmToolField) && switchLlmToolSupportedOnProfile;// --- Parallel tool calls (OpenHands path) ---// Surfaced only when the backend schema exposes the field, so older@@ -384,21 +353,17 @@ export function AgentSettingsScreen({);const initialToolConcurrency = React.useMemo(() => {if (!toolConcurrencyField) return "";- const raw = agentSettingsSource?.[TOOL_CONCURRENCY_FIELD_KEY];+ const raw = agentSettingsOverride?.[TOOL_CONCURRENCY_FIELD_KEY];return normalizeFieldValue(toolConcurrencyField, raw);- }, [toolConcurrencyField, agentSettingsSource]);+ }, [toolConcurrencyField, agentSettingsOverride]);const [toolConcurrency, setToolConcurrency] = useState<string | boolean>(initialToolConcurrency,);// --- MCP servers (both variants; a base-model field) ---- // Only the profile editor shows this: the global agent-settings page saves- // ``agent_settings``, which has no refs — it carries the resolved- // ``mcp_config`` itself.- const showProfileScopeFields = embedded;const initialMcpRefs = React.useMemo(- () => readProfileScope(agentSettingsSource?.[MCP_SERVER_REFS_KEY]),- [agentSettingsSource],+ () => readProfileScope(agentSettingsOverride?.[MCP_SERVER_REFS_KEY]),+ [agentSettingsOverride],);const [mcpMode, setMcpMode] = useState<ProfileScopeMode>(initialMcpRefs.mode);const [selectedMcpServers, setSelectedMcpServers] = useState<string[]>(@@ -442,11 +407,11 @@ export function AgentSettingsScreen({// --- Secret scope (both variants; a base-model field) ---const secretRefsSupportedOnProfile = agentProfileSupportsSecretRefs();const { data: savedSecrets } = useSearchSecrets({- enabled: embedded && secretRefsSupportedOnProfile,+ enabled: secretRefsSupportedOnProfile,});const initialSecretRefs = React.useMemo(- () => readProfileScope(agentSettingsSource?.[SECRET_REFS_KEY]),- [agentSettingsSource],+ () => readProfileScope(agentSettingsOverride?.[SECRET_REFS_KEY]),+ [agentSettingsOverride],);const [secretsMode, setSecretsMode] = useState<ProfileScopeMode>(initialSecretRefs.mode,@@ -489,8 +454,8 @@ export function AgentSettingsScreen({const [acpModel, setAcpModel] = useState("");const [isCustomAcpModel, setIsCustomAcpModel] = useState(false);- // ACP credentials live alongside the agent spec, so the page owns the- // credential form and a single Save persists both. Called unconditionally+ // ACP credentials live alongside the agent spec, so the form owns the+ // credential form and hands it to the editor's Save. Called unconditionally// (no-ops to empty fields for a non-ACP / custom command) to keep hook order// stable across the ``isLoading`` early-return below; ``detectPreset`` is a// cheap pure lookup.@@ -530,46 +495,34 @@ export function AgentSettingsScreen({[secretCatalog, selectedSecrets],);- 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.- const source = agentSettingsOverride ?? settings?.agent_settings ?? null;- if (!source && !settings) return;- const initIdentity = agentSettingsOverride ?? settings;- if (lastInitializedSettingsRef.current === initIdentity) return;-- lastInitializedSettingsRef.current = initIdentity;- const kind = source?.agent_kind;+ const kind = agentSettingsOverride?.agent_kind;if (kind === "acp") {setAgentType("acp");- const rawAcpServer = source?.acp_server;+ const rawAcpServer = agentSettingsOverride?.acp_server;const acpServer =typeof rawAcpServer === "string" ? rawAcpServer : undefined;const provider = getAcpProvider(acpServer);- const storedCommand = toStringArray(source?.acp_command);+ const storedCommand = toStringArray(agentSettingsOverride?.acp_command);const effectiveBaseCommand =storedCommand.length > 0? storedCommand: (provider?.default_command ?? []);const tokens = [...effectiveBaseCommand,- ...toStringArray(source?.acp_args),+ ...toStringArray(agentSettingsOverride?.acp_args),];const renderedCommandText =tokens.length > 0 ? formatCommand(tokens) : "";setCommandText(renderedCommandText);- loadedAcpServerRef.current = acpServer ?? null;- loadedCommandTextRef.current = renderedCommandText;- const savedModel = source?.acp_model;+ const savedModel = agentSettingsOverride?.acp_model;const normalizedSavedModel =typeof savedModel === "string" ? savedModel.trim() : "";const nextAcpModel =@@ -589,12 +542,10 @@ export function AgentSettingsScreen({setAgentType("openhands");setCommandText("");setAcpModel("");- loadedAcpServerRef.current = null;- loadedCommandTextRef.current = "";setIsCustomAcpModel(false);setLoadedSnapshot(EMPTY_AGENT_SETTINGS_SNAPSHOT);}- }, [settings, agentSettingsOverride]);+ }, [agentSettingsOverride]);// Sync the sub-agents toggle when settings reloaduseEffect(() => {@@ -623,7 +574,7 @@ export function AgentSettingsScreen({setSelectedSecrets(initialSecretRefs.selected);}, [initialSecretRefs]);- // --- Embedded (Agent-profile editor) save control ---+ // --- 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// ``sdk-section-page``). The body is (re)assigned during render below.@@ -668,7 +619,6 @@ export function AgentSettingsScreen({const credentialsDirty = acpCredentialForm.isDirty;const isAnyDirty = settingsDirty || credentialsDirty;useEffect(() => {- if (!embedded || !onSaveControlChange) return;onSaveControlChange({agentType,isValid: !acpCommandEmpty,@@ -681,7 +631,6 @@ export function AgentSettingsScreen({},});}, [- embedded,onSaveControlChange,agentType,acpCommandEmpty,@@ -696,7 +645,6 @@ export function AgentSettingsScreen({const isAcp = agentType === "acp";const commandTokens = parseCommand(commandText);- const isAcpInvalid = isAcp && commandTokens.length === 0;const selectedPreset = detectPreset(commandText, ACP_PROVIDERS);const selectedProvider = getAcpProvider(selectedPreset);const modelSuggestions = selectedProvider?.available_models ?? [];@@ -713,7 +661,7 @@ export function AgentSettingsScreen({formatCommand(ACP_PROVIDERS[0]?.default_command ?? []) ||COMMAND_PLACEHOLDER_FALLBACK;- // Assign the embedded control's field builder from the live render state.+ // Assign the control's field builder from the live render state.// The mapping itself lives in the pure `buildAgentProfileFields` (unit-// tested); this closure just snapshots the current state. Throws only when// called (at save time), never during render.@@ -737,125 +685,7 @@ export function AgentSettingsScreen({secretRefsSupportedOnProfile,});- const isSavingAny = isSaving || acpCredentialForm.isSaving;-- const handleSave = async () => {- // Persist ACP credentials first (if any were typed) so they exist when the- // agent spec is applied. When the spec is also changing, save silently so- // the settings save below owns the single "Saved" toast (otherwise the user- // sees it twice); a credentials-only save shows its own toast. Errors always- // toast and abort.- if (acpCredentialForm.isDirty) {- const ok = await acpCredentialForm.save({ silent: settingsDirty });- if (!ok) return;- acpCredentialForm.reset();- }-- // Only write the agent spec when it actually changed — a credentials-only- // edit must not re-push unchanged settings (or double-toast).- if (!settingsDirty) return;-- if (isAcp) {- const useDefault = !!(selectedProvider && isDefaultProviderCommand);- const loadedServer = loadedAcpServerRef.current;- const commandUnchanged = commandText === loadedCommandTextRef.current;- const loadedServerIsUnknown =- !!loadedServer &&- loadedServer !== ACP_CUSTOM_PRESET_KEY &&- !ACP_PROVIDERS.some((p) => p.key === loadedServer);- const preserveUnknownServer =- isAcp && commandUnchanged && loadedServerIsUnknown;- const providerKey = preserveUnknownServer- ? (loadedServer as string)- : selectedProvider && isDefaultProviderCommand- ? selectedProvider.key- : ACP_CUSTOM_PRESET_KEY;- // ``model: undefined`` lets buildAcpAgentSettingsDiff seed the- // provider's preferred default for built-in keys; for the custom preset- // it falls through to ``null`` since custom has no default.- const agentSettingsDiff = buildAcpAgentSettingsDiff(providerKey, {- command: useDefault ? [] : commandTokens,- model: acpModel.trim() || undefined,- allowUnknownServer: preserveUnknownServer,- });-- if (!agentSettingsDiff) return;-- saveSettings(- { agent_settings_diff: agentSettingsDiff },- {- onError: (error) => {- const message = retrieveAxiosErrorMessage(error as AxiosError);- displayErrorToast(message || t(I18nKey.ERROR$GENERIC));- },- onSuccess: () => {- displaySuccessToast(t(I18nKey.SETTINGS$SAVED));- setLoadedSnapshot({- agentType,- commandText,- acpModel,- isCustomAcpModel,- });- loadedCommandTextRef.current = commandText;- },- },- );- } else {- // OpenHands path: save agent_kind + sub-agents toggle + the LLM-switching- // toggle + parallel tool calls- const agentSettingsDiff: Record<string, SettingsValue> = {- agent_kind: "openhands",- enable_sub_agents: subAgentsEnabled,- };-- if (switchLlmToolField) {- // Schema-guarded like ``tool_concurrency_limit`` — older agent-servers- // that predate the field never receive the key.- agentSettingsDiff[ENABLE_SWITCH_LLM_TOOL_FIELD_KEY] =- switchLlmToolEnabled;- }-- if (toolConcurrencyField) {- let coerced: SettingsValue;- try {- // Reuse the schema-driven coercion + min/max validation rather than- // re-implementing it; throws a user-facing message on bad input.- coerced = coerceFieldValue(toolConcurrencyField, toolConcurrency);- } catch (error) {- displayErrorToast(- error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC),- );- return;- }- // ``tool_concurrency_limit`` is a non-nullable int (default 1); skip an- // empty input rather than sending ``null`` the backend would reject.- if (coerced != null) {- agentSettingsDiff[TOOL_CONCURRENCY_FIELD_KEY] = coerced;- }- }-- saveSettings(- {- agent_settings_diff: agentSettingsDiff,- },- {- onError: (error) => {- const message = retrieveAxiosErrorMessage(error as AxiosError);- displayErrorToast(message || t(I18nKey.ERROR$GENERIC));- },- onSuccess: () => {- displaySuccessToast(t(I18nKey.SETTINGS$SAVED));- setLoadedSnapshot({- agentType: "openhands",- commandText: "",- acpModel: "",- isCustomAcpModel: false,- });- },- },- );- }- };+ const isSaving = acpCredentialForm.isSaving;// Sub-agents field metadata for OpenHands sectionconst subAgentsLabel = subAgentsField@@ -890,17 +720,6 @@ export function AgentSettingsScreen({data-testid="agent-settings-screen"className="flex flex-col gap-6 pb-8 max-w-2xl">- {!embedded && (- <div>- <Typography.H2 className="mb-2">- {t(I18nKey.SETTINGS$NAV_AGENT)}- </Typography.H2>- <Typography.Paragraph className="text-sm text-[#A3A3A3]">- {t(I18nKey.SETTINGS$AGENT_PAGE_DESCRIPTION)}- </Typography.Paragraph>- </div>- )}-<SettingsDropdownInputtestId="agent-type-selector"name="agent-type"@@ -989,90 +808,86 @@ export function AgentSettingsScreen({<SchemaFieldfield={toolConcurrencyField}value={toolConcurrency}- isDisabled={isSavingAny}+ isDisabled={isSaving}onChange={setToolConcurrency}/>) : null}- {showProfileScopeFields ? (- <div className="flex flex-col gap-2.5">- <Typography.Text className="text-sm">- {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP)}- </Typography.Text>- <SettingsDropdownInput- testId="agent-settings-mcp-mode"- name="agent-mcp-mode"- label=""- items={[- {- key: "standard",- label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL),- },- {- key: "custom",- label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE),- },- ]}- selectedKey={mcpMode}- isDisabled={isSavingAny}- onSelectionChange={(key) => {- if (!key) return;- const mode = key as ProfileScopeMode;- setMcpMode(mode);- // Seed a first switch to custom from the default — every- // configured server — so turning the control on narrows from what- // the agent had rather than cutting it off from all of them.- if (mode === "custom" && selectedMcpServers.length === 0) {- setSelectedMcpServers(- configuredMcpNames.map(({ name }) => name),- );- }- }}+ <div className="flex flex-col gap-2.5">+ <Typography.Text className="text-sm">+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP)}+ </Typography.Text>+ <SettingsDropdownInput+ testId="agent-settings-mcp-mode"+ name="agent-mcp-mode"+ label=""+ items={[+ {+ key: "standard",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL),+ },+ {+ key: "custom",+ label: t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE),+ },+ ]}+ selectedKey={mcpMode}+ isDisabled={isSaving}+ onSelectionChange={(key) => {+ if (!key) return;+ const mode = key as ProfileScopeMode;+ setMcpMode(mode);+ // Seed a first switch to custom from the default — every+ // configured server — so turning the control on narrows from what+ // the agent had rather than cutting it off from all of them.+ if (mode === "custom" && selectedMcpServers.length === 0) {+ setSelectedMcpServers(configuredMcpNames.map(({ name }) => name));+ }+ }}+ />+ {mcpCatalog.length > 0 ? (+ <ProfileScopeList+ testId="agent-settings-mcp"+ items={mcpCatalog}+ selected={+ mcpMode === "custom"+ ? orderedSelectedMcpServers+ : mcpCatalog.map(({ name }) => name)+ }+ isDisabled={isSaving || mcpMode === "standard"}+ onToggle={(name, checked) =>+ setSelectedMcpServers((prev) =>+ checked+ ? [...prev, name]+ : prev.filter((entry) => entry !== name),+ )+ }/>- {mcpCatalog.length > 0 ? (- <ProfileScopeList- testId="agent-settings-mcp"- items={mcpCatalog}- selected={- mcpMode === "custom"- ? orderedSelectedMcpServers- : mcpCatalog.map(({ name }) => name)- }- isDisabled={isSavingAny || mcpMode === "standard"}- onToggle={(name, checked) =>- setSelectedMcpServers((prev) =>- checked- ? [...prev, name]- : prev.filter((entry) => entry !== name),- )- }- />- ) : (- <Typography.Text className="text-xs text-tertiary-alt">- {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_NONE)}- </Typography.Text>- )}- {danglingMcpRefs.length > 0 ? (- <Typography.Text- testId="agent-settings-mcp-dangling"- className="text-xs text-danger"- >- {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_DANGLING, {- names: danglingMcpRefs.join(", "),- })}- </Typography.Text>- ) : null}+ ) : (<Typography.Text className="text-xs text-tertiary-alt">- {t(- mcpMode === "custom"- ? I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT- : I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL_HINT,- )}+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_NONE)}</Typography.Text>- </div>- ) : null}+ )}+ {danglingMcpRefs.length > 0 ? (+ <Typography.Text+ testId="agent-settings-mcp-dangling"+ className="text-xs text-danger"+ >+ {t(I18nKey.SETTINGS$AGENT_PROFILE_MCP_DANGLING, {+ names: danglingMcpRefs.join(", "),+ })}+ </Typography.Text>+ ) : null}+ <Typography.Text className="text-xs text-tertiary-alt">+ {t(+ mcpMode === "custom"+ ? I18nKey.SETTINGS$AGENT_PROFILE_MCP_CHOOSE_HINT+ : I18nKey.SETTINGS$AGENT_PROFILE_MCP_ALL_HINT,+ )}+ </Typography.Text>+ </div>- {showProfileScopeFields && secretRefsSupportedOnProfile ? (+ {secretRefsSupportedOnProfile ? (<div className="flex flex-col gap-2.5"><Typography.Text className="text-sm">{t(I18nKey.SETTINGS$AGENT_PROFILE_SECRETS)}@@ -1092,7 +907,7 @@ export function AgentSettingsScreen({},]}selectedKey={secretsMode}- isDisabled={isSavingAny}+ isDisabled={isSaving}onSelectionChange={(key) => {if (!key) return;const mode = key as ProfileScopeMode;@@ -1110,7 +925,7 @@ export function AgentSettingsScreen({? orderedSelectedSecrets: secretCatalog.map(({ name }) => name)}- isDisabled={isSavingAny || secretsMode === "standard"}+ isDisabled={isSaving || secretsMode === "standard"}onToggle={(name, checked) =>setSelectedSecrets((prev) =>checked@@ -1275,22 +1090,6 @@ export function AgentSettingsScreen({/></>)}-- {!embedded && (- <div>- <BrandButton- testId="agent-save-button"- type="button"- variant="primary"- isDisabled={isSavingAny || !isAnyDirty || isAcpInvalid}- onClick={handleSave}- >- {isSavingAny- ? t(I18nKey.SETTINGS$SAVING)- : t(I18nKey.SETTINGS$SAVE_CHANGES)}- </BrandButton>- </div>- )}</div>);}@@ -1304,8 +1103,8 @@ export function AgentSettingsScreen({* Note: This is a route file; only the router should import the default export.* React Router's Vite plugin wraps a route's default export with* `withComponentProps`, which invokes it with route props and drops any props- * passed by a parent — so embedded consumers (the Agent-profile editor) MUST- * import the named `AgentSettingsScreen` export instead, or `embedded` /+ * passed by a parent — so the Agent-profile editor MUST import the named+ * `AgentSettingsScreen` export instead, or `agentSettingsOverride` /* `onSaveControlChange` never arrive. Mirrors `LlmSettingsRoute`.*/export default function AgentSettingsRoute() {