Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: stop loading the cloud conversation after switching to a local backend (#1047)

Hiep Le09af97be173c
diff --git a/__tests__/hooks/query/use-user-conversation.test.tsx b/__tests__/hooks/query/use-user-conversation.test.tsx
new file mode 100644
index 0000000000..9e8399692f
--- /dev/null
+++ b/__tests__/hooks/query/use-user-conversation.test.tsx
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import React from "react";
+import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import { useUserConversation } from "#/hooks/query/use-user-conversation";
+import type { Backend } from "#/api/backend-registry/types";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+// Mock the underlying service the hook depends on (not the hook itself).
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({
+ default: { batchGetAppConversations: vi.fn() },
+ }),
+);
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local 1",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "cloud-1",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-key",
+ kind: "cloud",
+};
+
+const CLOUD_CONVERSATION_ID = "conv-cloud";
+
+function makeConversation(id: string): AppConversation {
+ return {
+ id,
+ created_by_user_id: null,
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ title: "Test",
+ trigger: null,
+ pr_number: [],
+ llm_model: null,
+ metrics: null,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ execution_status: null,
+ sandbox_status: null,
+ conversation_url: "https://sandbox.example.com/api",
+ session_api_key: null,
+ sandbox_id: null,
+ sub_conversation_ids: [],
+ };
+}
+
+function makeWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>{children}</ActiveBackendProvider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ vi.mocked(
+ AgentServerConversationService.batchGetAppConversations,
+ ).mockReset();
+ vi.mocked(
+ AgentServerConversationService.batchGetAppConversations,
+ ).mockResolvedValue([makeConversation(CLOUD_CONVERSATION_ID)]);
+ setRegisteredBackends([localBackend, cloudBackend]);
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+});
+
+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 });
+ const { result } = renderHook(
+ () => useUserConversation(CLOUD_CONVERSATION_ID),
+ { wrapper: makeWrapper() },
+ );
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(
+ AgentServerConversationService.batchGetAppConversations,
+ ).toHaveBeenCalledTimes(1);
+
+ // Act β€” switch to the local backend without leaving the conversation.
+ setActiveSelection({ backendId: localBackend.id });
+
+ // Assert β€” the cloud id is foreign to the local backend, so the query is
+ // disabled and never fetched against it (no second service call).
+ await waitFor(() => expect(result.current.data).toBeUndefined());
+ expect(
+ AgentServerConversationService.batchGetAppConversations,
+ ).toHaveBeenCalledTimes(1);
+ });
+
+ it("still loads the conversation when only the org changes on the same backend", async () => {
+ // Arrange β€” opened under a cloud backend scoped to one org.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });
+ const { result } = renderHook(
+ () => useUserConversation(CLOUD_CONVERSATION_ID),
+ { wrapper: makeWrapper() },
+ );
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(
+ AgentServerConversationService.batchGetAppConversations,
+ ).toHaveBeenCalledTimes(1);
+
+ // Act β€” switch org within the same backend (e.g. the cloud personal-
+ // workspace self-heal), which keeps the same agent-server schema.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-b" });
+
+ // Assert β€” same backend, so the conversation is fetched again for the
+ // new org rather than being disabled.
+ await waitFor(() =>
+ expect(
+ AgentServerConversationService.batchGetAppConversations,
+ ).toHaveBeenCalledTimes(2),
+ );
+ });
+});
diff --git a/__tests__/routes/conversation-backend-switch.test.tsx b/__tests__/routes/conversation-backend-switch.test.tsx
new file mode 100644
index 0000000000..e9b385293d
--- /dev/null
+++ b/__tests__/routes/conversation-backend-switch.test.tsx
@@ -0,0 +1,157 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import React from "react";
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import { NavigationProvider } from "#/context/navigation-context";
+import ConversationView from "#/routes/conversation";
+import type { Backend } from "#/api/backend-registry/types";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+
+// Mock the underlying service the conversation queries depend on.
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({
+ default: { batchGetAppConversations: vi.fn() },
+ }),
+);
+
+// Stub the heavy presentational subtree so the test focuses on the route's
+// teardown behaviour, not the conversation UI.
+vi.mock(
+ "#/components/features/conversation/conversation-main/conversation-main",
+ () => ({
+ ConversationMain: () => <div data-testid="conversation-main" />,
+ ConversationMobilePanelPage: () => <div data-testid="conversation-panel" />,
+ }),
+);
+vi.mock("#/wrapper/event-handler", () => ({
+ EventHandler: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+vi.mock("#/contexts/websocket-provider-wrapper", () => ({
+ WebSocketProviderWrapper: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+vi.mock("#/hooks/query/use-task-polling", () => ({
+ useTaskPolling: () => ({ isTask: false, taskStatus: null, taskDetail: null }),
+}));
+vi.mock("#/hooks/query/use-is-authed", () => ({
+ useIsAuthed: () => ({ data: true }),
+}));
+vi.mock("#/api/cloud/conversation-service.api", () => ({
+ resumeCloudSandbox: vi.fn(),
+}));
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local 1",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "cloud-1",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-key",
+ kind: "cloud",
+};
+
+const CLOUD_CONVERSATION_ID = "conv-cloud";
+
+function makeConversation(id: string): AppConversation {
+ return {
+ id,
+ created_by_user_id: null,
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ title: "Test",
+ trigger: null,
+ pr_number: [],
+ llm_model: null,
+ metrics: null,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ execution_status: null,
+ sandbox_status: null,
+ conversation_url: "https://sandbox.example.com/api",
+ session_api_key: null,
+ sandbox_id: null,
+ sub_conversation_ids: [],
+ };
+}
+
+function renderConversation() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <MemoryRouter initialEntries={[`/conversations/${CLOUD_CONVERSATION_ID}`]}>
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <NavigationProvider
+ value={{
+ currentPath: `/conversations/${CLOUD_CONVERSATION_ID}`,
+ conversationId: CLOUD_CONVERSATION_ID,
+ isNavigating: false,
+ navigate: vi.fn(),
+ }}
+ >
+ <ConversationView />
+ </NavigationProvider>
+ </ActiveBackendProvider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ vi.mocked(
+ AgentServerConversationService.batchGetAppConversations,
+ ).mockReset();
+ vi.mocked(
+ AgentServerConversationService.batchGetAppConversations,
+ ).mockResolvedValue([makeConversation(CLOUD_CONVERSATION_ID)]);
+ setRegisteredBackends([localBackend, cloudBackend]);
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+});
+
+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 });
+ renderConversation();
+ expect(
+ await screen.findByTestId("conversation-main"),
+ ).toBeInTheDocument();
+
+ // Act β€” switch to the local backend without leaving the conversation.
+ setActiveSelection({ backendId: localBackend.id });
+
+ // Assert β€” the subtree unmounts instead of rendering the cloud
+ // conversation under the local backend, so its per-conversation queries
+ // cannot fire against a backend the id is foreign to.
+ await waitFor(() => {
+ expect(screen.queryByTestId("conversation-main")).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/src/hooks/query/use-user-conversation.ts b/src/hooks/query/use-user-conversation.ts
index ef8815e8d1..89adc167c4 100644
--- a/src/hooks/query/use-user-conversation.ts
+++ b/src/hooks/query/use-user-conversation.ts
@@ -1,4 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
+import { useRef } from "react";
import { Query, useQuery } from "@tanstack/react-query";
import { AxiosError } from "axios";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
@@ -23,6 +24,22 @@ export const useUserConversation = (
) => {
const active = useActiveBackend();
+ // The cid belongs to whichever backend was active when the user opened this
+ // conversation. If they switch to a *different* backend (e.g. cloud β†’ local)
+ // without leaving the conversation view, the cid is foreign to the new
+ // backend; fetching it makes that backend parse a response for an id it
+ // doesn't own and surfaces a confusing "agent server returned data this UI
+ // does not understand" toast. Pin the cid to its origin backend and disable
+ // the query until the route navigates to a valid id. Compare backend id
+ // ONLY β€” org changes within the same backend (e.g. the cloud
+ // personal-workspace self-heal in BackendSelector) keep the same
+ // agent-server schema and must still refetch.
+ const origin = useRef({ cid, backendId: active.backend.id });
+ if (origin.current.cid !== cid) {
+ origin.current = { cid, backendId: active.backend.id };
+ }
+ const backendChanged = origin.current.backendId !== active.backend.id;
+
return useQuery({
// Include the active backend identity so each (backend, org) pair
// maintains its own per-conversation cache entry. Without this, a
@@ -40,7 +57,7 @@ export const useUserConversation = (
await AgentServerConversationService.batchGetAppConversations([cid]);
return results[0] ?? null;
},
- enabled: !!cid && !cid.startsWith("task-"),
+ enabled: !!cid && !cid.startsWith("task-") && !backendChanged,
retry: false,
refetchInterval,
staleTime: FIVE_MINUTES,
diff --git a/src/routes/conversation.tsx b/src/routes/conversation.tsx
index c22810997b..9aa4115c4f 100644
--- a/src/routes/conversation.tsx
+++ b/src/routes/conversation.tsx
@@ -178,6 +178,20 @@ function AppContent() {
t,
]);
+ // A backend switch is in flight (BackendSelector flips the active backend
+ // and redirects to /conversations on the next tick). The conversationId in
+ // the URL belongs to the *previous* backend, so unmount the whole
+ // conversation subtree now β€” before any per-conversation query (history,
+ // metrics, sub-conversations, runtime info, …) re-fires against a backend
+ // the id is foreign to. Those foreign fetches fail response validation and
+ // surface "agent server returned data this UI does not understand". This is
+ // deterministic regardless of the navigate-vs-setActive render race: React
+ // re-renders this parent before its children, so returning null removes them
+ // before they can issue the request.
+ if (backendChanged) {
+ return null;
+ }
+
const content = (
<EventHandler>
<div data-testid="app-route" className="flex h-full flex-col">