Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: hide Cloud reconnect controls in cookie-auth (OHE-hosted) Canvas (#17044)

Hiep Leca4024e3ae79
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index e7a7d931e2..e46598f608 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -630,6 +630,52 @@ describe("BackendSelector", () => {
);
});
+ it("hides the backend footer actions when the locked backend uses cookie auth", async () => {
+ // Arrange: an OHE-hosted Canvas β€” nothing to add, manage, or reconnect.
+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");
+ vi.mocked(getCloudOrganizations).mockResolvedValue({
+ items: [{ id: "org-acme", name: "Acme Inc" }],
+ currentOrgId: "org-acme",
+ });
+
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ });
+ }}
+ >
+ <BackendSelector />
+ </TestSeed>,
+ );
+ await waitFor(() => {
+ const wrapper = screen.getByTestId("backend-selector");
+ const input = wrapper.querySelector("input") as HTMLInputElement;
+ expect(input.value).toBe("OpenHands Cloud – Acme Inc");
+ });
+
+ // Act
+ await openDropdown();
+
+ // Assert: the org rows render, but no footer actions do.
+ await waitFor(() => {
+ expect(
+ screen.getByText("OpenHands Cloud – Acme Inc"),
+ ).toBeInTheDocument();
+ });
+ expect(
+ screen.queryByTestId("manage-backends-menu-item"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("add-backend-menu-item"),
+ ).not.toBeInTheDocument();
+ });
+
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.tsx
index e22ae2005c..a6beea6e90 100644
--- a/__tests__/components/backends/manage-backends-modal.test.tsx
+++ b/__tests__/components/backends/manage-backends-modal.test.tsx
@@ -688,6 +688,77 @@ describe("ManageBackendsModal", () => {
).toHaveTextContent("Authorization request was denied.");
expect(screen.getByTestId("manage-backends-modal")).toBeInTheDocument();
});
+
+ it("hides the Cloud reconnect controls when the locked backend uses cookie auth", async () => {
+ // Arrange: an OHE-hosted Canvas β€” locked to Cloud, but the backend is
+ // authenticated by the main-app session cookie, not a device-flow key.
+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");
+
+ // Act
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ });
+ }}
+ >
+ <ManageBackendsModal onClose={vi.fn()} recoveryMode />
+ </TestSeed>,
+ );
+
+ // Assert
+ expect(
+ await screen.findByRole("heading", { name: "BACKEND$MANAGE_TITLE" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("manage-backends-reconnect-cloud-login-button"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByTestId("manage-backends-add")).not.toBeInTheDocument();
+ });
+
+ it("does not offer the device-flow login for a logged-out cookie-auth backend", async () => {
+ // Arrange: the main-app session cookie has expired, so the Cloud probe
+ // reports the backend as logged out.
+ vi.stubEnv("VITE_LOCK_TO_CLOUD", "https://app.all-hands.dev");
+ vi.mocked(getCloudOrganizations).mockRejectedValue(
+ Object.assign(new Error("Unauthorized"), {
+ isAxiosError: true,
+ response: { status: 401 },
+ }),
+ );
+
+ // Act
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "OpenHands Cloud",
+ host: "https://app.all-hands.dev",
+ apiKey: "",
+ kind: "cloud",
+ authMode: "cookie",
+ });
+ }}
+ >
+ <ManageBackendsModal onClose={vi.fn()} recoveryMode />
+ </TestSeed>,
+ );
+
+ // Assert
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("manage-backends-status-OpenHands Cloud"),
+ ).toHaveTextContent("BACKEND$LOGGED_OUT"),
+ );
+ expect(
+ screen.queryByTestId(/^manage-backends-login-.*-login-button$/),
+ ).not.toBeInTheDocument();
+ });
});
function renderInQueryClient(ui: React.ReactElement) {
diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsx
index 9996390a79..aaa6f8fef9 100644
--- a/__tests__/root.test.tsx
+++ b/__tests__/root.test.tsx
@@ -6,6 +6,13 @@ import { http, HttpResponse } from "msw";
import App, { links } from "#/root";
import { server } from "#/mocks/node";
import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import { LOCKED_CLOUD_BACKEND_ID } from "#/api/backend-registry/default-backend";
+import { __resetHealthStoreForTests } from "#/api/backend-registry/health-store";
+import {
+ BACKEND_HEALTH_STORAGE_KEY,
+ MAX_CONSECUTIVE_FAILURES,
+} from "#/api/backend-registry/health-storage";
+import { CLOUD_BACKEND_LOGGED_OUT_ERROR } from "#/hooks/query/use-backends-health";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import { ONBOARDING_COMPLETED_STORAGE_KEY } from "#/components/features/onboarding/use-onboarding-completion";
@@ -102,9 +109,39 @@ const renderApp = (initialEntries: string[] = ["/"]) =>
),
});
+const COOKIE_DEPLOYMENT_ORIGIN = "https://pr-254.staging.openhands.dev";
+
+/**
+ * Simulate an OHE-hosted Canvas: served from the locked Cloud host itself, so
+ * the single locked backend authenticates with the main-app session cookie.
+ * Returns the `window.location.assign` spy that observes login redirects.
+ */
+function mockLockedCookieDeployment() {
+ const assign = vi.fn();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: {
+ ...ORIGINAL_LOCATION,
+ origin: COOKIE_DEPLOYMENT_ORIGIN,
+ hostname: "pr-254.staging.openhands.dev",
+ pathname: "/canvas",
+ search: "",
+ hash: "",
+ assign,
+ },
+ });
+ vi.stubEnv("VITE_LOCK_TO_CLOUD", COOKIE_DEPLOYMENT_ORIGIN);
+ vi.stubEnv("VITE_SESSION_API_KEY", "");
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_SESSION_API_KEY__;
+ __resetActiveStoreForTests();
+ return assign;
+}
+
describe("App root agent-server availability guard", () => {
beforeEach(() => {
window.localStorage.clear();
+ __resetHealthStoreForTests();
vi.unstubAllEnvs();
delete (window as unknown as Record<string, unknown>)
.__AGENT_CANVAS_AUTH_REQUIRED__;
@@ -728,6 +765,72 @@ describe("App root agent-server availability guard", () => {
expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
});
+ it("redirects to main app login when the cookie session expires after the Canvas loaded", async () => {
+ // Arrange: the session is valid at load, then expires β€” the Cloud probe
+ // starts returning 401 and the next main-app auth check confirms it.
+ const assign = mockLockedCookieDeployment();
+ let sessionExpired = false;
+ server.use(
+ http.post("*/api/authenticate", () =>
+ sessionExpired
+ ? HttpResponse.json({ error: "unauthenticated" }, { status: 401 })
+ : HttpResponse.json({ ok: true }),
+ ),
+ http.get(`${COOKIE_DEPLOYMENT_ORIGIN}/api/organizations`, () => {
+ sessionExpired = true;
+ return HttpResponse.json(
+ { detail: "Not authenticated" },
+ { status: 401 },
+ );
+ }),
+ );
+
+ // Act
+ renderApp(["/"]);
+
+ // Assert: main-app login, not the device-flow recovery modal.
+ await waitFor(() => {
+ expect(assign).toHaveBeenCalledWith("/login?returnTo=%2Fcanvas");
+ });
+ expect(
+ screen.queryByTestId("manage-backends-modal"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
+ });
+
+ it("keeps a valid cookie session on the app when a stale logged-out health entry is persisted", async () => {
+ // Arrange: a previous visit left the locked backend persisted as disabled
+ // and "Logged out", but the user has since logged back in on the main app.
+ const assign = mockLockedCookieDeployment();
+ window.localStorage.setItem(
+ BACKEND_HEALTH_STORAGE_KEY,
+ JSON.stringify({
+ [LOCKED_CLOUD_BACKEND_ID]: {
+ consecutiveFailures: MAX_CONSECUTIVE_FAILURES,
+ lastError: CLOUD_BACKEND_LOGGED_OUT_ERROR,
+ lastFailureAt: 1,
+ disabled: true,
+ },
+ }),
+ );
+ __resetHealthStoreForTests();
+ server.use(
+ http.get(`${COOKIE_DEPLOYMENT_ORIGIN}/api/organizations`, () =>
+ HttpResponse.json({ items: [], current_org_id: null }),
+ ),
+ );
+
+ // Act
+ renderApp(["/"]);
+
+ // Assert: the stale health verdict must not bounce a valid session to
+ // /login (which would loop back via returnTo); the app renders instead.
+ await waitFor(() => {
+ expect(screen.getByTestId("app-outlet")).toBeInTheDocument();
+ });
+ expect(assign).not.toHaveBeenCalled();
+ });
+
it("hides first-run onboarding immediately after Cloud login completes in locked-to-Cloud mode (no flicker)", async () => {
// Regression for hieptl's flicker report on PR #1389: after Cloud
// login succeeds in locked-to-Cloud mode, the onboarding modal's
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index 1f71fec098..350341530b 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -254,6 +254,10 @@ export function BackendSelector({
}, [onOpenManageBackends, onSelectOption]);
const isLockedToCloud = getLockedCloudHost() !== null;
+ // A cookie-auth (OHE-hosted) Canvas has nothing to add, manage, or
+ // reconnect β€” its single locked backend is owned by the main-app session.
+ const hideBackendFooter =
+ isLockedToCloud && active.backend.authMode === "cookie";
const preventDropdownMenuClose = React.useCallback(
(event: React.SyntheticEvent<HTMLButtonElement>) => {
@@ -295,7 +299,7 @@ export function BackendSelector({
[openManageBackendsModal, preventDropdownMenuClose],
);
- const addBackendFooter = (
+ const addBackendFooter = hideBackendFooter ? undefined : (
<div className={dropdownMenuListClassName}>
{isLockedToCloud ? null : (
<button
diff --git a/src/components/features/backends/manage-backends-modal.tsx b/src/components/features/backends/manage-backends-modal.tsx
index 91a9703320..2a70ed006d 100644
--- a/src/components/features/backends/manage-backends-modal.tsx
+++ b/src/components/features/backends/manage-backends-modal.tsx
@@ -75,13 +75,19 @@ export function ManageBackendsModal({
const personalWorkspaceLabel = t(I18nKey.BACKEND$PERSONAL_WORKSPACE);
const lockedCloudHost = getLockedCloudHost();
const isLockedToCloud = lockedCloudHost !== null;
+ // Cookie-auth (OHE-hosted) backends have no API key to refresh β€” re-auth is
+ // the main-app login, so the device-flow reconnect controls don't apply.
+ const isCookieAuthBackend = active.backend.authMode === "cookie";
const lockedCloudBackend =
- isLockedToCloud && active.backend.kind === "cloud" ? active.backend : null;
+ isLockedToCloud && !isCookieAuthBackend && 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 modalTitle =
+ isLockedToCloud && !isCookieAuthBackend
+ ? 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>(
@@ -177,7 +183,11 @@ export function ManageBackendsModal({
name: backend.name,
})
}
- onLogin={(apiKey) => handleCloudLogin(backend, apiKey)}
+ onLogin={
+ backend.authMode === "cookie"
+ ? undefined
+ : (apiKey) => handleCloudLogin(backend, apiKey)
+ }
/>
))}
</ul>
diff --git a/src/root.tsx b/src/root.tsx
index 03f68f1739..7d3cecdd3a 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -242,6 +242,7 @@ export default function App() {
const hasRegisteredKey = Boolean(getEffectiveLocalBackend()?.apiKey);
const authMissing = bakedKeyMissing && !hasRegisteredKey;
const { active } = useActiveBackendContext();
+ const queryClient = useQueryClient();
// In locked-to-Cloud mode the only valid backend is a Cloud backend whose
// host matches the configured locked Cloud host. A missing backend, a stale
// Local backend (e.g. one persisted from a previous non-locked session), or
@@ -326,6 +327,19 @@ export default function App() {
active.backend.kind === "cloud" &&
activeCloudHealth?.isConnected === false &&
isCloudBackendLoggedOutHealthError(activeCloudHealth.lastError);
+ // Cookie-auth (OHE-hosted) deployments: a logged-out Cloud backend means the
+ // main-app session likely expired. Re-run the main-app auth probe and let its
+ // verdict drive the /login redirect above; never redirect off the health
+ // verdict itself β€” it can be a stale persisted entry that the recovery
+ // modal's one-shot re-probe clears.
+ const cookieSessionMaybeExpired =
+ shouldCheckMainAppAuth && activeCloudLoggedOut;
+ React.useEffect(() => {
+ if (!cookieSessionMaybeExpired) return;
+ void queryClient.invalidateQueries({
+ queryKey: QUERY_KEYS.MAIN_APP_COOKIE_AUTH,
+ });
+ }, [cookieSessionMaybeExpired, queryClient]);
// A cloud backend the health probe has given up on (disabled after repeated
// CORS/network failures) is unreachable from this origin β€” most commonly a
// self-hosted OHE that doesn't allow this frontend's origin. Route to the
@@ -345,7 +359,11 @@ export default function App() {
);
}
- if (waitingForMainAppAuth || redirectingToMainAppLogin) {
+ if (
+ waitingForMainAppAuth ||
+ redirectingToMainAppLogin ||
+ (cookieSessionMaybeExpired && mainAppAuth.isFetching)
+ ) {
return <AgentServerBootstrapLoading />;
}