🙌 OpenHands: AI-Driven Development
feat(backends): explain a suspended workspace and offer a switch (#17988)
Hiep Lef1aed4e3eb0a
diff --git a/__tests__/api/cloud/proxy.test.ts b/__tests__/api/cloud/proxy.test.tsindex 8a3cb09615..d4792aadcc 100644--- a/__tests__/api/cloud/proxy.test.ts+++ b/__tests__/api/cloud/proxy.test.ts@@ -5,6 +5,7 @@ import {setRegisteredBackends,} from "#/api/backend-registry/active-store";import { callCloudProxy } from "#/api/cloud/proxy";+import { getOrganizationSuspension } from "#/api/cloud/organization-suspension-store";import type { Backend } from "#/api/backend-registry/types";const cloudPersonal: Backend = {@@ -270,3 +271,56 @@ describe("callCloudProxy hostOverride routing", () => {});});});++describe("callCloudProxy organization suspension", () => {+ it("does not flag the organization for a 403 that is not a suspension", async () => {+ // Arrange+ setRegisteredBackends([cookieCloud]);+ setActiveSelection({ backendId: cookieCloud.id, orgId: "org-forbidden" });+ fetchMock.mockResolvedValue(+ mockJsonResponse({ detail: "Missing required permission: x" }, 403),+ );++ // Act+ await expect(+ callCloudProxy({+ backend: cookieCloud,+ method: "GET",+ path: "/api/v1/settings",+ }),+ ).rejects.toMatchObject({ status: 403 });++ // Assert+ expect(getOrganizationSuspension(cookieCloud.id, "org-forbidden")).toBe(+ null,+ );+ });++ it("flags the organization the request was sent for when the selection changes before it fails", async () => {+ // Arrange+ setRegisteredBackends([cookieCloud]);+ setActiveSelection({ backendId: cookieCloud.id, orgId: "org-suspended" });+ let respond: (response: Response) => void = () => {};+ fetchMock.mockReturnValue(+ new Promise<Response>((resolve) => {+ respond = resolve;+ }),+ );+ const request = callCloudProxy({+ backend: cookieCloud,+ method: "GET",+ path: "/api/v1/settings",+ });+ setActiveSelection({ backendId: cookieCloud.id, orgId: "org-next" });++ // Act+ respond(mockJsonResponse({ detail: "Organization is suspended" }, 403));+ await expect(request).rejects.toMatchObject({ status: 403 });++ // Assert+ expect(getOrganizationSuspension(cookieCloud.id, "org-suspended")).toBe(+ "organization",+ );+ expect(getOrganizationSuspension(cookieCloud.id, "org-next")).toBe(null);+ });+});diff --git a/__tests__/components/backends/cloud-organization-startup.test.tsx b/__tests__/components/backends/cloud-organization-startup.test.tsxindex 916d9d5b01..cf98f99f70 100644--- a/__tests__/components/backends/cloud-organization-startup.test.tsx+++ b/__tests__/components/backends/cloud-organization-startup.test.tsx@@ -10,7 +10,7 @@ import {screen,waitFor,} from "@testing-library/react";-import { QueryClient } from "@tanstack/react-query";+import { QueryClient, useQuery } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { AgentServerUIProviders } from "#/components/providers/agent-server-ui-providers";import {@@ -25,6 +25,8 @@ import {getCurrentCloudApiKey,} from "#/api/cloud/organization-service.api";import SettingsService from "#/api/settings-service/settings-service.api";+import { fetchCloudSettings } from "#/api/cloud/settings-service.api";+import { useActiveBackendContext } from "#/contexts/active-backend-context";import { DEFAULT_SETTINGS } from "#/services/settings";import { useSettings } from "#/hooks/query/use-settings";@@ -64,6 +66,16 @@ function SettingsConsumer() {) : null;}+function CloudSettingsConsumer() {+ const { active } = useActiveBackendContext();+ const settings = useQuery({+ queryKey: ["cloud-settings", active.orgId],+ queryFn: fetchCloudSettings,+ retry: false,+ });+ return settings.isSuccess ? <span>Workspace ready</span> : null;+}+function OrganizationConsumer() {const organizations = useAllCloudOrganizations();return <span>{organizations.cloud.isFetching ? "Fetching" : "Settled"}</span>;@@ -362,4 +374,96 @@ describe("Cloud organization startup", () => {expect(getActiveSelection()?.orgId).toBe("current-org"),);});++ describe("suspended organization", () => {+ const originalFetch = global.fetch;++ // The cloud refuses org-scoped calls for `refusedOrgId` with `detail`.+ function arrangeRefusedOrg(refusedOrgId: string, detail: string) {+ setActiveSelection({ backendId: cloud.id, orgId: refusedOrgId });+ vi.mocked(getCloudOrganizations).mockResolvedValue({+ items: [+ { id: "personal-org", name: "Personal", is_personal: true },+ { id: refusedOrgId, name: "Acme" },+ { id: "beta-org", name: "Beta" },+ ],+ currentOrgId: refusedOrgId,+ });+ global.fetch = vi.fn(+ async (_url: RequestInfo | URL, init?: RequestInit) => {+ const orgId = (init?.headers as Record<string, string>)["X-Org-Id"];+ return orgId === refusedOrgId+ ? new Response(JSON.stringify({ detail }), {+ status: 403,+ headers: { "content-type": "application/json" },+ })+ : new Response("{}", {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ },+ ) as typeof fetch;+ }++ function renderCloudSettingsConsumer() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, retryDelay: 0 } },+ });+ render(+ <AgentServerUIProviders queryClient={client} resolveCloudOrganization>+ <CloudSettingsConsumer />+ </AgentServerUIProviders>,+ );+ }++ afterEach(() => {+ global.fetch = originalFetch;+ });++ it("replaces the app with an explanation and the user's other workspaces", async () => {+ // Arrange+ arrangeRefusedOrg("suspended-org", "Organization is suspended");++ // Act+ renderCloudSettingsConsumer();++ // Assert+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "BACKEND$ORGANIZATION_SUSPENDED",+ );+ expect(screen.queryByText("Workspace ready")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Beta" })).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Acme" }),+ ).not.toBeInTheDocument();+ });++ it("explains a suspended membership", async () => {+ // Arrange+ arrangeRefusedOrg("membership-org", "User membership is suspended");++ // Act+ renderCloudSettingsConsumer();++ // Assert+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "BACKEND$MEMBERSHIP_SUSPENDED",+ );+ });++ it("restores the app after the user switches to another workspace", async () => {+ // Arrange+ arrangeRefusedOrg("switched-away-org", "Organization is suspended");+ renderCloudSettingsConsumer();+ const betaButton = await screen.findByRole("button", { name: "Beta" });++ // Act+ fireEvent.click(betaButton);++ // Assert+ expect(await screen.findByText("Workspace ready")).toBeInTheDocument();+ expect(getActiveSelection()?.orgId).toBe("beta-org");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });+ });});diff --git a/src/api/cloud/client.ts b/src/api/cloud/client.tsindex 125633ed71..db7b5e043e 100644--- a/src/api/cloud/client.ts+++ b/src/api/cloud/client.ts@@ -25,7 +25,7 @@ function requireCloudBackend(backend?: Backend): Backend {* backend's orgId across an unrelated API key, which the cloud backend* rejects when api_key_org_id and X-Org-Id disagree.*/-function activeOrgForBackend(backend: Backend): string | null {+export function activeOrgForBackend(backend: Backend): string | null {const active = getActiveBackend();return active.backend.id === backend.id ? active.orgId : null;}diff --git a/src/api/cloud/organization-suspension-store.ts b/src/api/cloud/organization-suspension-store.tsnew file mode 100644index 0000000000..38b552f307--- /dev/null+++ b/src/api/cloud/organization-suspension-store.ts@@ -0,0 +1,59 @@+import { HttpError } from "@openhands/typescript-client";++export type OrganizationSuspension = "organization" | "membership";++type Listener = () => void;++/**+ * The cloud backend's exact `detail` for a request made in a suspended+ * organization or with a suspended membership.+ */+const SUSPENSION_DETAILS: Record<string, OrganizationSuspension> = {+ "Organization is suspended": "organization",+ "User membership is suspended": "membership",+};++let suspensions: Record<string, OrganizationSuspension> = {};+const listeners = new Set<Listener>();++function suspensionKey(backendId: string, orgId: string): string {+ return `${backendId}:${orgId}`;+}++/**+ * Remember that the cloud backend refused `orgId` because it, or the user's+ * membership in it, is suspended. Any other error is ignored.+ */+export function recordOrganizationSuspension(+ backendId: string,+ orgId: string | null,+ error: unknown,+): void {+ if (!orgId || !(error instanceof HttpError) || error.status !== 403) return;+ const detail = (error.response as { detail?: unknown } | undefined)?.detail;+ const suspension =+ typeof detail === "string" ? SUSPENSION_DETAILS[detail] : undefined;+ if (!suspension) return;++ const key = suspensionKey(backendId, orgId);+ if (suspensions[key] === suspension) return;+ suspensions = { ...suspensions, [key]: suspension };+ listeners.forEach((listener) => listener());+}++export function getOrganizationSuspension(+ backendId: string,+ orgId: string | null,+): OrganizationSuspension | null {+ if (!orgId) return null;+ return suspensions[suspensionKey(backendId, orgId)] ?? null;+}++export function subscribeOrganizationSuspension(+ listener: Listener,+): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.tsindex 27cb6c9c6b..cc4c0591af 100644--- a/src/api/cloud/proxy.ts+++ b/src/api/cloud/proxy.ts@@ -1,6 +1,11 @@import type { CloudRequestOptions } from "@openhands/typescript-client/clients";import type { Backend } from "../backend-registry/types";-import { createCloudClientForRuntime, createCloudClient } from "./client";+import {+ activeOrgForBackend,+ createCloudClientForRuntime,+ createCloudClient,+} from "./client";+import { recordOrganizationSuspension } from "./organization-suspension-store";export interface CloudProxyRequest {backend: Backend;@@ -21,19 +26,27 @@ export async function callCloudProxy<TResponse = unknown>(const client = req.hostOverride? createCloudClientForRuntime(req.backend): createCloudClient(req.backend);+ // The org this request is scoped to, read when the client is built so a+ // later org switch can't be blamed for this response.+ const orgId = activeOrgForBackend(req.backend);- return client.request<TResponse>({- method: req.method,- path: req.path,- body: req.body,- headers: req.headers,- timeoutSeconds: req.timeoutSeconds,- hostOverride: req.hostOverride,- authMode:- req.authMode === undefined || req.authMode === "bearer"- ? "bearer"- : req.authMode,- sessionApiKey: req.sessionApiKey,- responseType: req.responseType,- });+ try {+ return await client.request<TResponse>({+ method: req.method,+ path: req.path,+ body: req.body,+ headers: req.headers,+ timeoutSeconds: req.timeoutSeconds,+ hostOverride: req.hostOverride,+ authMode:+ req.authMode === undefined || req.authMode === "bearer"+ ? "bearer"+ : req.authMode,+ sessionApiKey: req.sessionApiKey,+ responseType: req.responseType,+ });+ } catch (error) {+ recordOrganizationSuspension(req.backend.id, orgId, error);+ throw error;+ }}diff --git a/src/components/features/backends/cloud-organization-boundary.tsx b/src/components/features/backends/cloud-organization-boundary.tsxindex 02404f2229..24527cb061 100644--- a/src/components/features/backends/cloud-organization-boundary.tsx+++ b/src/components/features/backends/cloud-organization-boundary.tsx@@ -2,6 +2,11 @@ import React from "react";import { useTranslation } from "react-i18next";import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useAllCloudOrganizations } from "#/hooks/query/use-cloud-organizations";+import {+ getOrganizationSuspension,+ subscribeOrganizationSuspension,+ type OrganizationSuspension,+} from "#/api/cloud/organization-suspension-store";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { BrandButton } from "#/components/features/settings/brand-button";import { I18nKey } from "#/i18n/declaration";@@ -17,6 +22,10 @@ export function CloudOrganizationBoundary({const isCloud = active.backend.kind === "cloud";const hasValidSelection =entry?.hasData && entry.orgs.some((org) => org.id === active.orgId);+ const suspension = React.useSyncExternalStore(+ subscribeOrganizationSuspension,+ () => getOrganizationSuspension(active.backend.id, active.orgId),+ );// Resolve membership before mounting consumers that send org-scoped requests.React.useEffect(() => {@@ -30,6 +39,14 @@ export function CloudOrganizationBoundary({}}, [active, entry, hasValidSelection, isCloud, setActive]);+ // The cloud refused the selected org; replace the app until the user+ // switches, so org-scoped calls stop failing behind it.+ if (isCloud && suspension) {+ return (+ <SuspendedOrganizationScreen entry={entry} suspension={suspension} />+ );+ }+const canUseSavedSelection = active.orgId && entry?.isError && !entry.hasData;if (!isCloud ||@@ -92,3 +109,46 @@ function CloudOrganizationRecovery({</div>);}++function SuspendedOrganizationScreen({+ entry,+ suspension,+}: {+ entry: ReturnType<typeof useAllCloudOrganizations>[string] | undefined;+ suspension: OrganizationSuspension;+}) {+ const { t } = useTranslation("openhands");+ const { active, setActive } = useActiveBackendContext();+ const orgs = entry?.orgs ?? [];+ const orgLabel = (org: (typeof orgs)[number]) =>+ org.is_personal === true ? t(I18nKey.BACKEND$PERSONAL_WORKSPACE) : org.name;+ const suspendedOrg = orgs.find((org) => org.id === active.orgId);+ const otherOrgs = orgs.filter((org) => org.id !== active.orgId);+ return (+ <div className="min-h-full flex flex-col items-center justify-center gap-4 bg-base px-6 text-contrast">+ <p role="alert" className="max-w-md text-center">+ {t(+ suspension === "organization"+ ? I18nKey.BACKEND$ORGANIZATION_SUSPENDED+ : I18nKey.BACKEND$MEMBERSHIP_SUSPENDED,+ { name: suspendedOrg ? orgLabel(suspendedOrg) : "" },+ )}+ </p>+ {otherOrgs.length > 0 && (+ <>+ <p>{t(I18nKey.BACKEND$SWITCH_WORKSPACE)}</p>+ {otherOrgs.map((org) => (+ <BrandButton+ key={org.id}+ type="button"+ variant="secondary"+ onClick={() => setActive(active.backend.id, org.id)}+ >+ {orgLabel(org)}+ </BrandButton>+ ))}+ </>+ )}+ </div>+ );+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 31d173914c..b5e5bdda04 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -44777,6 +44777,57 @@"tr": "Erişilebilir çalışma alanı yok. Yöneticinizden erişim izinlerinizi kontrol etmesini isteyin.","uk": "Немає доступних робочих просторів. Попросіть адміністратора перевірити ваші права доступу."},+ "BACKEND$ORGANIZATION_SUSPENDED": {+ "en": "{{name}} is suspended. Contact your administrator to restore access.",+ "ja": "ワークスペース「{{name}}」は停止されています。アクセスを復元するには管理者にお問い合わせください。",+ "zh-CN": "工作区 {{name}} 已被暂停。请联系管理员以恢复访问权限。",+ "zh-TW": "工作區 {{name}} 已被暫停。請聯絡管理員以恢復存取權限。",+ "ko-KR": "작업 공간 {{name}}이(가) 정지되었습니다. 액세스를 복원하려면 관리자에게 문의하세요.",+ "no": "Arbeidsområdet {{name}} er suspendert. Kontakt administratoren for å gjenopprette tilgangen.",+ "it": "Lo spazio di lavoro {{name}} è sospeso. Contatta l'amministratore per ripristinare l'accesso.",+ "pt": "O espaço de trabalho {{name}} está suspenso. Entre em contato com o administrador para restaurar o acesso.",+ "es": "El espacio de trabajo {{name}} está suspendido. Contacta con tu administrador para restaurar el acceso.",+ "ar": "تم تعليق مساحة العمل {{name}}. تواصل مع المسؤول لاستعادة الوصول.",+ "fr": "L'espace de travail {{name}} est suspendu. Contactez votre administrateur pour rétablir l'accès.",+ "tr": "{{name}} çalışma alanı askıya alındı. Erişimi geri yüklemek için yöneticinize başvurun.",+ "de": "Der Arbeitsbereich {{name}} ist gesperrt. Wenden Sie sich an Ihren Administrator, um den Zugriff wiederherzustellen.",+ "uk": "Робочий простір {{name}} призупинено. Зверніться до адміністратора, щоб відновити доступ.",+ "ca": "L'espai de treball {{name}} està suspès. Contacta amb l'administrador per restaurar l'accés."+ },+ "BACKEND$MEMBERSHIP_SUSPENDED": {+ "en": "Your access to {{name}} is suspended. Contact your administrator to restore it.",+ "ja": "「{{name}}」へのアクセスは停止されています。復元するには管理者にお問い合わせください。",+ "zh-CN": "您对 {{name}} 的访问权限已被暂停。请联系管理员以恢复。",+ "zh-TW": "您對 {{name}} 的存取權限已被暫停。請聯絡管理員以恢復。",+ "ko-KR": "{{name}}에 대한 액세스가 정지되었습니다. 복원하려면 관리자에게 문의하세요.",+ "no": "Tilgangen din til {{name}} er suspendert. Kontakt administratoren for å gjenopprette den.",+ "it": "Il tuo accesso a {{name}} è sospeso. Contatta l'amministratore per ripristinarlo.",+ "pt": "Seu acesso a {{name}} está suspenso. Entre em contato com o administrador para restaurá-lo.",+ "es": "Tu acceso a {{name}} está suspendido. Contacta con tu administrador para restaurarlo.",+ "ar": "تم تعليق وصولك إلى {{name}}. تواصل مع المسؤول لاستعادته.",+ "fr": "Votre accès à {{name}} est suspendu. Contactez votre administrateur pour le rétablir.",+ "tr": "{{name}} erişiminiz askıya alındı. Geri yüklemek için yöneticinize başvurun.",+ "de": "Ihr Zugriff auf {{name}} ist gesperrt. Wenden Sie sich an Ihren Administrator, um ihn wiederherzustellen.",+ "uk": "Ваш доступ до {{name}} призупинено. Зверніться до адміністратора, щоб відновити його.",+ "ca": "El teu accés a {{name}} està suspès. Contacta amb l'administrador per restaurar-lo."+ },+ "BACKEND$SWITCH_WORKSPACE": {+ "en": "Switch to another workspace",+ "ja": "別のワークスペースに切り替える",+ "zh-CN": "切换到其他工作区",+ "zh-TW": "切換到其他工作區",+ "ko-KR": "다른 작업 공간으로 전환",+ "no": "Bytt til et annet arbeidsområde",+ "it": "Passa a un altro spazio di lavoro",+ "pt": "Mudar para outro espaço de trabalho",+ "es": "Cambiar a otro espacio de trabajo",+ "ar": "التبديل إلى مساحة عمل أخرى",+ "fr": "Passer à un autre espace de travail",+ "tr": "Başka bir çalışma alanına geç",+ "de": "Zu einem anderen Arbeitsbereich wechseln",+ "uk": "Перейти до іншого робочого простору",+ "ca": "Canvia a un altre espai de treball"+ },"SETTINGS$APPS_VIEW_LOADING": {"en": "Loading app view...","ja": "アプリビューを読み込み中...",