Skip to content

πŸ™Œ OpenHands: AI-Driven Development

refactor(backends): PLTF-2954 extract useBackendForm hook, delete duplicated form state (#1341)

aivong-openhandsd2062a3ad3f9
diff --git a/__tests__/components/backends/backend-form-modal.test.tsx b/__tests__/components/backends/backend-form-modal.test.tsx
new file mode 100644
index 0000000000..88a1f9026c
--- /dev/null
+++ b/__tests__/components/backends/backend-form-modal.test.tsx
@@ -0,0 +1,293 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import {
+ ActiveBackendProvider,
+ useActiveBackendContext,
+} from "#/contexts/active-backend-context";
+import {
+ NavigationProvider,
+ type NavigationContextValue,
+} from "#/context/navigation-context";
+import { BackendFormModal } from "#/components/features/backends/backend-form-modal";
+
+const getServerInfoMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(function ServerClientMock() {
+ return {
+ getServerInfo: getServerInfoMock,
+ };
+ }),
+}));
+
+function renderWithProviders(
+ ui: React.ReactElement,
+ navigation?: NavigationContextValue,
+) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ {navigation ? (
+ <NavigationProvider value={navigation}>{ui}</NavigationProvider>
+ ) : (
+ ui
+ )}
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+}
+
+function TestSeed({
+ onMount,
+ children,
+}: {
+ onMount: (ctx: ReturnType<typeof useActiveBackendContext>) => void;
+ children: React.ReactNode;
+}) {
+ const ctx = useActiveBackendContext();
+ React.useEffect(() => {
+ onMount(ctx);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ return children as React.ReactElement;
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ getServerInfoMock.mockReset();
+ getServerInfoMock.mockResolvedValue({ version: "1.28.0" });
+ __resetActiveStoreForTests();
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+});
+
+describe("BackendFormModal – edit mode (BackendForm entry point)", () => {
+ it("pre-fills fields with the backend data passed as prop", () => {
+ renderWithProviders(
+ <BackendFormModal
+ mode="edit"
+ backend={{
+ id: "seeded-id",
+ name: "My Server",
+ host: "http://localhost:9000",
+ apiKey: "sk-old",
+ kind: "local",
+ }}
+ onClose={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId("edit-backend-name")).toHaveValue("My Server");
+ expect(screen.getByTestId("edit-backend-host")).toHaveValue(
+ "http://localhost:9000",
+ );
+ expect(screen.getByTestId("edit-backend-api-key")).toHaveValue("sk-old");
+ });
+
+ it("disables Save when name is cleared", async () => {
+ renderWithProviders(
+ <BackendFormModal
+ mode="edit"
+ backend={{
+ id: "seeded-id",
+ name: "My Server",
+ host: "http://localhost:9000",
+ apiKey: "",
+ kind: "local",
+ }}
+ onClose={vi.fn()}
+ />,
+ );
+
+ const submit = screen.getByTestId(
+ "edit-backend-submit",
+ ) as HTMLButtonElement;
+ expect(submit).not.toBeDisabled();
+
+ const user = userEvent.setup();
+ const nameInput = screen.getByTestId("edit-backend-name");
+ await user.clear(nameInput);
+
+ expect(submit).toBeDisabled();
+ });
+
+ it("calls updateBackend and onClose on successful submit", async () => {
+ let backendId = "";
+ const onClose = vi.fn();
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ backendId = ctx
+ .addBackend({
+ name: "Local Seed",
+ host: "http://localhost:9000",
+ apiKey: "sk-old",
+ kind: "local",
+ })
+ .id;
+ }}
+ >
+ <BackendFormModal
+ mode="edit"
+ backend={{
+ id: backendId,
+ name: "Local Seed",
+ host: "http://localhost:9000",
+ apiKey: "sk-old",
+ kind: "local",
+ }}
+ onClose={onClose}
+ />
+ </TestSeed>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("edit-backend-name")).toHaveValue(
+ "Local Seed",
+ );
+ });
+
+ const user = userEvent.setup();
+
+ // Verify the submit button is enabled with pre-filled values
+ const submitBtn = screen.getByTestId("edit-backend-submit");
+ expect(submitBtn).not.toBeDisabled();
+
+ await user.click(submitBtn);
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ const stored = JSON.parse(
+ window.localStorage.getItem("openhands-backends") ?? "[]",
+ );
+ const updated = stored.find((b: { id: string }) => b.id === backendId);
+ expect(updated).toMatchObject({
+ id: backendId,
+ name: "Local Seed",
+ host: "http://localhost:9000",
+ kind: "local",
+ });
+ });
+
+ it("shows connection error and keeps modal open when probe fails", async () => {
+ // Default: health check succeeds (otherwise the modal won't render cleanly).
+ // Override just before the submit action so the submit-time probe fails.
+ let backendId = "";
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ backendId = ctx
+ .addBackend({
+ name: "Offline Server",
+ host: "http://localhost:9999",
+ apiKey: "sk-key",
+ kind: "local",
+ })
+ .id;
+ }}
+ >
+ <BackendFormModal
+ mode="edit"
+ backend={{
+ id: backendId,
+ name: "Offline Server",
+ host: "http://localhost:9999",
+ apiKey: "sk-key",
+ kind: "local",
+ }}
+ onClose={vi.fn()}
+ />
+ </TestSeed>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("edit-backend-name")).toHaveValue(
+ "Offline Server",
+ );
+ });
+
+ const user = userEvent.setup();
+ const nameInput = screen.getByTestId("edit-backend-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "Retry Server");
+
+ // Now make the submit-time probe fail (health check already consumed the default mock).
+ getServerInfoMock.mockRejectedValueOnce(new Error("Connection refused"));
+
+ await user.click(screen.getByTestId("edit-backend-submit"));
+
+ expect(
+ await screen.findByTestId("edit-backend-error"),
+ ).toHaveTextContent("Connection refused");
+ });
+
+ it("preserves cloud kind when editing a cloud backend", async () => {
+ let backendId = "";
+ const onClose = vi.fn();
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ backendId = ctx
+ .addBackend({
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "sk-cloud",
+ kind: "cloud",
+ })
+ .id;
+ }}
+ >
+ <BackendFormModal
+ mode="edit"
+ backend={{
+ id: backendId,
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "sk-cloud",
+ kind: "cloud",
+ }}
+ onClose={onClose}
+ />
+ </TestSeed>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("edit-backend-name")).toHaveValue(
+ "OpenHands Cloud",
+ );
+ });
+
+ const user = userEvent.setup();
+ const nameInput = screen.getByTestId("edit-backend-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed Cloud");
+
+ const apiKeyInput = screen.getByTestId("edit-backend-api-key");
+ await user.clear(apiKeyInput);
+ await user.type(apiKeyInput, "new-token");
+
+ await user.click(screen.getByTestId("edit-backend-submit"));
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ const stored = JSON.parse(
+ window.localStorage.getItem("openhands-backends") ?? "[]",
+ );
+ const updated = stored.find((b: { id: string }) => b.id === backendId);
+ expect(updated).toMatchObject({
+ id: backendId,
+ kind: "cloud",
+ });
+ });
+});
diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsx
index d96839804c..2cdd02b9fc 100644
--- a/src/components/features/backends/backend-form-modal.tsx
+++ b/src/components/features/backends/backend-form-modal.tsx
@@ -264,6 +264,123 @@ export interface BackendFormSubmitPayload {
kind: BackendKind;
}
+interface UseBackendFormOptions {
+ initialName?: string;
+ initialHost?: string;
+ initialApiKey?: string;
+ /**
+ * Called to test the connection. The hook does NOT call
+ * `testBackendConnection` directly so callers can inject a
+ * wrapped version (e.g. with extra logging or different timeout).
+ * Should throw on failure.
+ */
+ onTestConnection: (payload: BackendFormSubmitPayload) => Promise<void>;
+ /** Called after a successful connection test and persistence. */
+ onSuccess: () => void;
+ /**
+ * When provided, completely replaces the default submit flow
+ * (onTestConnection + onSuccess). The hook still manages form state
+ * and canSubmit validation, but the caller owns error handling and
+ * success side effects. Should throw on failure.
+ */
+ onSubmitOverride?: (payload: BackendFormSubmitPayload) => Promise<void>;
+}
+
+/**
+ * Shared hook for the backend-form state used by both `BackendForm`
+ * (edit/add mode) and `ManualConnectionColumn` (add-mode-only column).
+ * Encapsulates name / host / apiKey fields, `connectionError`,
+ * `isSubmitting`, and the shared `handleSubmit` flow.
+ */
+function useBackendForm({
+ initialName = "",
+ initialHost = "",
+ initialApiKey = "",
+ onTestConnection,
+ onSuccess,
+ onSubmitOverride,
+}: UseBackendFormOptions) {
+ const { t } = useTranslation("openhands");
+
+ const [name, setName] = React.useState(initialName);
+ const [host, setHost] = React.useState(initialHost);
+ const [apiKey, setApiKey] = React.useState(initialApiKey);
+ const [connectionError, setConnectionError] = React.useState<string | null>(
+ null,
+ );
+ const [isSubmitting, setIsSubmitting] = React.useState(false);
+
+ const kind = inferKindFromHost(host);
+ const canSubmit =
+ name.trim().length > 0 &&
+ isValidHostUrl(host) &&
+ (kind === "local" || apiKey.trim().length > 0);
+
+ const handleSubmit = React.useCallback(
+ async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ if (!canSubmit || isSubmitting) return;
+
+ const payload: BackendFormSubmitPayload = {
+ name: name.trim(),
+ host: normalizeHost(host),
+ apiKey: apiKey.trim(),
+ kind,
+ };
+
+ setConnectionError(null);
+ setIsSubmitting(true);
+
+ try {
+ // When onSubmitOverride is provided, it completely replaces the
+ // default flow (onTestConnection + onSuccess).
+ if (onSubmitOverride) {
+ await onSubmitOverride(payload);
+ } else {
+ await onTestConnection(payload);
+ onSuccess();
+ }
+ } catch (error) {
+ setConnectionError(
+ getConnectionTestFailedMessage(
+ getConnectionTestFailedTitle(t, payload.host),
+ error,
+ ),
+ );
+ } finally {
+ setIsSubmitting(false);
+ }
+ },
+ [
+ canSubmit,
+ isSubmitting,
+ name,
+ host,
+ apiKey,
+ kind,
+ onTestConnection,
+ onSuccess,
+ onSubmitOverride,
+ t,
+ ],
+ );
+
+ return {
+ name,
+ setName,
+ host,
+ setHost,
+ apiKey,
+ setApiKey,
+ connectionError,
+ setConnectionError,
+ isSubmitting,
+ kind,
+ canSubmit,
+ handleSubmit,
+ };
+}
+
export interface BackendFormProps {
mode: BackendFormMode;
/** Required when `mode === "edit"`. */
@@ -335,26 +452,53 @@ export function BackendForm({
const { t } = useTranslation("openhands");
const { addBackend, updateBackend } = useActiveBackendContext();
- const [name, setName] = React.useState(backend?.name ?? "");
- const [host, setHost] = React.useState(backend?.host ?? "");
- const [apiKey, setApiKey] = React.useState(backend?.apiKey ?? "");
- const [connectionError, setConnectionError] = React.useState<string | null>(
- null,
- );
- const [isSubmitting, setIsSubmitting] = React.useState(false);
-
- // Inline validation: only show errors after the user has left a field.
- const [nameTouched, setNameTouched] = React.useState(false);
- const [hostTouched, setHostTouched] = React.useState(false);
-
// In edit mode preserve the existing backend's kind so that renaming or
// rotating the API key on a cloud backend (e.g. an OHE/enterprise instance
// on a custom domain) does not silently downgrade it to "local" and switch
// the auth header from `Authorization: Bearer` to `X-Session-API-Key`.
// Only infer from the host when adding a new backend.
- const kind: BackendKind =
- mode === "edit" && backend ? backend.kind : inferKindFromHost(host);
+ const fixedKind: BackendKind | null =
+ mode === "edit" && backend ? backend.kind : null;
+
+ const {
+ name,
+ setName,
+ host,
+ setHost,
+ apiKey,
+ setApiKey,
+ connectionError,
+ setConnectionError,
+ isSubmitting,
+ kind: inferredKind,
+ handleSubmit: runSubmit,
+ } = useBackendForm({
+ initialName: backend?.name ?? "",
+ initialHost: backend?.host ?? "",
+ initialApiKey: backend?.apiKey ?? "",
+ onTestConnection: testBackendConnection,
+ onSuccess: async () => {
+ const payload: BackendFormSubmitPayload = {
+ name: name.trim(),
+ host: normalizeHost(host),
+ apiKey: apiKey.trim(),
+ kind: fixedKind ?? inferredKind,
+ };
+ if (mode === "edit" && backend) {
+ updateBackend(backend.id, payload);
+ } else {
+ addBackend(payload);
+ }
+ onSubmitted();
+ },
+ onSubmitOverride,
+ });
+ // Inline validation: only show errors after the user has left a field.
+ const [nameTouched, setNameTouched] = React.useState(false);
+ const [hostTouched, setHostTouched] = React.useState(false);
+
+ const kind = fixedKind ?? inferredKind;
const testIdRoot =
explicitTestIdRoot ?? (mode === "edit" ? "edit-backend" : "add-backend");
@@ -376,9 +520,6 @@ export function BackendForm({
: undefined;
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- if (isSubmitting) return;
-
if (!canSubmit) {
// Mark all validated fields as touched so inline errors become visible
// (e.g. user pressed Enter before filling required fields).
@@ -386,42 +527,7 @@ export function BackendForm({
setHostTouched(true);
return;
}
-
- const payload: BackendFormSubmitPayload = {
- name: name.trim(),
- host: normalizeHost(host),
- apiKey: apiKey.trim(),
- kind,
- };
-
- setConnectionError(null);
- setIsSubmitting(true);
-
- try {
- if (onSubmitOverride) {
- await onSubmitOverride(payload);
- return;
- }
-
- await testBackendConnection(payload);
-
- if (mode === "edit" && backend) {
- updateBackend(backend.id, payload);
- } else {
- addBackend(payload);
- }
-
- onSubmitted();
- } catch (error) {
- setConnectionError(
- getConnectionTestFailedMessage(
- getConnectionTestFailedTitle(t, payload.host),
- error,
- ),
- );
- } finally {
- setIsSubmitting(false);
- }
+ await runSubmit(event);
};
return (
@@ -562,50 +668,32 @@ function ManualConnectionColumn({ onClose }: { onClose: () => void }) {
const { addBackend } = useActiveBackendContext();
const redirectAfterAdd = useRedirectAfterAddBackend();
- const [name, setName] = React.useState("");
- const [host, setHost] = React.useState("");
- const [apiKey, setApiKey] = React.useState("");
- const [connectionError, setConnectionError] = React.useState<string | null>(
- null,
- );
- const [isSubmitting, setIsSubmitting] = React.useState(false);
-
- const kind: BackendKind = inferKindFromHost(host);
- const canSubmit =
- name.trim().length > 0 &&
- isValidHostUrl(host) &&
- (kind === "local" || apiKey.trim().length > 0);
-
- const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault();
- if (!canSubmit || isSubmitting) return;
-
- const payload = {
- name: name.trim(),
- host: normalizeHost(host),
- apiKey: apiKey.trim(),
- kind,
- };
-
- setConnectionError(null);
- setIsSubmitting(true);
-
- try {
- await testBackendConnection(payload);
- addBackend(payload);
+ const {
+ name,
+ setName,
+ host,
+ setHost,
+ apiKey,
+ setApiKey,
+ connectionError,
+ setConnectionError,
+ isSubmitting,
+ kind,
+ canSubmit,
+ handleSubmit,
+ } = useBackendForm({
+ onTestConnection: testBackendConnection,
+ onSuccess: () => {
+ addBackend({
+ name: name.trim(),
+ host: normalizeHost(host),
+ apiKey: apiKey.trim(),
+ kind,
+ });
redirectAfterAdd();
onClose();
- } catch (error) {
- setConnectionError(
- getConnectionTestFailedMessage(
- getConnectionTestFailedTitle(t, payload.host),
- error,
- ),
- );
- } finally {
- setIsSubmitting(false);
- }
- };
+ },
+ });
return (
<form