🙌 OpenHands: AI-Driven Development
fix: locked Cloud backend reconnect modal (#1807)
Graham Neubig61c8e5f835ac
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsxindex 1f9cf3d083..e7a7d931e2 100644--- a/__tests__/components/backends/backend-selector.test.tsx+++ b/__tests__/components/backends/backend-selector.test.tsx@@ -616,6 +616,20 @@ describe("BackendSelector", () => {});});+ it("hides add-backend footer action when locked to Cloud", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");++ renderWithProviders(<BackendSelector />);++ await openDropdown();+ expect(+ screen.queryByTestId("add-backend-menu-item"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("manage-backends-menu-item")).toHaveTextContent(+ "BACKEND$RECONNECT_CLOUD",+ );+ });+it("includes the seeded default Local backend in the manage backends modal as a removable entry", async () => {renderWithProviders(<BackendSelector />);diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsxindex 3589e086fe..18be777f02 100644--- a/__tests__/components/backends/manage-backends-modal.test.tsx+++ b/__tests__/components/backends/manage-backends-modal.test.tsx@@ -555,6 +555,138 @@ describe("ManageBackendsModal", () => {expect.anything(),);});+ it("uses Cloud reconnect recovery controls when locked to Cloud", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const user = userEvent.setup();+ vi.spyOn(window, "open").mockReturnValue({+ closed: false,+ close: vi.fn(),+ location: { href: "" },+ } as unknown as Window);++ renderWithProviders(+ <TestSeed+ onMount={(ctx) => {+ ctx.addBackend({+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "expired-token",+ kind: "cloud",+ });+ }}+ >+ <ManageBackendsModal onClose={vi.fn()} recoveryMode />+ </TestSeed>,+ );++ expect(+ await screen.findByRole("heading", {+ name: "BACKEND$RECONNECT_CLOUD_TITLE",+ }),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("manage-backends-add")).not.toBeInTheDocument();++ const reconnectButton = await screen.findByTestId(+ "manage-backends-reconnect-cloud-login-button",+ );+ expect(reconnectButton).toHaveTextContent("BACKEND$RECONNECT_CLOUD");++ await user.click(reconnectButton);+ expect(deviceFlowMocks.startDeviceFlow).toHaveBeenCalledWith(+ "https://app.all-hands.dev",+ );+ });++ it("updates the locked Cloud backend token when reconnect succeeds", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ deviceFlowMocks.pollForToken.mockResolvedValue({+ access_token: "fresh-cloud-token",+ token_type: "Bearer",+ });+ const user = userEvent.setup();+ vi.spyOn(window, "open").mockReturnValue({+ closed: false,+ close: vi.fn(),+ location: { href: "" },+ } as unknown as Window);++ renderWithProviders(+ <TestSeed+ onMount={(ctx) => {+ ctx.addBackend({+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "expired-token",+ kind: "cloud",+ });+ }}+ >+ <ManageBackendsModal onClose={vi.fn()} recoveryMode />+ </TestSeed>,+ );++ await user.click(+ await screen.findByTestId(+ "manage-backends-reconnect-cloud-login-button",+ ),+ );++ await waitFor(() => {+ const stored = JSON.parse(+ window.localStorage.getItem("openhands-backends") ?? "[]",+ );+ expect(stored).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "OpenHands Cloud",+ apiKey: "fresh-cloud-token",+ }),+ ]),+ );+ });+ expect(+ screen.queryByTestId("manage-backends-reconnect-cloud-auth-modal"),+ ).not.toBeInTheDocument();+ });++ it("keeps locked Cloud recovery open when reconnect authorization fails", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ deviceFlowMocks.pollForToken.mockRejectedValue(+ new Error("Authorization request was denied."),+ );+ const user = userEvent.setup();+ vi.spyOn(window, "open").mockReturnValue({+ closed: false,+ close: vi.fn(),+ location: { href: "" },+ } as unknown as Window);++ renderWithProviders(+ <TestSeed+ onMount={(ctx) => {+ ctx.addBackend({+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "expired-token",+ kind: "cloud",+ });+ }}+ >+ <ManageBackendsModal onClose={vi.fn()} recoveryMode />+ </TestSeed>,+ );++ await user.click(+ await screen.findByTestId(+ "manage-backends-reconnect-cloud-login-button",+ ),+ );++ expect(+ await screen.findByTestId("manage-backends-reconnect-cloud-auth-error"),+ ).toHaveTextContent("Authorization request was denied.");+ expect(screen.getByTestId("manage-backends-modal")).toBeInTheDocument();+ });});function renderInQueryClient(ui: React.ReactElement) {diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsxindex fa0ba1d28d..a4908d28de 100644--- a/__tests__/root.test.tsx+++ b/__tests__/root.test.tsx@@ -11,6 +11,8 @@ import { ONBOARDING_COMPLETED_STORAGE_KEY } from "#/components/features/onboardiconst TRANSLATIONS: Record<string, string> = {BACKEND$MANAGE_TITLE: "Manage backends",+ BACKEND$RECONNECT_CLOUD_TITLE: "Reconnect to Cloud",+ BACKEND$RECONNECT_CLOUD: "Reconnect to Cloud",BACKEND$MANAGE_EMPTY: "No backends yet.",BACKEND$ADD: "+ Add Backend",BACKEND$LOG_BACK_IN: "Log back in",@@ -560,6 +562,49 @@ describe("App root agent-server availability guard", () => {expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();});+ it("shows locked Cloud reconnect recovery without add-backend controls", async () => {+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");+ const cloudBackend = {+ id: "cloud-expired",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "expired-token",+ kind: "cloud",+ };+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([cloudBackend]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: cloudBackend.id, orgId: null }),+ );+ window.sessionStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: cloudBackend.id, orgId: null }),+ );+ window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");+ __resetActiveStoreForTests();+ server.use(+ http.get("https://app.all-hands.dev/api/keys/current", () =>+ HttpResponse.json({ detail: "NoCredentialsError" }, { status: 401 }),+ ),+ );++ renderApp(["/"]);++ await waitFor(() => {+ expect(+ screen.getByRole("heading", { name: "Reconnect to Cloud" }),+ ).toBeInTheDocument();+ });+ expect(screen.queryByTestId("manage-backends-add")).not.toBeInTheDocument();+ expect(+ screen.getByTestId("manage-backends-reconnect-cloud-login-button"),+ ).toHaveTextContent("Reconnect to Cloud");+ expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();+ });+it("renders the routed page when the agent server is reachable", async () => {window.localStorage.setItem(ONBOARDING_COMPLETED_STORAGE_KEY, "1");diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsxindex fca0406602..1f71fec098 100644--- a/src/components/features/backends/backend-selector.tsx+++ b/src/components/features/backends/backend-selector.tsx@@ -4,6 +4,7 @@ import { useMatch, useNavigate } from "react-router";import { Plus, Settings } from "lucide-react";import { Dropdown } from "#/ui/dropdown/dropdown";import { DropdownOption } from "#/ui/dropdown/types";+import { getLockedCloudHost } from "#/api/agent-server-config";import { isNoBackend } from "#/api/backend-registry/active-store";import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useAllCloudOrganizations } from "#/hooks/query/use-cloud-organizations";@@ -252,6 +253,8 @@ export function BackendSelector({setManageBackendsModalOpen(true);}, [onOpenManageBackends, onSelectOption]);+ const isLockedToCloud = getLockedCloudHost() !== null;+const preventDropdownMenuClose = React.useCallback((event: React.SyntheticEvent<HTMLButtonElement>) => {event.preventDefault();@@ -294,23 +297,25 @@ export function BackendSelector({const addBackendFooter = (<div className={dropdownMenuListClassName}>- <button- type="button"- data-testid="add-backend-menu-item"- onMouseDown={preventDropdownMenuClose}- onTouchStart={preventDropdownMenuClose}- onTouchEnd={handleAddBackendTouchEnd}- onClick={handleAddBackendClick}- className={cn(- dropdownFooterActionClassName,- "cursor-pointer rounded-md",- )}- >- <span className={dropdownMenuRowIconWrapperClassName} aria-hidden>- <Plus width={16} height={16} />- </span>- {t(I18nKey.BACKEND$ADD)}- </button>+ {isLockedToCloud ? null : (+ <button+ type="button"+ data-testid="add-backend-menu-item"+ onMouseDown={preventDropdownMenuClose}+ onTouchStart={preventDropdownMenuClose}+ onTouchEnd={handleAddBackendTouchEnd}+ onClick={handleAddBackendClick}+ className={cn(+ dropdownFooterActionClassName,+ "cursor-pointer rounded-md",+ )}+ >+ <span className={dropdownMenuRowIconWrapperClassName} aria-hidden>+ <Plus width={16} height={16} />+ </span>+ {t(I18nKey.BACKEND$ADD)}+ </button>+ )}<buttontype="button"data-testid="manage-backends-menu-item"@@ -326,7 +331,11 @@ export function BackendSelector({<span className={dropdownMenuRowIconWrapperClassName} aria-hidden><Settings width={16} height={16} /></span>- {t(I18nKey.BACKEND$MANAGE)}+ {t(+ isLockedToCloud+ ? I18nKey.BACKEND$RECONNECT_CLOUD+ : I18nKey.BACKEND$MANAGE,+ )}</button></div>);diff --git a/src/components/features/backends/manage-backends-modal.tsx b/src/components/features/backends/manage-backends-modal.tsxindex 0be04a6300..4a230026ba 100644--- a/src/components/features/backends/manage-backends-modal.tsx+++ b/src/components/features/backends/manage-backends-modal.tsx@@ -2,6 +2,7 @@ import React from "react";import { useTranslation } from "react-i18next";import { Plus } from "lucide-react";+import { getLockedCloudHost } from "#/api/agent-server-config";import { type Backend } from "#/api/backend-registry/types";import { BrandButton } from "#/components/features/settings/brand-button";import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";@@ -20,6 +21,7 @@ import { cn } from "#/utils/utils";import { modalTitleLgClassName } from "#/utils/modal-classes";import { BackendFormModal } from "./backend-form-modal";import { BackendRow } from "./backend-row";+import { DeviceFlowAuth } from "./device-flow-auth";interface ManageBackendsModalProps {onClose: () => void;@@ -71,6 +73,15 @@ export function ManageBackendsModal({const cloudOrgs = useAllCloudOrganizations();const currentUserIds = useCloudCurrentUserId();const personalWorkspaceLabel = t(I18nKey.BACKEND$PERSONAL_WORKSPACE);+ const lockedCloudHost = getLockedCloudHost();+ const isLockedToCloud = lockedCloudHost !== null;+ const lockedCloudBackend =+ isLockedToCloud && active.backend.kind === "cloud" ? active.backend : null;+ const lockedCloudReconnectHost =+ lockedCloudHost ?? lockedCloudBackend?.host ?? "";+ const modalTitle = isLockedToCloud+ ? t(I18nKey.BACKEND$RECONNECT_CLOUD_TITLE)+ : t(I18nKey.BACKEND$MANAGE_TITLE);const [pendingRemoval, setPendingRemoval] =React.useState<PendingRemoval | null>(null);const [editingBackend, setEditingBackend] = React.useState<Backend | null>(@@ -101,13 +112,21 @@ export function ManageBackendsModal({[updateBackend],);+ const handleLockedCloudReconnect = React.useCallback(+ (apiKey: string) => {+ if (!lockedCloudBackend) return;+ updateBackend(lockedCloudBackend.id, { apiKey });+ },+ [lockedCloudBackend, updateBackend],+ );+return (<><ModalBackdroponClose={recoveryMode ? undefined : onClose}closeOnEscape={!recoveryMode}closeOnBackdropClick={!recoveryMode}- aria-label={t(I18nKey.BACKEND$MANAGE_TITLE)}+ aria-label={modalTitle}><divdata-testid="manage-backends-modal"@@ -125,9 +144,7 @@ export function ManageBackendsModal({/>)}<div className={cn("p-5", !recoveryMode && "pr-12")}>- <h2 className={modalTitleLgClassName}>- {t(I18nKey.BACKEND$MANAGE_TITLE)}- </h2>+ <h2 className={modalTitleLgClassName}>{modalTitle}</h2></div><div className="flex min-h-0 flex-1 flex-col px-5">@@ -169,15 +186,29 @@ export function ManageBackendsModal({</div><div className="flex justify-end gap-2 p-5">- <BrandButton- type="button"- variant={recoveryMode ? "primary" : "secondary"}- onClick={() => setShowAddForm(true)}- testId="manage-backends-add"- startContent={<Plus width={14} height={14} />}- >- {t(I18nKey.BACKEND$ADD)}- </BrandButton>+ {isLockedToCloud ? (+ lockedCloudBackend ? (+ <DeviceFlowAuth+ host={lockedCloudReconnectHost}+ onSuccess={handleLockedCloudReconnect}+ testIdRoot="manage-backends-reconnect-cloud"+ idleButtonLabel={t(I18nKey.BACKEND$RECONNECT_CLOUD)}+ className="w-full sm:w-auto"+ buttonClassName="sm:w-auto"+ statusDisplay="modal"+ />+ ) : null+ ) : (+ <BrandButton+ type="button"+ variant={recoveryMode ? "primary" : "secondary"}+ onClick={() => setShowAddForm(true)}+ testId="manage-backends-add"+ startContent={<Plus width={14} height={14} />}+ >+ {t(I18nKey.BACKEND$ADD)}+ </BrandButton>+ )}{recoveryMode ? null : (<BrandButtontype="button"diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 3cca4fc12f..55e5482c49 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -28678,6 +28678,40 @@"uk": "Керувати бекендами","ca": "Gestiona els backends"},+ "BACKEND$RECONNECT_CLOUD_TITLE": {+ "en": "Reconnect to Cloud",+ "ja": "Cloud に再接続",+ "zh-CN": "重新连接到 Cloud",+ "zh-TW": "重新連線至 Cloud",+ "ko-KR": "Cloud에 다시 연결",+ "no": "Koble til Cloud på nytt",+ "it": "Riconnettiti a Cloud",+ "pt": "Reconectar ao Cloud",+ "es": "Reconectar a Cloud",+ "ar": "إعادة الاتصال بـ Cloud",+ "fr": "Se reconnecter à Cloud",+ "tr": "Cloud'a yeniden bağlan",+ "de": "Erneut mit Cloud verbinden",+ "uk": "Повторно підключитися до Cloud",+ "ca": "Torna a connectar a Cloud"+ },+ "BACKEND$RECONNECT_CLOUD": {+ "en": "Reconnect to Cloud",+ "ja": "Cloud に再接続",+ "zh-CN": "重新连接到 Cloud",+ "zh-TW": "重新連線至 Cloud",+ "ko-KR": "Cloud에 다시 연결",+ "no": "Koble til Cloud på nytt",+ "it": "Riconnettiti a Cloud",+ "pt": "Reconectar ao Cloud",+ "es": "Reconectar a Cloud",+ "ar": "إعادة الاتصال بـ Cloud",+ "fr": "Se reconnecter à Cloud",+ "tr": "Cloud'a yeniden bağlan",+ "de": "Erneut mit Cloud verbinden",+ "uk": "Повторно підключитися до Cloud",+ "ca": "Torna a connectar a Cloud"+ },"BACKEND$MANAGE_EMPTY": {"en": "No extra backends added yet.","ja": "追加されたバックエンドはまだありません。",