Skip to content

🙌 OpenHands: AI-Driven Development

fix: show environment-switch overlay during backend changes (#178)

Hiep Lef8ad3fa8855f
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index 81ae0630df..0df993ec92 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -10,6 +10,10 @@ import {
useActiveBackendContext,
} from "#/contexts/active-backend-context";
import { BackendSelector } from "#/components/features/backends/backend-selector";
+import {
+ __resetEnvironmentSwitchOverlayForTests,
+ EnvironmentSwitchOverlay,
+} from "#/components/features/backends/environment-switch-overlay";
import {
getCloudOrganizations,
@@ -84,6 +88,7 @@ beforeEach(() => {
afterEach(() => {
window.localStorage.clear();
__resetActiveStoreForTests();
+ __resetEnvironmentSwitchOverlayForTests();
});
describe("BackendSelector", () => {
@@ -208,18 +213,14 @@ describe("BackendSelector", () => {
await openDropdown();
await waitFor(() => {
- expect(
- screen.getByText("ProdPersonal – Personal"),
- ).toBeInTheDocument();
+ expect(screen.getByText("ProdPersonal – Personal")).toBeInTheDocument();
});
expect(screen.getByText("ProdAcme – Acme Inc")).toBeInTheDocument();
// Inaccessible orgs must not appear under either backend.
expect(
screen.queryByText("ProdPersonal – Acme Inc"),
).not.toBeInTheDocument();
- expect(
- screen.queryByText("ProdAcme – Personal"),
- ).not.toBeInTheDocument();
+ expect(screen.queryByText("ProdAcme – Personal")).not.toBeInTheDocument();
expect(screen.queryByText(/Beta Co/)).not.toBeInTheDocument();
});
@@ -389,6 +390,43 @@ describe("BackendSelector", () => {
expect(await screen.findByTestId("home")).toBeInTheDocument();
});
+ it("keeps the environment-switch overlay visible even after the selector unmounts mid-switch", async () => {
+ // Arrange — selector and overlay are rendered in independent trees
+ // so the selector can be torn down without taking the overlay with
+ // it. This mirrors production: ContextMenuContainer's click-outside
+ // handler unmounts UserContextMenu (and BackendSelector) the moment
+ // the dropdown's portaled option list is clicked, so the trigger
+ // must not depend on BackendSelector staying mounted.
+ const selectorRender = renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "Acme Local",
+ host: "http://localhost:9000",
+ apiKey: "k",
+ kind: "local",
+ });
+ }}
+ >
+ <BackendSelector />
+ </TestSeed>,
+ );
+ render(<EnvironmentSwitchOverlay />);
+
+ // Act — select a different backend, then immediately unmount the
+ // selector (the click itself would do this in production via the
+ // outside-click handler).
+ const user = await openDropdown();
+ await user.click(screen.getByText("Acme Local"));
+ selectorRender.unmount();
+
+ // Assert — the overlay is still in the DOM with the chosen target
+ expect(screen.getByTestId("environment-switch-overlay")).toHaveAttribute(
+ "data-target",
+ "Acme Local",
+ );
+ });
+
it("does not redirect when switching backends from a non-conversation route", async () => {
function SettingsRoute() {
return (
diff --git a/__tests__/components/backends/environment-switch-overlay.test.tsx b/__tests__/components/backends/environment-switch-overlay.test.tsx
new file mode 100644
index 0000000000..a07fef6bc9
--- /dev/null
+++ b/__tests__/components/backends/environment-switch-overlay.test.tsx
@@ -0,0 +1,46 @@
+import React from "react";
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetEnvironmentSwitchOverlayForTests,
+ ENVIRONMENT_SWITCH_DURATION_MS,
+ EnvironmentSwitchOverlay,
+ triggerEnvironmentSwitch,
+} from "#/components/features/backends/environment-switch-overlay";
+
+describe("EnvironmentSwitchOverlay", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ __resetEnvironmentSwitchOverlayForTests();
+ vi.useRealTimers();
+ });
+
+ it("renders the overlay with the requested target on trigger and tears it down after the configured duration", () => {
+ // Arrange
+ render(<EnvironmentSwitchOverlay />);
+
+ // Act — request a switch to a specific environment
+ act(() => {
+ triggerEnvironmentSwitch("Acme Cloud");
+ });
+
+ // Assert — overlay is mounted and carries the requested target
+ expect(screen.getByTestId("environment-switch-overlay")).toHaveAttribute(
+ "data-target",
+ "Acme Cloud",
+ );
+
+ // Act — wait out the auto-hide window
+ act(() => {
+ vi.advanceTimersByTime(ENVIRONMENT_SWITCH_DURATION_MS);
+ });
+
+ // Assert — overlay tears itself down without further user action
+ expect(
+ screen.queryByTestId("environment-switch-overlay"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index 6c5e594675..d159f012e6 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -9,6 +9,10 @@ import { useCloudCurrentUserId } from "#/hooks/query/use-cloud-current-user-id";
import { useSwitchCloudOrganization } from "#/hooks/mutation/use-switch-cloud-organization";
import { I18nKey } from "#/i18n/declaration";
import type { Backend } from "#/api/backend-registry/types";
+import {
+ ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS,
+ triggerEnvironmentSwitch,
+} from "#/components/features/backends/environment-switch-overlay";
const VALUE_SEPARATOR = "::";
@@ -145,6 +149,20 @@ export function BackendSelector() {
const { backendId, orgId } = parseOptionValue(item.value);
const target = backends.find((b) => b.id === backendId);
+ // Show the environment-switch overlay immediately so the user
+ // gets feedback before any /switch network call. The overlay
+ // auto-dismisses on its own 980ms timer regardless of whether
+ // the switch succeeds or fails.
+ triggerEnvironmentSwitch(item.label);
+
+ // Hold the active swap for ~400ms — placing it in the middle
+ // of the content-fade-to-black window so React Query refetches
+ // happen while the layout is invisible behind the overlay,
+ // rather than thrashing visibly before the fade.
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS);
+ });
+
// Cloud + org pick: fire `/switch` FIRST against the explicit
// target backend, then update the active selection after it
// resolves. This ensures the SaaS-side `current_org_id` is
diff --git a/src/components/features/backends/environment-switch-overlay.tsx b/src/components/features/backends/environment-switch-overlay.tsx
new file mode 100644
index 0000000000..ff4daaff4d
--- /dev/null
+++ b/src/components/features/backends/environment-switch-overlay.tsx
@@ -0,0 +1,216 @@
+import React from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+
+export const ENVIRONMENT_SWITCH_DURATION_MS = 980;
+export const ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS = 400;
+
+// Module-level store. The overlay state must survive the unmount of the
+// component that triggers a switch — the user-context menu remounts
+// (`menuResetCount` key flip in user-actions.tsx) the moment the dropdown's
+// portaled option list is clicked, because that click registers as outside
+// the menu's `useClickOutsideElement` ref. If state lived inside
+// BackendSelector, the trigger would fire and immediately get torn down
+// before React paints the overlay.
+interface EnvironmentSwitchSnapshot {
+ visible: boolean;
+ target: string;
+}
+
+let snapshot: EnvironmentSwitchSnapshot = { visible: false, target: "" };
+const listeners = new Set<() => void>();
+let hideTimeoutId: ReturnType<typeof setTimeout> | null = null;
+
+function setSnapshot(next: EnvironmentSwitchSnapshot) {
+ snapshot = next;
+ if (typeof document !== "undefined") {
+ if (next.visible) {
+ document.body.setAttribute("data-environment-switching", "true");
+ } else {
+ document.body.removeAttribute("data-environment-switching");
+ }
+ }
+ listeners.forEach((listener) => listener());
+}
+
+export function triggerEnvironmentSwitch(target: string) {
+ setSnapshot({ visible: true, target });
+ if (hideTimeoutId) clearTimeout(hideTimeoutId);
+ hideTimeoutId = setTimeout(() => {
+ setSnapshot({ visible: false, target: "" });
+ hideTimeoutId = null;
+ }, ENVIRONMENT_SWITCH_DURATION_MS);
+}
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+function getSnapshot() {
+ return snapshot;
+}
+
+/** Test-only: clear the pending hide timer and reset the snapshot. */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+export function __resetEnvironmentSwitchOverlayForTests() {
+ if (hideTimeoutId) {
+ clearTimeout(hideTimeoutId);
+ hideTimeoutId = null;
+ }
+ setSnapshot({ visible: false, target: "" });
+}
+
+function EnvironmentSwitchIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ viewBox="0 0 74.17 22"
+ xmlns="http://www.w3.org/2000/svg"
+ className={className}
+ aria-hidden
+ >
+ <g>
+ <rect
+ x="1"
+ y="1"
+ width="20"
+ height="8"
+ rx="2"
+ ry="2"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <rect
+ x="1"
+ y="13"
+ width="20"
+ height="8"
+ rx="2"
+ ry="2"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <line
+ x1="5"
+ y1="5"
+ x2="5.01"
+ y2="5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ <line
+ x1="5"
+ y1="17"
+ x2="5.01"
+ y2="17"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ </g>
+ <g>
+ <rect
+ x="53.17"
+ y="1"
+ width="20"
+ height="8"
+ rx="2"
+ ry="2"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <rect
+ x="53.17"
+ y="13"
+ width="20"
+ height="8"
+ rx="2"
+ ry="2"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <line
+ x1="57.17"
+ y1="5"
+ x2="57.18"
+ y2="5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ <line
+ x1="57.17"
+ y1="17"
+ x2="57.18"
+ y2="17"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ </g>
+ <g>
+ <path
+ d="M43.09,7l4,4-4,4"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M27.09,11h20"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M31.09,7l-4,4,4,4"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ </svg>
+ );
+}
+
+export function EnvironmentSwitchOverlay() {
+ const { t } = useTranslation("openhands");
+ const { visible, target } = React.useSyncExternalStore(
+ subscribe,
+ getSnapshot,
+ getSnapshot,
+ );
+
+ if (!visible || typeof document === "undefined") return null;
+
+ return createPortal(
+ <div
+ data-testid="environment-switch-overlay"
+ data-target={target}
+ className="environment-switch-overlay pointer-events-none fixed inset-0 z-[2147483646] flex items-center justify-center"
+ aria-live="polite"
+ aria-atomic="true"
+ >
+ <div className="pointer-events-none flex min-w-[280px] max-w-[420px] flex-col items-center gap-2 rounded-xl border border-border bg-card px-5 py-4 text-foreground shadow-2xl">
+ <EnvironmentSwitchIcon className="mb-2 h-6 w-20 shrink-0 text-foreground" />
+ <p className="text-center text-sm font-medium">
+ {t(I18nKey.BACKEND$SWITCHING_TO, { environment: target })}
+ </p>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index f38d993208..df114d4ffb 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -22473,6 +22473,23 @@
"uk": "Особистий робочий простір",
"ca": "Espai de treball personal"
},
+ "BACKEND$SWITCHING_TO": {
+ "en": "Switching to {{environment}}",
+ "ja": "{{environment}} に切り替えています",
+ "zh-CN": "正在切换到 {{environment}}",
+ "zh-TW": "正在切換到 {{environment}}",
+ "ko-KR": "{{environment}}(으)로 전환 중",
+ "no": "Bytter til {{environment}}",
+ "it": "Passaggio a {{environment}}",
+ "pt": "Mudando para {{environment}}",
+ "es": "Cambiando a {{environment}}",
+ "ar": "التبديل إلى {{environment}}",
+ "fr": "Passage à {{environment}}",
+ "tr": "{{environment}} ortamına geçiliyor",
+ "de": "Wechsel zu {{environment}}",
+ "uk": "Перемикання на {{environment}}",
+ "ca": "Canviant a {{environment}}"
+ },
"TELEMETRY$CONSENT_TITLE": {
"en": "Help improve OpenHands",
"ja": "OpenHandsの改善にご協力ください",
diff --git a/src/index.css b/src/index.css
index f67c24ec6a..1aea4ef87e 100644
--- a/src/index.css
+++ b/src/index.css
@@ -27,6 +27,7 @@
body {
margin: 0;
+ background-color: var(--oh-color-base);
font-family:
-apple-system, "SF Pro", BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
@@ -75,3 +76,45 @@ code {
scroll-behavior: smooth;
scroll-timeline: 100ms;
}
+
+@keyframes environment-switch-content-refresh {
+ 0% {
+ opacity: 1;
+ }
+ 30% {
+ opacity: 0;
+ }
+ 70% {
+ opacity: 0;
+ }
+ 100% {
+ opacity: 1;
+ }
+}
+
+:host[data-environment-switching="true"] [data-testid="root-layout"] {
+ animation: environment-switch-content-refresh 980ms ease-in-out forwards;
+}
+
+@keyframes environment-switch-overlay-fade {
+ 0% {
+ opacity: 0;
+ transform: scale(0.98);
+ }
+ 15% {
+ opacity: 1;
+ transform: scale(1);
+ }
+ 85% {
+ opacity: 1;
+ transform: scale(1);
+ }
+ 100% {
+ opacity: 0;
+ transform: scale(0.98);
+ }
+}
+
+.environment-switch-overlay > div {
+ animation: environment-switch-overlay-fade 980ms ease-in-out forwards;
+}
diff --git a/src/routes/root-layout.tsx b/src/routes/root-layout.tsx
index c31afd0dbf..1b98de4431 100644
--- a/src/routes/root-layout.tsx
+++ b/src/routes/root-layout.tsx
@@ -10,6 +10,7 @@ import { I18nKey } from "#/i18n/declaration";
import i18n from "#/i18n";
import { useConfig } from "#/hooks/query/use-config";
import { Sidebar } from "#/components/features/sidebar/sidebar";
+import { EnvironmentSwitchOverlay } from "#/components/features/backends/environment-switch-overlay";
import { AnalyticsConsentFormModal } from "#/components/features/analytics/analytics-consent-form-modal";
import { useSettings } from "#/hooks/query/use-settings";
import { useMigrateUserConsent } from "#/hooks/use-migrate-user-consent";
@@ -131,6 +132,7 @@ export default function MainApp() {
/>
)}
</div>
+ <EnvironmentSwitchOverlay />
</ReactRouterNavigationProvider>
);
}