π OpenHands: AI-Driven Development
fix: cloud conversation org scoping (#18130)
Rohit Malhotra96bcee6a4f9a
diff --git a/__tests__/hooks/query/use-conversation-skills.test.tsx b/__tests__/hooks/query/use-conversation-skills.test.tsxindex 39ceb31c5a..0e0d8cc45b 100644--- a/__tests__/hooks/query/use-conversation-skills.test.tsx+++ b/__tests__/hooks/query/use-conversation-skills.test.tsx@@ -123,7 +123,7 @@ afterEach(() => {describe("useConversationSkills", () => {it("lists the conversation's own skills on a cloud backend once its sandbox runs", async () => {// Arrange- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });const { wrapper } = makeWrapper(CONVERSATION_ID);// Act@@ -141,7 +141,7 @@ describe("useConversationSkills", () => {it("does not request skills for a cloud conversation whose sandbox is not running yet", async () => {// Arrange- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });vi.mocked(AgentServerConversationService.batchGetAppConversations,).mockResolvedValue([makeConversation({ sandbox_status: "STARTING" })]);@@ -183,7 +183,7 @@ describe("useConversationSkills", () => {it("falls back to the global catalog on a cloud backend without a conversation route", async () => {// Arrange- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });const { wrapper } = makeWrapper(null);// Actdiff --git a/__tests__/hooks/query/use-paginated-conversations.test.tsx b/__tests__/hooks/query/use-paginated-conversations.test.tsxindex 518e519bec..8ec4e2b00c 100644--- a/__tests__/hooks/query/use-paginated-conversations.test.tsx+++ b/__tests__/hooks/query/use-paginated-conversations.test.tsx@@ -7,6 +7,10 @@ import { NavigationProvider } from "#/context/navigation-context";import { usePaginatedConversations } from "#/hooks/query/use-paginated-conversations";import type { AppConversationPage } from "#/api/conversation-service/agent-server-conversation-service.types";+const { useActiveBackendMock } = vi.hoisted(() => ({+ useActiveBackendMock: vi.fn(),+}));+vi.mock("#/api/conversation-service/agent-server-conversation-service.api",() => ({@@ -17,10 +21,7 @@ vi.mock();vi.mock("#/contexts/active-backend-context", () => ({- useActiveBackend: () => ({- backend: { id: "test-backend", kind: "local" },- orgId: null,- }),+ useActiveBackend: useActiveBackendMock,}));const emptyPage: AppConversationPage = { items: [], next_page_id: null };@@ -56,6 +57,11 @@ describe("usePaginatedConversations β interval polling", () => {vi.mocked(AgentServerConversationService.searchConversations,).mockResolvedValue(emptyPage);+ useActiveBackendMock.mockReset();+ useActiveBackendMock.mockReturnValue({+ backend: { id: "test-backend", kind: "local" },+ orgId: null,+ });});afterEach(() => {@@ -98,4 +104,20 @@ describe("usePaginatedConversations β interval polling", () => {AgentServerConversationService.searchConversations,).toHaveBeenCalledTimes(2);});++ it("does not search Cloud conversations before an org is selected", async () => {+ useActiveBackendMock.mockReturnValue({+ backend: { id: "cloud-backend", kind: "cloud" },+ orgId: null,+ });++ renderHook(() => usePaginatedConversations(), {+ wrapper: createWrapper("/"),+ });+ await flushAsync();++ expect(+ AgentServerConversationService.searchConversations,+ ).not.toHaveBeenCalled();+ });});diff --git a/__tests__/hooks/query/use-user-conversation.test.tsx b/__tests__/hooks/query/use-user-conversation.test.tsxindex 9e8399692f..f051cd45e4 100644--- a/__tests__/hooks/query/use-user-conversation.test.tsx+++ b/__tests__/hooks/query/use-user-conversation.test.tsx@@ -96,7 +96,7 @@ afterEach(() => {describe("useUserConversation β backend switch", () => {it("does not load the conversation id against a different backend after switching", async () => {// Arrange β the conversation is opened while the cloud backend is active.- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });const { result } = renderHook(() => useUserConversation(CLOUD_CONVERSATION_ID),{ wrapper: makeWrapper() },@@ -141,4 +141,31 @@ describe("useUserConversation β backend switch", () => {).toHaveBeenCalledTimes(2),);});++ it("waits for a Cloud org before loading a conversation", async () => {+ // Arrange β locked-cloud bootstraps with the backend selected before its+ // organization boundary has resolved the concrete workspace.+ setActiveSelection({ backendId: cloudBackend.id });+ const { result } = renderHook(+ () => useUserConversation(CLOUD_CONVERSATION_ID),+ { wrapper: makeWrapper() },+ );++ // Assert β the detail lookup does not fall back to the server's mutable+ // current_org_id while Canvas still has no explicit org scope.+ expect(result.current.fetchStatus).toBe("idle");+ expect(+ AgentServerConversationService.batchGetAppConversations,+ ).not.toHaveBeenCalled();++ // Act β once the Cloud organization boundary resolves the workspace, the+ // query can run under the org-scoped key.+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });++ await waitFor(() =>+ expect(+ AgentServerConversationService.batchGetAppConversations,+ ).toHaveBeenCalledTimes(1),+ );+ });});diff --git a/__tests__/routes/conversation-backend-switch.test.tsx b/__tests__/routes/conversation-backend-switch.test.tsxindex 4c90bb89d2..8e2ac4fbd3 100644--- a/__tests__/routes/conversation-backend-switch.test.tsx+++ b/__tests__/routes/conversation-backend-switch.test.tsx@@ -218,7 +218,7 @@ afterEach(() => {describe("conversation route β backend switch", () => {it("tears down the conversation view when the active backend changes mid-conversation", async () => {// Arrange β the cloud conversation renders while the cloud backend is active.- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });renderConversation();expect(await screen.findByTestId("conversation-main")).toBeInTheDocument();@@ -238,7 +238,7 @@ describe("conversation route β shared read-only fallback", () => {it("sends an org member to the read-only shared view when only the shared lookup can see the conversation", async () => {// Arrange β the owner lookup misses on cloud, but the conversation is// shared with this user (an automation conversation from their org).- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });vi.mocked(AgentServerConversationService.batchGetAppConversations,).mockResolvedValue([null]);@@ -261,7 +261,7 @@ describe("conversation route β shared read-only fallback", () => {it("reports the conversation as missing when neither lookup can see it on cloud", async () => {// Arrange- setActiveSelection({ backendId: cloudBackend.id });+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });vi.mocked(AgentServerConversationService.batchGetAppConversations,).mockResolvedValue([null]);diff --git a/src/api/cloud/proxy.test.ts b/src/api/cloud/proxy.test.tsnew file mode 100644index 0000000000..5558a830dd--- /dev/null+++ b/src/api/cloud/proxy.test.ts@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Backend } from "#/api/backend-registry/types";++const { CloudClientMock, requestMock, getActiveBackendMock } = vi.hoisted(+ () => ({+ requestMock: vi.fn(),+ CloudClientMock: vi.fn(function CloudClient(this: { request: unknown }) {+ this.request = requestMock;+ }),+ getActiveBackendMock: vi.fn(),+ }),+);++vi.mock("@openhands/typescript-client/clients", () => ({+ CloudClient: CloudClientMock,+}));++vi.mock("../agent-server-config", () => ({+ getAgentServerBaseUrl: () => null,+ getAgentServerHeaders: () => ({}),+}));++vi.mock("../backend-registry/active-store", () => ({+ getActiveBackend: getActiveBackendMock,+}));++import { callCloudProxy } from "./proxy";++const cloudBackend: Backend = {+ id: "locked-cloud",+ name: "OpenHands Cloud",+ host: "https://cloud.example.test",+ apiKey: "",+ kind: "cloud",+ authMode: "cookie",+};++describe("callCloudProxy", () => {+ beforeEach(() => {+ CloudClientMock.mockClear();+ requestMock.mockReset();+ requestMock.mockResolvedValue({ ok: true });+ getActiveBackendMock.mockReset();+ getActiveBackendMock.mockReturnValue({+ backend: cloudBackend,+ orgId: "org-1",+ });+ });++ it("forwards the active Cloud org as X-Org-Id", async () => {+ await callCloudProxy({+ backend: cloudBackend,+ method: "GET",+ path: "/api/v1/app-conversations?ids=conv-1",+ headers: { "X-Agent-Canvas-Client": "test" },+ });++ expect(requestMock).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: expect.objectContaining({+ "X-Agent-Canvas-Client": "test",+ "X-Org-Id": "org-1",+ }),+ }),+ );+ });++ it("does not send an org header for inactive cloud backends", async () => {+ const inactiveBackend = { ...cloudBackend, id: "other-cloud" };++ await callCloudProxy({+ backend: inactiveBackend,+ method: "GET",+ path: "/api/v1/app-conversations?ids=conv-1",+ });++ expect(requestMock).toHaveBeenCalledWith(+ expect.objectContaining({ headers: undefined }),+ );+ });+});diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.tsindex cc4c0591af..d2f95022f5 100644--- a/src/api/cloud/proxy.ts+++ b/src/api/cloud/proxy.ts@@ -29,13 +29,14 @@ export async function callCloudProxy<TResponse = unknown>(// 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);+ const headers = orgId ? { ...req.headers, "X-Org-Id": orgId } : req.headers;try {return await client.request<TResponse>({method: req.method,path: req.path,body: req.body,- headers: req.headers,+ headers,timeoutSeconds: req.timeoutSeconds,hostOverride: req.hostOverride,authMode:diff --git a/src/hooks/query/use-paginated-conversations.ts b/src/hooks/query/use-paginated-conversations.tsindex 460dfdb463..98670cbc1c 100644--- a/src/hooks/query/use-paginated-conversations.ts+++ b/src/hooks/query/use-paginated-conversations.ts@@ -12,6 +12,8 @@ export const usePaginatedConversations = (limit: number = 20) => {const active = useActiveBackend();const { currentPath } = useNavigation();const hasBackend = !isNoBackend(active.backend);+ const hasConversationScope =+ active.backend.kind !== "cloud" || !!active.orgId;return useInfiniteQuery({// Include the active backend identity so each (backend, org) pair@@ -34,7 +36,7 @@ export const usePaginatedConversations = (limit: number = 20) => {return result;},- enabled: !!userIsAuthenticated && hasBackend,+ enabled: !!userIsAuthenticated && hasBackend && hasConversationScope,getNextPageParam: (lastPage: AppConversationPage) => lastPage.next_page_id,initialPageParam: undefined as string | undefined,// Poll every 30s so titles, execution status, and timestamps stay freshdiff --git a/src/hooks/query/use-user-conversation.ts b/src/hooks/query/use-user-conversation.tsindex e037c2cd92..3e0e75c3b4 100644--- a/src/hooks/query/use-user-conversation.ts+++ b/src/hooks/query/use-user-conversation.ts@@ -41,6 +41,8 @@ export const useUserConversation = (origin.current = { cid, backendId: active.backend.id };}const backendChanged = origin.current.backendId !== active.backend.id;+ const hasConversationScope =+ active.backend.kind !== "cloud" || !!active.orgId;return useQuery({// Include the active backend identity so each (backend, org) pair@@ -59,7 +61,11 @@ export const useUserConversation = (await AgentServerConversationService.batchGetAppConversations([cid]);return results[0] ?? null;},- enabled: !!cid && !cid.startsWith("task-") && !backendChanged,+ enabled:+ !!cid &&+ !cid.startsWith("task-") &&+ !backendChanged &&+ hasConversationScope,// Rate limits (429) are transient and worth a couple of backed-off// retries; any other failure (404, 5xx, network) fails immediately as// before rather than masking a real problem.