Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(acp): single Save + auth banner + one toast on Settings β†’ Agent (#1251)

simonrosenberg098af964a83b
diff --git a/__tests__/components/settings/acp-credentials-section.test.tsx b/__tests__/components/settings/acp-credentials-section.test.tsx
index 9f364bb074..d4b524aab6 100644
--- a/__tests__/components/settings/acp-credentials-section.test.tsx
+++ b/__tests__/components/settings/acp-credentials-section.test.tsx
@@ -1,31 +1,33 @@
import React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { render, screen, waitFor } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- __resetActiveStoreForTests,
- setActiveSelection,
- setRegisteredBackends,
-} from "#/api/backend-registry/active-store";
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import { AcpCredentialsSection } from "#/components/features/settings/acp-credentials-section";
+import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";
import { SecretsService } from "#/api/secrets-service";
-// Observe the save outcome (success vs orphaned-credential warning) without
-// rendering real toasts.
-const toastMocks = vi.hoisted(() => ({
- success: vi.fn(),
- warning: vi.fn(),
- error: vi.fn(),
-}));
-vi.mock("#/utils/custom-toast-handlers", () => ({
- displaySuccessToast: toastMocks.success,
- displayWarningToast: toastMocks.warning,
- displayErrorToast: toastMocks.error,
+// The login-detection probe is exercised in its own hook test; here we stub it
+// so rendering the section doesn't spin a subprocess and we can drive the auth
+// banner states directly.
+const acpAuthStatusMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/query/use-acp-auth-status", () => ({
+ useAcpAuthStatus: (...args: unknown[]) => acpAuthStatusMock(...args),
}));
+// The section is presentational: the form lives in the parent (Settings β†’
+// Agent) so a single Save persists the agent spec + credentials together. These
+// tests drive the section through the real form hook to cover field rendering,
+// conflict warnings, and the auth banner; the save flow is covered in
+// __tests__/routes/agent-settings.test.tsx.
+function Harness({ providerKey }: { providerKey: string }) {
+ const form = useAcpCredentialForm(providerKey);
+ return <AcpCredentialsSection form={form} providerKey={providerKey} />;
+}
+
function renderSection(providerKey: string) {
const user = userEvent.setup();
render(
@@ -35,34 +37,22 @@ function renderSection(providerKey: string) {
}
>
<ActiveBackendProvider>
- <AcpCredentialsSection providerKey={providerKey} />
+ <Harness providerKey={providerKey} />
</ActiveBackendProvider>
</QueryClientProvider>,
);
return { user };
}
-function useCloudBackend() {
- setRegisteredBackends([
- {
- id: "cloud-1",
- name: "Cloud",
- host: "https://app.example.dev",
- apiKey: "key",
- kind: "cloud",
- },
- ]);
- setActiveSelection({ backendId: "cloud-1", orgId: null });
-}
-
beforeEach(() => {
vi.restoreAllMocks();
- toastMocks.success.mockClear();
- toastMocks.warning.mockClear();
- toastMocks.error.mockClear();
__resetActiveStoreForTests();
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: false,
+ isSupported: true,
+ });
vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
- vi.spyOn(SecretsService, "createSecret").mockResolvedValue();
});
afterEach(() => {
__resetActiveStoreForTests();
@@ -72,48 +62,21 @@ describe("AcpCredentialsSection", () => {
it("renders the provider's credential fields (blob as textarea, key as password)", () => {
renderSection("codex");
- const blob = screen.getByTestId("settings-acp-secret-CODEX_AUTH_JSON");
- expect(blob.tagName).toBe("TEXTAREA");
+ expect(
+ screen.getByTestId("settings-acp-secret-CODEX_AUTH_JSON").tagName,
+ ).toBe("TEXTAREA");
expect(
screen.getByTestId("settings-acp-secret-OPENAI_API_KEY"),
).toHaveAttribute("type", "password");
- // Pristine form β€” nothing to save yet.
- expect(screen.getByTestId("acp-credentials-save-button")).toBeDisabled();
});
it("renders nothing for a provider without credential fields", () => {
renderSection("custom");
expect(
- screen.queryByTestId("acp-credentials-save-button"),
+ screen.queryByTestId("settings-acp-secret-CODEX_AUTH_JSON"),
).not.toBeInTheDocument();
});
- it("saves the filled fields as secrets and resets the form", async () => {
- const { user } = renderSection("claude-code");
-
- await user.type(
- screen.getByTestId("settings-acp-secret-ANTHROPIC_API_KEY"),
- "sk-ant-123",
- );
- await user.click(screen.getByTestId("acp-credentials-save-button"));
-
- await waitFor(() => {
- expect(SecretsService.createSecret).toHaveBeenCalledWith(
- "ANTHROPIC_API_KEY",
- "sk-ant-123",
- undefined,
- );
- expect(toastMocks.success).toHaveBeenCalledTimes(1);
- });
- expect(
- (
- screen.getByTestId(
- "settings-acp-secret-ANTHROPIC_API_KEY",
- ) as HTMLInputElement
- ).value,
- ).toBe("");
- });
-
it("warns when the Claude OAuth token and base URL are both set", async () => {
const { user } = renderSection("claude-code");
@@ -134,25 +97,48 @@ describe("AcpCredentialsSection", () => {
).toBeInTheDocument();
});
- it("toasts success when a file credential is saved on a cloud backend (cloud materialises file secrets)", async () => {
- // Cloud materialises file-content credentials from the encrypted secret
- // store via agent_context.secrets at conversation start, so a saved blob is
- // consumable β€” no orphaned-credential warning.
- useCloudBackend();
- const { user } = renderSection("codex");
+ it("shows the 'already signed in' banner when the login probe detects a session", () => {
+ acpAuthStatusMock.mockReturnValue({
+ status: "authenticated",
+ isChecking: false,
+ isSupported: true,
+ });
+ renderSection("claude-code");
+ expect(
+ screen.getByTestId("settings-acp-auth-detected"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("settings-acp-auth-checking"),
+ ).not.toBeInTheDocument();
+ });
- await user.click(screen.getByTestId("settings-acp-secret-CODEX_AUTH_JSON"));
- await user.paste('{"tokens":{}}');
- await user.click(screen.getByTestId("acp-credentials-save-button"));
+ it("shows the checking spinner while the login probe is in flight", () => {
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: true,
+ isSupported: true,
+ });
+ renderSection("claude-code");
+ expect(
+ screen.getByTestId("settings-acp-auth-checking"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("settings-acp-auth-detected"),
+ ).not.toBeInTheDocument();
+ });
- await waitFor(() => {
- expect(SecretsService.createSecret).toHaveBeenCalledWith(
- "CODEX_AUTH_JSON",
- '{"tokens":{}}',
- undefined,
- );
- expect(toastMocks.success).toHaveBeenCalled();
+ it("shows no auth banner when there is no detected session", () => {
+ acpAuthStatusMock.mockReturnValue({
+ status: "unauthenticated",
+ isChecking: false,
+ isSupported: true,
});
- expect(toastMocks.warning).not.toHaveBeenCalled();
+ renderSection("claude-code");
+ expect(
+ screen.queryByTestId("settings-acp-auth-detected"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("settings-acp-auth-checking"),
+ ).not.toBeInTheDocument();
});
});
diff --git a/__tests__/routes/agent-settings.test.tsx b/__tests__/routes/agent-settings.test.tsx
index 51652498c9..2f22751ad2 100644
--- a/__tests__/routes/agent-settings.test.tsx
+++ b/__tests__/routes/agent-settings.test.tsx
@@ -5,9 +5,30 @@ import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import AgentSettingsScreen from "#/routes/agent-settings";
import SettingsService from "#/api/settings-service/settings-service.api";
+import { SecretsService } from "#/api/secrets-service";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { Settings } from "#/types/settings";
+// Stub the login-detection probe so the ACP credentials section doesn't spin a
+// subprocess; default to no detected session so existing tests are unaffected.
+const acpAuthStatusMock = vi.hoisted(() => vi.fn());
+vi.mock("#/hooks/query/use-acp-auth-status", () => ({
+ useAcpAuthStatus: (...args: unknown[]) => acpAuthStatusMock(...args),
+}));
+
+// Observe save toasts so we can assert the single Save shows one confirmation,
+// not one per persisted thing (agent spec + credentials).
+const toastMocks = vi.hoisted(() => ({
+ success: vi.fn(),
+ error: vi.fn(),
+ warning: vi.fn(),
+}));
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displaySuccessToast: toastMocks.success,
+ displayErrorToast: toastMocks.error,
+ displayWarningToast: toastMocks.warning,
+}));
+
function buildSettings(overrides: Partial<Settings> = {}): Settings {
return {
...MOCK_DEFAULT_USER_SETTINGS,
@@ -37,6 +58,18 @@ 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(SecretsService, "getSecrets").mockResolvedValue([]);
+ vi.spyOn(SecretsService, "createSecret").mockResolvedValue();
+ acpAuthStatusMock.mockReturnValue({
+ status: "unknown",
+ isChecking: false,
+ isSupported: true,
+ });
+ toastMocks.success.mockClear();
+ toastMocks.error.mockClear();
+ toastMocks.warning.mockClear();
});
it("renders the agent type selector defaulting to OpenHands with sub-agents toggle", async () => {
@@ -265,7 +298,9 @@ describe("AgentSettingsScreen", () => {
// 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" }),
+ await screen.findByRole("option", {
+ name: "SETTINGS$AGENT_PRESET_CUSTOM",
+ }),
);
const commandInput = screen.getByTestId(
"agent-command-input",
@@ -684,4 +719,119 @@ describe("AgentSettingsScreen", () => {
"--new-flag",
]);
});
+
+ it("a single Save persists ACP credentials together with the agent spec", 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();
+ await screen.findByTestId("agent-settings-screen");
+
+ // Switch to ACP (Claude Code prefilled) and paste a credential β€” there is
+ // ONE Save button for the whole page; the credentials section has none.
+ await user.click(screen.getByTestId("agent-type-selector"));
+ await user.click(
+ await screen.findByRole("option", { name: "SETTINGS$AGENT_TYPE_ACP" }),
+ );
+ await user.type(
+ await screen.findByTestId("settings-acp-secret-ANTHROPIC_API_KEY"),
+ "sk-ant-xyz",
+ );
+ expect(
+ screen.queryByTestId("acp-credentials-save-button"),
+ ).not.toBeInTheDocument();
+
+ 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);
+ });
+ 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: ["npx", "-y", "@agentclientprotocol/claude-agent-acp"],
+ },
+ }),
+ );
+ const saveSettings = vi.spyOn(SettingsService, "saveSettings");
+ const createSecret = vi.spyOn(SecretsService, "createSecret");
+
+ renderAgentSettingsScreen();
+ await screen.findByTestId("agent-settings-screen");
+
+ 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();
+ });
+
+ it("shows the 'already signed in' banner in the credentials section when authenticated", async () => {
+ acpAuthStatusMock.mockReturnValue({
+ status: "authenticated",
+ isChecking: false,
+ isSupported: true,
+ });
+ 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();
+ await screen.findByTestId("agent-settings-screen");
+
+ expect(
+ await screen.findByTestId("settings-acp-auth-detected"),
+ ).toBeInTheDocument();
+ });
});
diff --git a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
index e6864b198a..0b77477b64 100644
--- a/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
+++ b/src/components/features/onboarding/steps/setup-acp-secrets-step.tsx
@@ -1,8 +1,8 @@
import React from "react";
import { useTranslation } from "react-i18next";
-import { Check, Loader2 } from "lucide-react";
import { BrandButton } from "#/components/features/settings/brand-button";
import { AcpConflictWarnings } from "#/components/features/settings/acp-conflict-warnings";
+import { AcpAuthStatusBanner } from "#/components/features/settings/acp-auth-status-banner";
import { AcpSecretField } from "#/components/features/settings/acp-secret-field";
import { I18nKey } from "#/i18n/declaration";
import { useAcpAuthStatus } from "#/hooks/query/use-acp-auth-status";
@@ -150,36 +150,12 @@ export function SetupAcpSecretsStep({
)}
</header>
- {authStatus === "authenticated" ? (
- <div
- data-testid="onboarding-acp-auth-detected"
- // Matches the onboarding "backend connected" success banner
- // (check-backend-step.tsx) for a consistent look.
- className="flex items-start gap-2 rounded-xl border border-green-500/40 bg-green-500/10 px-4 py-3 text-sm text-green-200"
- >
- <Check
- className="mt-0.5 size-4 shrink-0 text-green-400"
- aria-hidden
- />
- <span>
- {t(I18nKey.ONBOARDING$ACP_AUTH_DETECTED, {
- provider: providerName,
- })}
- </span>
- </div>
- ) : isCheckingAuth ? (
- <div
- data-testid="onboarding-acp-auth-checking"
- className="flex items-center gap-2 text-sm text-[var(--oh-muted)]"
- >
- <Loader2 className="size-4 shrink-0 animate-spin" aria-hidden />
- <span>
- {t(I18nKey.ONBOARDING$ACP_AUTH_CHECKING, {
- provider: providerName,
- })}
- </span>
- </div>
- ) : null}
+ <AcpAuthStatusBanner
+ status={authStatus}
+ isChecking={isCheckingAuth}
+ providerName={providerName}
+ testIdPrefix="onboarding-acp-auth"
+ />
<div className="flex flex-col gap-5">
{fields.map((field) => (
diff --git a/src/components/features/settings/acp-auth-status-banner.tsx b/src/components/features/settings/acp-auth-status-banner.tsx
new file mode 100644
index 0000000000..1d808b47cf
--- /dev/null
+++ b/src/components/features/settings/acp-auth-status-banner.tsx
@@ -0,0 +1,63 @@
+import { Check, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import type { AcpAuthStatus } from "#/hooks/query/use-acp-auth-status";
+
+interface AcpAuthStatusBannerProps {
+ status: AcpAuthStatus;
+ isChecking: boolean;
+ providerName: string;
+ /**
+ * Prefix for the banner test ids, e.g. ``"onboarding-acp-auth"`` β†’
+ * ``onboarding-acp-auth-detected`` / ``onboarding-acp-auth-checking``.
+ */
+ testIdPrefix: string;
+}
+
+/**
+ * Auth-status banner shared by the ACP credential forms (the onboarding step
+ * and Settings β†’ Agent): a green "already signed in" banner when the local
+ * login probe detects a session, or a spinner while it's checking. Renders
+ * nothing otherwise (unauthenticated / unknown / non-local backend), so the
+ * caller falls back to the API-key fields.
+ */
+export function AcpAuthStatusBanner({
+ status,
+ isChecking,
+ providerName,
+ testIdPrefix,
+}: AcpAuthStatusBannerProps) {
+ const { t } = useTranslation("openhands");
+
+ if (status === "authenticated") {
+ return (
+ <div
+ data-testid={`${testIdPrefix}-detected`}
+ // Matches the onboarding "backend connected" success banner
+ // (check-backend-step.tsx) for a consistent look.
+ className="flex items-start gap-2 rounded-xl border border-green-500/40 bg-green-500/10 px-4 py-3 text-sm text-green-200"
+ >
+ <Check className="mt-0.5 size-4 shrink-0 text-green-400" aria-hidden />
+ <span>
+ {t(I18nKey.ONBOARDING$ACP_AUTH_DETECTED, { provider: providerName })}
+ </span>
+ </div>
+ );
+ }
+
+ if (isChecking) {
+ return (
+ <div
+ data-testid={`${testIdPrefix}-checking`}
+ className="flex items-center gap-2 text-sm text-[var(--oh-muted)]"
+ >
+ <Loader2 className="size-4 shrink-0 animate-spin" aria-hidden />
+ <span>
+ {t(I18nKey.ONBOARDING$ACP_AUTH_CHECKING, { provider: providerName })}
+ </span>
+ </div>
+ );
+ }
+
+ return null;
+}
diff --git a/src/components/features/settings/acp-credentials-section.tsx b/src/components/features/settings/acp-credentials-section.tsx
index b35acedffb..028f1f6494 100644
--- a/src/components/features/settings/acp-credentials-section.tsx
+++ b/src/components/features/settings/acp-credentials-section.tsx
@@ -1,44 +1,35 @@
-import React from "react";
import { useTranslation } from "react-i18next";
import { AcpConflictWarnings } from "#/components/features/settings/acp-conflict-warnings";
+import { AcpAuthStatusBanner } from "#/components/features/settings/acp-auth-status-banner";
import { AcpSecretField } from "#/components/features/settings/acp-secret-field";
-import { BrandButton } from "#/components/features/settings/brand-button";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
-import { useAcpCredentialForm } from "#/hooks/use-acp-credential-form";
+import { useAcpAuthStatus } from "#/hooks/query/use-acp-auth-status";
+import { getAcpProviderDisplayName } from "#/constants/acp-providers";
+import type { AcpCredentialForm } from "#/hooks/use-acp-credential-form";
/**
- * Settings β†’ Agent credentials section for a built-in ACP provider: the same
- * fields the onboarding step collects, saved through the same flow
- * ({@link useAcpCredentialForm}), so credentials can be added or rotated after
- * onboarding. Renders nothing for providers without credential fields.
+ * Settings β†’ Agent credentials section for a built-in ACP provider: renders the
+ * same fields the onboarding step collects (and the same "already signed in"
+ * auth banner), so credentials can be added or rotated after onboarding. The
+ * form state and the save are owned by the parent (Settings β†’ Agent) so the
+ * page has a single Save button for both agent settings and credentials.
+ * Renders nothing for providers without credential fields.
*/
export function AcpCredentialsSection({
+ form,
providerKey,
}: {
+ form: AcpCredentialForm;
providerKey: string;
}) {
const { t } = useTranslation("openhands");
- const {
- fields,
- values,
- setValue,
- secretExists,
- conflicts,
- isDirty,
- save,
- reset,
- isSaving,
- } = useAcpCredentialForm(providerKey);
+ const { fields, values, setValue, secretExists, conflicts } = form;
+ const { status: authStatus, isChecking } = useAcpAuthStatus(providerKey);
+ const providerName = getAcpProviderDisplayName(providerKey) ?? providerKey;
if (fields.length === 0) return null;
- const handleSave = async () => {
- if (await save()) {
- reset();
- }
- };
-
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
@@ -50,6 +41,13 @@ export function AcpCredentialsSection({
</Typography.Text>
</div>
+ <AcpAuthStatusBanner
+ status={authStatus}
+ isChecking={isChecking}
+ providerName={providerName}
+ testIdPrefix="settings-acp-auth"
+ />
+
<div className="flex flex-col gap-5">
{fields.map((field) => (
<AcpSecretField
@@ -65,18 +63,6 @@ export function AcpCredentialsSection({
</div>
<AcpConflictWarnings conflicts={conflicts} />
-
- <BrandButton
- testId="acp-credentials-save-button"
- type="button"
- variant="primary"
- isDisabled={isSaving || !isDirty}
- onClick={handleSave}
- >
- {isSaving
- ? t(I18nKey.SETTINGS$SAVING)
- : t(I18nKey.SETTINGS$SAVE_CHANGES)}
- </BrandButton>
</div>
);
}
diff --git a/src/hooks/use-acp-credential-form.ts b/src/hooks/use-acp-credential-form.ts
index 2afdf0feef..f78a888a5b 100644
--- a/src/hooks/use-acp-credential-form.ts
+++ b/src/hooks/use-acp-credential-form.ts
@@ -25,8 +25,10 @@ export interface AcpCredentialForm {
consumesFileCredentials: boolean;
/** At least one field has a non-blank typed value. */
isDirty: boolean;
- /** Persist the filled fields; resolves ``true`` when everything saved. */
- save: () => Promise<boolean>;
+ /** Persist the filled fields; resolves ``true`` when everything saved.
+ * ``silent`` suppresses the success toast so a caller saving credentials
+ * alongside other state can emit a single combined confirmation. */
+ save: (options?: { silent?: boolean }) => Promise<boolean>;
reset: () => void;
isSaving: boolean;
}
@@ -92,7 +94,7 @@ export function useAcpCredentialForm(
conflicts: getAcpCredentialConflicts(providerKey, hasValueFor),
consumesFileCredentials,
isDirty: fields.some((field) => Boolean(values[field.name]?.trim())),
- save: () => saveFilled(values),
+ save: (options) => saveFilled(values, options),
reset,
isSaving,
};
diff --git a/src/hooks/use-save-acp-secrets.ts b/src/hooks/use-save-acp-secrets.ts
index 24ed1464d1..b35d4e5400 100644
--- a/src/hooks/use-save-acp-secrets.ts
+++ b/src/hooks/use-save-acp-secrets.ts
@@ -39,7 +39,14 @@ export function useSaveAcpSecrets(
const { mutateAsync: createSecret } = useCreateSecret();
const [isSaving, setIsSaving] = React.useState(false);
- const saveFilled = async (values: Record<string, string>) => {
+ // ``silent`` suppresses the success/warning toast (not errors) so a caller
+ // that persists credentials alongside something else β€” the Settings β†’ Agent
+ // single Save, which also writes the agent spec β€” can emit one combined
+ // "Saved" instead of two. The standalone onboarding caller leaves it off.
+ const saveFilled = async (
+ values: Record<string, string>,
+ { silent = false }: { silent?: boolean } = {},
+ ) => {
const toSave = fields
.map((field) => ({ field, value: values[field.name]?.trim() }))
.filter(
@@ -62,7 +69,7 @@ export function useSaveAcpSecrets(
!consumesFileCredentials && toSave.some(({ field }) => field.multiline);
if (savedOrphanedFileCredential) {
displayWarningToast(t(I18nKey.ONBOARDING$ACP_SECRETS_ORPHANED_WARNING));
- } else {
+ } else if (!silent) {
displaySuccessToast(t(I18nKey.SETTINGS$SAVED));
}
return true;
diff --git a/src/routes/agent-settings.tsx b/src/routes/agent-settings.tsx
index 5a3cc07d79..d5e5771cd2 100644
--- a/src/routes/agent-settings.tsx
+++ b/src/routes/agent-settings.tsx
@@ -8,6 +8,7 @@ import { SettingsDropdownInput } from "#/components/features/settings/settings-d
import { SettingsInput } from "#/components/features/settings/settings-input";
import { SettingsSwitch } from "#/components/features/settings/settings-switch";
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 { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
@@ -116,6 +117,19 @@ function AgentSettingsScreen() {
const [isCustomAcpModel, setIsCustomAcpModel] = useState(false);
const [isDirty, setIsDirty] = useState(false);
+ // ACP credentials live alongside the agent spec, so the page owns the
+ // credential form and a single Save persists both. Called unconditionally
+ // (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.
+ const acpPresetForCreds =
+ agentType === "acp" ? detectPreset(commandText, ACP_PROVIDERS) : null;
+ const acpCredentialForm = useAcpCredentialForm(
+ acpPresetForCreds && acpPresetForCreds !== ACP_CUSTOM_PRESET_KEY
+ ? acpPresetForCreds
+ : null,
+ );
+
const lastInitializedSettingsRef = useRef<unknown>(null);
const loadedAcpServerRef = useRef<string | null>(null);
const loadedCommandTextRef = useRef<string>("");
@@ -199,9 +213,31 @@ function AgentSettingsScreen() {
// Dirty tracking: for OpenHands path, also check sub-agents toggle
const isOpenHandsDirty =
!isAcp && subAgentsEnabled !== initialSubAgentsEnabled;
- const effectiveIsDirty = isDirty || isOpenHandsDirty;
+ const settingsDirty = isDirty || isOpenHandsDirty;
+ // The single Save covers both the agent spec and ACP credentials, so it is
+ // active when either changed, and shows "Saving…" while either is in flight.
+ // ``isDirty`` is already false off the ACP path (no credential fields), so no
+ // ``isAcp`` guard is needed.
+ const credentialsDirty = acpCredentialForm.isDirty;
+ const isAnyDirty = settingsDirty || credentialsDirty;
+ const isSavingAny = isSaving || acpCredentialForm.isSaving;
+
+ const handleSave = async () => {
+ // 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;
- const handleSave = () => {
if (isAcp) {
const useDefault = !!(selectedProvider && isDefaultProviderCommand);
const loadedServer = loadedAcpServerRef.current;
@@ -479,7 +515,10 @@ function AgentSettingsScreen() {
{isAcp && selectedPreset !== ACP_CUSTOM_PRESET_KEY && (
<>
<hr className="border-[#3D4046]" />
- <AcpCredentialsSection providerKey={selectedPreset} />
+ <AcpCredentialsSection
+ form={acpCredentialForm}
+ providerKey={selectedPreset}
+ />
</>
)}
@@ -488,10 +527,10 @@ function AgentSettingsScreen() {
testId="agent-save-button"
type="button"
variant="primary"
- isDisabled={isSaving || !effectiveIsDirty || isAcpInvalid}
+ isDisabled={isSavingAny || !isAnyDirty || isAcpInvalid}
onClick={handleSave}
>
- {isSaving
+ {isSavingAny
? t(I18nKey.SETTINGS$SAVING)
: t(I18nKey.SETTINGS$SAVE_CHANGES)}
</BrandButton>