Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(frontend): stop mutating cloud current_org_id on backend select (#359)

Hiep Le5dc765faf7a1
diff --git a/__tests__/api/cloud/organization-service.test.ts b/__tests__/api/cloud/organization-service.test.ts
index dd51e421ea..6ecc5de844 100644
--- a/__tests__/api/cloud/organization-service.test.ts
+++ b/__tests__/api/cloud/organization-service.test.ts
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
getCloudOrganizations,
getCurrentCloudApiKey,
- switchCloudOrganization,
} from "#/api/cloud/organization-service.api";
import type { Backend } from "#/api/backend-registry/types";
@@ -104,18 +103,4 @@ describe("cloud organization-service via local proxy", () => {
await expect(getCurrentCloudApiKey(cloudBackend)).rejects.toBe(error);
});
-
- it("switchCloudOrganization posts to the org-switch path through the proxy", async () => {
- vi.mocked(axios.post).mockResolvedValue({ data: {} });
-
- await switchCloudOrganization("org-2", cloudBackend);
-
- const [, body] = vi.mocked(axios.post).mock.calls[0]!;
- expect(body).toMatchObject({
- host: cloudBackend.host,
- method: "POST",
- path: "/api/organizations/org-2/switch",
- headers: { Authorization: "Bearer bearer-token" },
- });
- });
});
diff --git a/__tests__/api/cloud/proxy.test.ts b/__tests__/api/cloud/proxy.test.ts
new file mode 100644
index 0000000000..05563b243a
--- /dev/null
+++ b/__tests__/api/cloud/proxy.test.ts
@@ -0,0 +1,101 @@
+import axios from "axios";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { callCloudProxy } from "#/api/cloud/proxy";
+import type { Backend } from "#/api/backend-registry/types";
+
+vi.mock("axios");
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local",
+ host: "http://localhost:9000",
+ apiKey: "local-key",
+ kind: "local",
+};
+
+const cloudPersonal: Backend = {
+ id: "cloud-personal",
+ name: "Production - Personal",
+ host: "https://app.all-hands.dev",
+ apiKey: "personal-key",
+ kind: "cloud",
+};
+
+const cloudAcme: Backend = {
+ id: "cloud-acme",
+ name: "Production - Acme",
+ host: "https://app.all-hands.dev",
+ apiKey: "acme-key",
+ kind: "cloud",
+};
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ vi.mocked(axios.post).mockReset();
+ vi.mocked(axios.post).mockResolvedValue({ data: {} });
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ vi.mocked(axios.post).mockReset();
+});
+
+describe("callCloudProxy X-Org-Id injection", () => {
+ it("sends X-Org-Id when targeting the active cloud backend with a selected orgId", async () => {
+ // Arrange β€” active selection points at the cloud backend with a
+ // resolved orgId. This is the steady-state case after the user picks
+ // an org row in the BackendSelector.
+ setRegisteredBackends([localBackend, cloudPersonal]);
+ setActiveSelection({
+ backendId: cloudPersonal.id,
+ orgId: "org-personal-uuid",
+ });
+
+ // Act
+ await callCloudProxy({
+ backend: cloudPersonal,
+ method: "GET",
+ path: "/api/v1/app-conversations/search",
+ });
+
+ // Assert β€” the upstream envelope carries the X-Org-Id of the active
+ // selection so the SaaS can scope this request to the user's
+ // locally-chosen org without depending on user.current_org_id.
+ const [, body] = vi.mocked(axios.post).mock.calls[0]!;
+ expect(
+ (body as { headers: Record<string, string> }).headers["X-Org-Id"],
+ ).toBe("org-personal-uuid");
+ });
+
+ it("omits X-Org-Id when targeting a different cloud backend than the active one", async () => {
+ // Arrange β€” the BackendSelector fan-out (e.g. useAllCloudOrganizations)
+ // calls callCloudProxy(b) for every registered cloud backend. Sending
+ // the active backend's orgId across an unrelated API key would cause
+ // the SaaS to 403 on api_key_org_id / X-Org-Id mismatch.
+ setRegisteredBackends([cloudPersonal, cloudAcme]);
+ setActiveSelection({
+ backendId: cloudPersonal.id,
+ orgId: "org-personal-uuid",
+ });
+
+ // Act β€” request targets the non-active backend.
+ await callCloudProxy({
+ backend: cloudAcme,
+ method: "GET",
+ path: "/api/keys/current",
+ });
+
+ // Assert
+ const [, body] = vi.mocked(axios.post).mock.calls[0]!;
+ expect(
+ (body as { headers: Record<string, string> }).headers,
+ ).not.toHaveProperty("X-Org-Id");
+ });
+});
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index 0ff461d30d..3f66c648c7 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -10,7 +10,6 @@ import {
import userEvent from "@testing-library/user-event";
import { createRoutesStub, MemoryRouter, useParams } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { createAxiosError } from "test-utils";
import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
import {
ActiveBackendProvider,
@@ -24,16 +23,13 @@ import {
import {
getCloudOrganizations,
- switchCloudOrganization,
getCloudOrganizationMe,
getCurrentCloudApiKey,
} from "#/api/cloud/organization-service.api";
import { createServerClient } from "#/api/typescript-client";
-import { displayErrorToast } from "#/utils/custom-toast-handlers";
vi.mock("#/api/cloud/organization-service.api", () => ({
getCloudOrganizations: vi.fn(),
- switchCloudOrganization: vi.fn().mockResolvedValue(undefined),
getCloudOrganizationMe: vi.fn(),
getCurrentCloudApiKey: vi.fn(),
}));
@@ -42,10 +38,6 @@ vi.mock("#/api/typescript-client", () => ({
createServerClient: vi.fn(),
}));
-vi.mock("#/utils/custom-toast-handlers", () => ({
- displayErrorToast: vi.fn(),
-}));
-
function renderWithProviders(ui: React.ReactElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -85,8 +77,6 @@ beforeEach(() => {
window.localStorage.clear();
__resetActiveStoreForTests();
vi.mocked(getCloudOrganizations).mockReset();
- vi.mocked(switchCloudOrganization).mockReset();
- vi.mocked(switchCloudOrganization).mockResolvedValue(undefined);
vi.mocked(getCloudOrganizationMe).mockReset();
vi.mocked(getCloudOrganizationMe).mockResolvedValue({
orgId: "",
@@ -110,7 +100,6 @@ beforeEach(() => {
// the rest of the ServerClient surface is unused here, so a
// partial cast is sufficient.
} as unknown as ReturnType<typeof createServerClient>);
- vi.mocked(displayErrorToast).mockReset();
});
afterEach(() => {
@@ -158,7 +147,7 @@ describe("BackendSelector", () => {
expect(screen.getByText("Production")).toBeInTheDocument();
});
- it("expands a cloud backend into one row per org and fires switch-org on select", async () => {
+ it("expands a cloud backend into one row per org and records the org locally without calling SaaS /switch", async () => {
vi.mocked(getCloudOrganizations).mockResolvedValue({
items: [
{ id: "org-personal", name: "Personal" },
@@ -167,15 +156,16 @@ describe("BackendSelector", () => {
currentOrgId: "org-personal",
});
+ let cloudId = "";
renderWithProviders(
<TestSeed
onMount={(ctx) => {
- ctx.addBackend({
+ cloudId = ctx.addBackend({
name: "Production",
host: "https://app.all-hands.dev",
apiKey: "bearer-key",
kind: "cloud",
- });
+ }).id;
}}
>
<BackendSelector />
@@ -191,15 +181,15 @@ describe("BackendSelector", () => {
await user.click(screen.getByText("Production – Acme Inc"));
+ // Selecting an org row updates the active selection locally only β€”
+ // it must never trigger the SaaS-mutating /switch call that used to
+ // leak the local-UI choice into the cloud UI's `current_org_id`.
await waitFor(() => {
- expect(switchCloudOrganization).toHaveBeenCalled();
+ const stored = JSON.parse(
+ window.localStorage.getItem("openhands-active-backend") ?? "null",
+ );
+ expect(stored).toEqual({ backendId: cloudId, orgId: "org-2" });
});
- // The selector now passes an explicit backend so /switch lands on
- // the right cloud BEFORE the active selection flips.
- expect(switchCloudOrganization).toHaveBeenCalledWith(
- "org-2",
- expect.objectContaining({ host: "https://app.all-hands.dev" }),
- );
});
it("filters each cloud backend's org rows to the org its API key is bound to", async () => {
@@ -304,7 +294,7 @@ describe("BackendSelector", () => {
).not.toBeInTheDocument();
});
- it("self-heals (cloud, null) β†’ (cloud, personal-workspace org) once orgs + /me resolve", async () => {
+ it("self-heals (cloud, null) β†’ (cloud, personal-workspace org) locally once orgs + /me resolve", async () => {
const personalOrgId = "0b93b5f2-5396-49f2-8d98-61f906184270";
vi.mocked(getCloudOrganizations).mockResolvedValue({
items: [
@@ -337,16 +327,10 @@ describe("BackendSelector", () => {
</TestSeed>,
);
- // After orgs + /me resolve, the selector should have snapped the
- // selection onto the personal-workspace org and fired switchOrg.
- await waitFor(() => {
- expect(switchCloudOrganization).toHaveBeenCalled();
- });
- expect(switchCloudOrganization).toHaveBeenCalledWith(
- personalOrgId,
- expect.objectContaining({ host: "https://app.all-hands.dev" }),
- );
-
+ // After orgs + /me resolve, the selector snaps the active selection
+ // onto the personal-workspace org locally β€” without round-tripping
+ // /switch on the SaaS (which would have mutated the cloud UI's
+ // user.current_org_id as a side effect).
await waitFor(() => {
const stored = JSON.parse(
window.localStorage.getItem("openhands-active-backend") ?? "null",
@@ -592,147 +576,6 @@ describe("BackendSelector", () => {
).not.toBeInTheDocument();
});
- it("shows an error toast, dismisses the overlay, and does not switch to the failing cloud backend", async () => {
- vi.mocked(getCloudOrganizations).mockResolvedValue({
- items: [{ id: "org-2", name: "Acme Inc" }],
- currentOrgId: "org-2",
- });
- vi.mocked(switchCloudOrganization).mockRejectedValueOnce(
- createAxiosError(500, "Server Error", { message: "switch failed" }),
- );
-
- let productionId = "";
- let activeLocalId = "";
- renderWithProviders(
- <>
- <TestSeed
- onMount={(ctx) => {
- activeLocalId = ctx.addBackend({
- name: "Active Local",
- host: "http://localhost:9000",
- apiKey: "local-key",
- kind: "local",
- }).id;
- ctx.setActive(activeLocalId, null);
- productionId = ctx.addBackend({
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-key",
- kind: "cloud",
- }).id;
- }}
- >
- <BackendSelector />
- </TestSeed>
- <EnvironmentSwitchOverlay />
- </>,
- );
-
- const initialSelection = JSON.parse(
- window.localStorage.getItem("openhands-active-backend") ?? "null",
- );
-
- const user = await openDropdown();
- await waitFor(() => {
- expect(screen.getByText("Production – Acme Inc")).toBeInTheDocument();
- });
-
- await user.click(screen.getByText("Production – Acme Inc"));
-
- await waitFor(() => {
- expect(displayErrorToast).toHaveBeenCalledWith("switch failed");
- });
- expect(
- screen.queryByTestId("environment-switch-overlay"),
- ).not.toBeInTheDocument();
-
- const stored = JSON.parse(
- window.localStorage.getItem("openhands-active-backend") ?? "null",
- );
- expect(initialSelection?.backendId).toBe(activeLocalId);
- expect(stored?.backendId).not.toBe(productionId);
- expect(stored?.orgId ?? null).toBeNull();
- });
-
- it("shows a generic error toast instead of throwing on unexpected org switch errors", async () => {
- const consoleErrorSpy = vi
- .spyOn(console, "error")
- .mockImplementation(() => undefined);
- vi.mocked(getCloudOrganizations).mockResolvedValue({
- items: [{ id: "org-2", name: "Acme Inc" }],
- currentOrgId: "org-2",
- });
- vi.mocked(switchCloudOrganization).mockRejectedValueOnce(
- new Error("unexpected failure"),
- );
-
- renderWithProviders(
- <TestSeed
- onMount={(ctx) => {
- ctx.addBackend({
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-key",
- kind: "cloud",
- });
- }}
- >
- <BackendSelector />
- </TestSeed>,
- );
-
- const user = await openDropdown();
- await waitFor(() => {
- expect(screen.getByText("Production – Acme Inc")).toBeInTheDocument();
- });
-
- await user.click(screen.getByText("Production – Acme Inc"));
-
- await waitFor(() => {
- expect(displayErrorToast).toHaveBeenCalledWith("ERROR$GENERIC");
- });
- expect(consoleErrorSpy).toHaveBeenCalledWith(
- "Unexpected error during org switch:",
- expect.any(Error),
- );
- consoleErrorSpy.mockRestore();
- });
-
- it("falls back to the first registered local backend when malformed cloud self-heal fails", async () => {
- vi.mocked(getCloudOrganizations).mockResolvedValue({
- items: [{ id: "org-2", name: "Acme Inc" }],
- currentOrgId: "org-2",
- });
- vi.mocked(switchCloudOrganization).mockRejectedValueOnce(
- createAxiosError(500, "Server Error", { message: "switch failed" }),
- );
-
- renderWithProviders(
- <TestSeed
- onMount={(ctx) => {
- const production = ctx.addBackend({
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-key",
- kind: "cloud",
- });
- ctx.setActive(production.id, null);
- }}
- >
- <BackendSelector />
- </TestSeed>,
- );
-
- await waitFor(() => {
- const stored = JSON.parse(
- window.localStorage.getItem("openhands-active-backend") ?? "null",
- );
- // The seeded default-local backend is the first registered local.
- expect(stored?.backendId).toBe("default-local");
- expect(stored?.orgId ?? null).toBeNull();
- });
- });
-
it("renders the backend footer actions and opens/closes the add modal", async () => {
renderWithProviders(<BackendSelector />);
@@ -810,21 +653,32 @@ describe("BackendSelector", () => {
});
it("falls back to the seeded default backend when removing the active backend from manage backends", async () => {
- renderWithProviders(
- <TestSeed
- onMount={(ctx) => {
- const backend = ctx.addBackend({
- name: "Local 1",
- host: "http://localhost:9000",
- apiKey: "k",
- kind: "local",
- });
- ctx.setActive(backend.id);
- }}
- >
- <BackendSelector />
- </TestSeed>,
+ // Pre-seed the registry and active selection in localStorage so the
+ // initial render already reflects `Local 1` as active. Seeding via
+ // `TestSeed.onMount` instead would call `setActive` AFTER the first
+ // commit, causing the Dropdown's `key={activeValue-label}` to change
+ // and remount the dropdown β€” which races with the async health probe
+ // and intermittently drops the open-click state update.
+ const local1Id = "local-1-test-id";
+ window.localStorage.setItem(
+ "openhands-backends",
+ JSON.stringify([
+ {
+ id: local1Id,
+ name: "Local 1",
+ host: "http://localhost:9000",
+ apiKey: "k",
+ kind: "local",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ "openhands-active-backend",
+ JSON.stringify({ backendId: local1Id, orgId: null }),
);
+ __resetActiveStoreForTests();
+
+ renderWithProviders(<BackendSelector />);
let wrapper = screen.getByTestId("backend-selector");
let input = wrapper.querySelector("input") as HTMLInputElement;
diff --git a/__tests__/hooks/mutation/use-switch-cloud-organization.test.tsx b/__tests__/hooks/mutation/use-switch-cloud-organization.test.tsx
deleted file mode 100644
index 37ce70b555..0000000000
--- a/__tests__/hooks/mutation/use-switch-cloud-organization.test.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import React from "react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { renderHook, act, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useSwitchCloudOrganization } from "#/hooks/mutation/use-switch-cloud-organization";
-
-vi.mock("#/api/cloud/organization-service.api", () => ({
- switchCloudOrganization: vi.fn().mockResolvedValue(undefined),
-}));
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- vi.clearAllMocks();
-});
-
-function makeWrapper(queryClient: QueryClient) {
- return function Wrapper({ children }: { children: React.ReactNode }) {
- return (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- );
- };
-}
-
-describe("useSwitchCloudOrganization", () => {
- it("on success removes per-conversation queries and leaves unrelated cache entries untouched", async () => {
- const orgId = "fd950a0a-25bc-48ff-b4dd-ad53a990fb82";
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
-
- queryClient.setQueryData(["user", "conversation", "abc"], { dummy: 1 });
- queryClient.setQueryData(["unrelated"], { dummy: 1 });
-
- const { result } = renderHook(() => useSwitchCloudOrganization(), {
- wrapper: makeWrapper(queryClient),
- });
-
- act(() => {
- result.current.mutate({ orgId });
- });
-
- await waitFor(() => {
- expect(result.current.isSuccess).toBe(true);
- });
-
- // Per-conversation queries must be physically removed (their org
- // context is stale).
- expect(
- queryClient.getQueryData(["user", "conversation", "abc"]),
- ).toBeUndefined();
- // Other queries are NOT invalidated by this hook β€” they refetch via
- // the active-backend key change driven by `setActive` in the caller.
- expect(queryClient.getQueryData(["unrelated"])).toEqual({ dummy: 1 });
- });
-});
diff --git a/src/api/cloud/organization-service.api.ts b/src/api/cloud/organization-service.api.ts
index b6b0e90fcc..0e72ad1b0a 100644
--- a/src/api/cloud/organization-service.api.ts
+++ b/src/api/cloud/organization-service.api.ts
@@ -83,18 +83,6 @@ export async function getCurrentCloudApiKey(
}
}
-export async function switchCloudOrganization(
- orgId: string,
- backend?: Backend,
-): Promise<void> {
- const target = resolveBackend(backend);
- await callCloudProxy<unknown>({
- backend: target,
- method: "POST",
- path: `/api/organizations/${encodeURIComponent(orgId)}/switch`,
- });
-}
-
/**
* Fetch `GET /api/organizations/{orgId}/me`. Identifies the calling user as
* a member of `orgId`. The GUI uses `me.org_id === me.user_id` to decide
diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.ts
index 8ef6c29812..4fc84ff984 100644
--- a/src/api/cloud/proxy.ts
+++ b/src/api/cloud/proxy.ts
@@ -1,5 +1,8 @@
import axios from "axios";
-import { getEffectiveLocalBackend } from "../backend-registry/active-store";
+import {
+ getActiveBackend,
+ getEffectiveLocalBackend,
+} from "../backend-registry/active-store";
import { buildAuthHeaders } from "../backend-registry/auth";
import type { Backend } from "../backend-registry/types";
@@ -70,8 +73,21 @@ export async function callCloudProxy<TResponse = unknown>(
req: CloudProxyRequest,
): Promise<TResponse> {
const local = getEffectiveLocalBackend();
+ // Send `X-Org-Id` so the upstream scopes per-request to the org the user
+ // selected locally, instead of the user's globally-shared
+ // `current_org_id` on the SaaS. Restricted to calls against the active
+ // backend: the selector also fans out per-backend bookkeeping calls
+ // (e.g. `getCloudOrganizations(b)`) that would otherwise carry the
+ // active backend's orgId across an unrelated API key, which the SaaS
+ // rejects when api_key_org_id and X-Org-Id disagree.
+ const active = getActiveBackend();
+ const orgIdHeader =
+ active.backend.id === req.backend.id && active.orgId
+ ? { "X-Org-Id": active.orgId }
+ : {};
const upstreamHeaders = {
...buildUpstreamAuthHeaders(req),
+ ...orgIdHeader,
...(req.headers ?? {}),
};
const upstreamHost = req.hostOverride ?? req.backend.host;
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index 6ce8ff9e1f..1630eebeed 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -1,5 +1,4 @@
import React from "react";
-import axios from "axios";
import { useTranslation } from "react-i18next";
import { useMatch, useNavigate } from "react-router";
import { Plus, Settings } from "lucide-react";
@@ -12,7 +11,6 @@ import {
useBackendsHealth,
type BackendHealth,
} from "#/hooks/query/use-backends-health";
-import { useSwitchCloudOrganization } from "#/hooks/mutation/use-switch-cloud-organization";
import { I18nKey } from "#/i18n/declaration";
import type { Backend } from "#/api/backend-registry/types";
// Import the trigger helpers from the lightweight store, not the overlay
@@ -20,12 +18,9 @@ import type { Backend } from "#/api/backend-registry/types";
// pull in the overlay's render code (the overlay is lazy-loaded from
// `routes/root-layout.tsx`).
import {
- dismissEnvironmentSwitch,
ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS,
triggerEnvironmentSwitch,
} from "#/components/features/backends/environment-switch-store";
-import { displayErrorToast } from "#/utils/custom-toast-handlers";
-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
import { getLastConversationId } from "#/api/backend-registry/last-conversation-store";
import { AddBackendModal } from "./add-backend-modal";
import { BackendStatusDot } from "./backend-status-dot";
@@ -116,8 +111,6 @@ export function BackendSelector({
const currentUserIds = useCloudCurrentUserId();
// Probe each registered backend every 10s.
const healthByBackendId = useBackendsHealth(backends);
- const { mutateAsync: switchOrg, isPending: isSwitching } =
- useSwitchCloudOrganization();
const navigate = useNavigate();
const conversationMatch = useMatch("/conversations/:conversationId");
const automationDetailMatch = useMatch("/automations/:automationId");
@@ -127,11 +120,6 @@ export function BackendSelector({
const personalWorkspaceLabel = t(I18nKey.BACKEND$PERSONAL_WORKSPACE);
- const firstLocalBackendId = React.useMemo(
- () => backends.find((b) => b.kind === "local")?.id ?? null,
- [backends],
- );
-
const options = React.useMemo(
() =>
buildOptions(
@@ -162,53 +150,25 @@ export function BackendSelector({
// selecting that shape would drift from what the dropdown can render
// (UI says "Local", APIs hit cloud). When we detect the drift, snap
// the selection onto the personal-workspace org (or, lacking a /me
- // result, the first org). Pre-switch the SaaS-side current_org BEFORE
- // touching active state so queries refetch (via key change) only
- // once and against the correct org context.
+ // result, the first org). The selection is recorded locally only;
+ // the SaaS request scope follows from the API key's bound org and the
+ // X-Org-Id header sent by `callCloudProxy`, so the cloud UI's
+ // org choice is never mutated as a side effect.
React.useEffect(() => {
- let cancelled = false;
-
- if (active.backend.kind === "cloud" && !active.orgId) {
- const { backend } = active;
- const entry = cloudOrgs[backend.id];
-
- if (entry && entry.orgs.length > 0) {
- const userId = currentUserIds[backend.id]?.userId ?? null;
- const personal = userId
- ? entry.orgs.find((o) => o.id === userId)
- : undefined;
- const target = personal ?? entry.orgs[0];
-
- if (target) {
- const syncActiveOrg = async () => {
- try {
- await switchOrg({ orgId: target.id, backend });
- if (!cancelled) {
- setActive(backend.id, target.id);
- }
- } catch {
- if (!cancelled && firstLocalBackendId) {
- setActive(firstLocalBackendId, null);
- }
- }
- };
-
- syncActiveOrg();
- }
- }
+ if (active.backend.kind !== "cloud" || active.orgId) return;
+ const { backend } = active;
+ const entry = cloudOrgs[backend.id];
+ if (!entry || entry.orgs.length === 0) return;
+
+ const userId = currentUserIds[backend.id]?.userId ?? null;
+ const personal = userId
+ ? entry.orgs.find((o) => o.id === userId)
+ : undefined;
+ const target = personal ?? entry.orgs[0];
+ if (target) {
+ setActive(backend.id, target.id);
}
-
- return () => {
- cancelled = true;
- };
- }, [
- active,
- firstLocalBackendId,
- cloudOrgs,
- currentUserIds,
- setActive,
- switchOrg,
- ]);
+ }, [active, cloudOrgs, currentUserIds, setActive]);
const openAddBackendModal = React.useCallback(() => {
setAddBackendModalOpen(true);
@@ -276,25 +236,6 @@ export function BackendSelector({
setTimeout(resolve, ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS);
});
- if (orgId && target.kind === "cloud") {
- try {
- await switchOrg({ orgId, backend: target });
- } catch (error) {
- dismissEnvironmentSwitch();
-
- if (!axios.isAxiosError(error)) {
- console.error("Unexpected error during org switch:", error);
- displayErrorToast(t(I18nKey.ERROR$GENERIC));
- return;
- }
-
- displayErrorToast(
- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),
- );
- return;
- }
- }
-
// Compute where the user should land on the target backend.
// The rule:
// - on `/conversations/:id`: jump to the target backend's
@@ -331,7 +272,7 @@ export function BackendSelector({
setActive(target.id, orgId);
}}
placeholder={active.backend.name}
- loading={someCloudLoading || isSwitching}
+ loading={someCloudLoading}
options={options}
className="bg-[#1F1F1F66] border-[#242424]"
/>
diff --git a/src/hooks/mutation/use-switch-cloud-organization.ts b/src/hooks/mutation/use-switch-cloud-organization.ts
deleted file mode 100644
index 5d86becba0..0000000000
--- a/src/hooks/mutation/use-switch-cloud-organization.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { switchCloudOrganization } from "#/api/cloud/organization-service.api";
-import type { Backend } from "#/api/backend-registry/types";
-
-interface SwitchVariables {
- orgId: string;
- /**
- * Backend to forward `/switch` to. Required when the active backend
- * hasn't been swapped over yet (e.g. switching from Local β†’ a cloud
- * backend, where we want the SaaS-side `current_org_id` updated
- * BEFORE we flip the GUI's active selection β€” otherwise queries
- * would refetch with stale `current_org_id`).
- */
- backend?: Backend;
-}
-
-/**
- * Switch the current cloud organization on the SaaS.
- *
- * Mirrors OpenHands' `useSwitchOrganization`. The SaaS server tracks
- * the caller's "current org", so subsequent API calls automatically
- * scope to the new org.
- *
- * No explicit per-key invalidations on success: every long-lived
- * cloud-aware query (`useSettings`, `usePaginatedConversations`,
- * `useGitRepositories`, `useAppInstallations`, `useGitUser`,
- * `useCloudCurrentUserId`, …) has the active backend identity + orgId
- * baked into its query key. The caller updates the active selection
- * after this mutation succeeds; that re-keys those queries and React
- * Query refetches them automatically β€” once, with the correct
- * server-side `current_org_id` already in place.
- *
- * Per-conversation queries (`["user", "conversation"]`) are removed
- * outright since their data is org-scoped and shouldn't survive the
- * transition.
- */
-export function useSwitchCloudOrganization() {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: ({ orgId, backend }: SwitchVariables) =>
- switchCloudOrganization(orgId, backend),
- onSuccess: () => {
- queryClient.removeQueries({ queryKey: ["user", "conversation"] });
- },
- });
-}
diff --git a/src/hooks/query/use-cloud-current-user-id.ts b/src/hooks/query/use-cloud-current-user-id.ts
index eb685ffed8..7201376670 100644
--- a/src/hooks/query/use-cloud-current-user-id.ts
+++ b/src/hooks/query/use-cloud-current-user-id.ts
@@ -23,9 +23,9 @@ import { useAllCloudOrganizations } from "./use-cloud-organizations";
* active environment, while still supporting the personal-workspace
* label across non-active backends in the dropdown.
*
- * `useSwitchCloudOrganization.onSuccess` invalidates
- * `["cloud-current-user"]`, so picking a different org refetches `/me`
- * with the new active orgId.
+ * The query key includes `active.orgId`, so picking a different org
+ * via `setActive` re-keys this query and refetches `/me` with the new
+ * active orgId.
*/
export function useCloudCurrentUserId(): Record<
string,