π OpenHands: AI-Driven Development
Fix manage backends recovery (#1205)
Graham Neubigabc2cec356bf
diff --git a/src/components/features/backends/manage-backends-modal.tsx b/src/components/features/backends/manage-backends-modal.tsxindex 3d31d47abe..d3f41b620a 100644--- a/src/components/features/backends/manage-backends-modal.tsx+++ b/src/components/features/backends/manage-backends-modal.tsx@@ -62,6 +62,11 @@ function BackendVersion({ backend }: { backend: Backend }) {interface ManageBackendsModalProps {onClose: () => void;+ /**+ * Recovery mode is used by the root unavailable-backend gate. There is no+ * app shell behind the modal, so dismiss controls would be misleading.+ */+ recoveryMode?: boolean;}interface PendingRemoval {@@ -72,11 +77,18 @@ interface PendingRemoval {interface BackendRowProps {backend: Backend;health: BackendHealth | undefined;+ onSelect: () => void;onEdit: () => void;onRemove: () => void;}-function BackendRow({ backend, health, onEdit, onRemove }: BackendRowProps) {+function BackendRow({+ backend,+ health,+ onSelect,+ onEdit,+ onRemove,+}: BackendRowProps) {const { t } = useTranslation("openhands");const isInvalidApiKey = isInvalidBackendApiKeyHealthError(health?.lastError);let statusLabel: string;@@ -95,34 +107,47 @@ function BackendRow({ backend, health, onEdit, onRemove }: BackendRowProps) {statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING);}const dotStatus = isInvalidApiKey ? false : (health?.isConnected ?? null);+ const canSelect = health?.isConnected === true && !isInvalidApiKey;return (<li- className="flex items-center gap-3 px-3 py-3"+ className="flex items-stretch"data-testid={`manage-backends-row-${backend.name}`}>- <BackendStatusDot isConnected={dotStatus} />- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex min-w-0 items-center gap-2">- <span className="truncate text-sm text-white">{backend.name}</span>- <BackendVersion backend={backend} />+ <button+ type="button"+ disabled={!canSelect}+ onClick={onSelect}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-3 px-3 py-3 text-left",+ canSelect+ ? "cursor-pointer transition-colors hover:bg-interactive-hover focus-visible:bg-interactive-hover focus-visible:outline-none"+ : "cursor-default",+ )}+ >+ <BackendStatusDot isConnected={dotStatus} />+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm text-white">{backend.name}</span>+ <BackendVersion backend={backend} />+ </div>+ <span className="truncate text-xs text-[var(--oh-muted)]">+ {backend.host}+ </span>+ <span+ data-testid={`manage-backends-status-${backend.name}`}+ className={cn("truncate text-xs", statusClassName)}+ >+ {statusLabel}+ </span></div>- <span className="truncate text-xs text-[var(--oh-muted)]">- {backend.host}- </span>- <span- data-testid={`manage-backends-status-${backend.name}`}- className={cn("truncate text-xs", statusClassName)}- >- {statusLabel}+ <span className="px-2 py-1 rounded-full text-[11px] uppercase tracking-wide text-[var(--oh-text-tertiary)] bg-[var(--oh-surface)] border border-[var(--oh-border)]">+ {backend.kind === "cloud"+ ? t(I18nKey.BACKEND$KIND_CLOUD)+ : t(I18nKey.BACKEND$KIND_LOCAL)}</span>- </div>- <span className="px-2 py-1 rounded-full text-[11px] uppercase tracking-wide text-[var(--oh-text-tertiary)] bg-[var(--oh-surface)] border border-[var(--oh-border)]">- {backend.kind === "cloud"- ? t(I18nKey.BACKEND$KIND_CLOUD)- : t(I18nKey.BACKEND$KIND_LOCAL)}- </span>- <div className="flex shrink-0 items-center gap-0.5">+ </button>+ <div className="flex shrink-0 items-center gap-0.5 px-3 py-3"><buttontype="button"onClick={onEdit}@@ -146,9 +171,13 @@ function BackendRow({ backend, health, onEdit, onRemove }: BackendRowProps) {);}-export function ManageBackendsModal({ onClose }: ManageBackendsModalProps) {+export function ManageBackendsModal({+ onClose,+ recoveryMode = false,+}: ManageBackendsModalProps) {const { t } = useTranslation("openhands");- const { backends, removeBackend } = useActiveBackendContext();+ const { backends, active, removeBackend, setActive } =+ useActiveBackendContext();const healthByBackendId = useBackendsHealth(backends, {probeDisabledOnce: true,});@@ -165,10 +194,22 @@ export function ManageBackendsModal({ onClose }: ManageBackendsModalProps) {setPendingRemoval(null);};+ const handleSelectBackend = React.useCallback(+ (backend: Backend) => {+ if (active.backend.id !== backend.id || active.orgId !== null) {+ setActive(backend.id);+ }+ onClose();+ },+ [active.backend.id, active.orgId, onClose, setActive],+ );+return (<><ModalBackdrop- onClose={onClose}+ onClose={recoveryMode ? undefined : onClose}+ closeOnEscape={!recoveryMode}+ closeOnBackdropClick={!recoveryMode}aria-label={t(I18nKey.BACKEND$MANAGE_TITLE)}><div@@ -180,11 +221,13 @@ export function ManageBackendsModal({ onClose }: ManageBackendsModalProps) {"max-h-[70vh]",)}>- <ModalCloseButton- onClose={onClose}- testId="close-manage-backends-modal"- />- <div className="p-5 pr-12">+ {recoveryMode ? null : (+ <ModalCloseButton+ onClose={onClose}+ testId="close-manage-backends-modal"+ />+ )}+ <div className={cn("p-5", !recoveryMode && "pr-12")}><h2 className={modalTitleLgClassName}>{t(I18nKey.BACKEND$MANAGE_TITLE)}</h2>@@ -206,6 +249,7 @@ export function ManageBackendsModal({ onClose }: ManageBackendsModalProps) {key={backend.id}backend={backend}health={healthByBackendId[backend.id]}+ onSelect={() => handleSelectBackend(backend)}onEdit={() => setEditingBackend(backend)}onRemove={() =>setPendingRemoval({@@ -223,21 +267,23 @@ export function ManageBackendsModal({ onClose }: ManageBackendsModalProps) {<div className="flex justify-end gap-2 p-5"><BrandButtontype="button"- variant="secondary"+ variant={recoveryMode ? "primary" : "secondary"}onClick={() => setShowAddForm(true)}testId="manage-backends-add"startContent={<Plus width={14} height={14} />}>{t(I18nKey.BACKEND$ADD)}</BrandButton>- <BrandButton- type="button"- variant="primary"- onClick={onClose}- testId="manage-backends-done"- >- {t(I18nKey.HOME$DONE)}- </BrandButton>+ {recoveryMode ? null : (+ <BrandButton+ type="button"+ variant="primary"+ onClick={onClose}+ testId="manage-backends-done"+ >+ {t(I18nKey.HOME$DONE)}+ </BrandButton>+ )}</div></div></ModalBackdrop>diff --git a/src/contexts/active-backend-context.tsx b/src/contexts/active-backend-context.tsxindex c9e292ca06..a96c67ac60 100644--- a/src/contexts/active-backend-context.tsx+++ b/src/contexts/active-backend-context.tsx@@ -1,4 +1,5 @@import React from "react";+import { clearCachedAgentServerInfo } from "#/api/agent-server-compatibility";import {getActiveSelection,getRegisteredBackends,@@ -18,6 +19,8 @@ import {type BackendSelection,type ResolvedActiveBackend,} from "#/api/backend-registry/types";+import { QUERY_KEYS } from "#/hooks/query/query-keys";+import { queryClient } from "#/query-client-config";interface ActiveBackendContextValue {backends: Backend[];@@ -52,6 +55,13 @@ export function ActiveBackendProvider({getSnapshot,);+ const retryBootstrapProbe = React.useCallback(() => {+ clearCachedAgentServerInfo();+ void queryClient.invalidateQueries({+ queryKey: QUERY_KEYS.WEB_CLIENT_CONFIG,+ });+ }, []);+const setActive = React.useCallback((backendId: string, orgId?: string | null) => {const prevBackendId = getActiveSelection()?.backendId ?? null;@@ -62,6 +72,7 @@ export function ActiveBackendProvider({const next: BackendSelection = { backendId, orgId: nextOrgId };setActiveSelection(next);+ retryBootstrapProbe();// No blanket `invalidateQueries()` here. Long-lived queries// (`useSettings`, `usePaginatedConversations`,@@ -71,7 +82,7 @@ export function ActiveBackendProvider({// treats a backend/org switch as a brand-new query and fetches// automatically β once, with no duplicate waves.},- [],+ [retryBootstrapProbe],);// @spec BM-001 β Auto-switch to newly connected backend@@ -81,14 +92,16 @@ export function ActiveBackendProvider({const list = [...getRegisteredBackends(), next];setRegisteredBackends(list);setActiveSelection({ backendId: next.id });+ retryBootstrapProbe();return next;},- [],+ [retryBootstrapProbe],);const updateBackend = React.useCallback((id: string, patch: Partial<Omit<Backend, "id">>) => {const prev = getRegisteredBackends().find((b) => b.id === id);+ const activeBeforeUpdate = getActiveSelection()?.backendId ?? null;const list = getRegisteredBackends().map((b) =>b.id === id ? { ...b, ...patch } : b,);@@ -107,20 +120,27 @@ export function ActiveBackendProvider({patch.apiKey !== prev.apiKey;if (hostChanged || apiKeyChanged) {resetBackendHealth(id);+ if (activeBeforeUpdate === id) {+ retryBootstrapProbe();+ }}},- [],+ [retryBootstrapProbe],);- const removeBackend = React.useCallback((id: string) => {- const list = getRegisteredBackends().filter((b) => b.id !== id);- setRegisteredBackends(list);- dropBackendHealth(id);- // If the active selection pointed at this backend, the active- // store falls back to the first remaining local backend (or the- // env-derived default if no locals exist); consumer hooks re-key- // by the new active backend identity and refetch automatically.- }, []);+ const removeBackend = React.useCallback(+ (id: string) => {+ const list = getRegisteredBackends().filter((b) => b.id !== id);+ setRegisteredBackends(list);+ dropBackendHealth(id);+ retryBootstrapProbe();+ // If the active selection pointed at this backend, the active+ // store falls back to the first remaining local backend (or the+ // env-derived default if no locals exist); consumer hooks re-key+ // by the new active backend identity and refetch automatically.+ },+ [retryBootstrapProbe],+ );const value = React.useMemo<ActiveBackendContextValue>(() => ({diff --git a/src/root.tsx b/src/root.tsxindex 6bbb48ff0d..f785454797 100644--- a/src/root.tsx+++ b/src/root.tsx@@ -13,6 +13,7 @@ import React from "react";import { useQueryClient } from "@tanstack/react-query";import { Toaster } from "react-hot-toast";import {+ clearCachedAgentServerInfo,isAgentServerUnavailableError,isAgentServerAuthError,} from "#/api/agent-server-compatibility";@@ -95,14 +96,14 @@ function AgentServerBootstrapLoading() {function MissingAgentServerScreen() {const queryClient = useQueryClient();- // The modal is the no-backend gate. Closing it must re-run the- // /server_info probe once a usable local backend has been registered,- // otherwise the app stays stuck behind a "Done" button that closes a- // modal with nothing rendered behind it (the probe never re-fires on its- // own). Re-fetch only when a backend now exists; otherwise keep the modal.+ // The modal is the no-backend gate. Selecting or adding a reachable+ // backend must re-run the /server_info probe; otherwise the app stays+ // behind the recovery screen because the failed bootstrap query will not+ // re-fire on its own. Re-fetch only when a backend now exists.const handleClose = React.useCallback(() => {if (getEffectiveLocalBackend()) {- queryClient.invalidateQueries({+ clearCachedAgentServerInfo();+ void queryClient.invalidateQueries({queryKey: QUERY_KEYS.WEB_CLIENT_CONFIG,});}@@ -114,7 +115,7 @@ function MissingAgentServerScreen() {className="min-h-screen bg-base"><React.Suspense fallback={null}>- <ManageBackendsModal onClose={handleClose} />+ <ManageBackendsModal onClose={handleClose} recoveryMode /></React.Suspense></main>);