Skip to content

🙌 OpenHands: AI-Driven Development

fix(conversations): key per-conversation queries by active backend (#275)

Robert Brennan9c405c201a8f
diff --git a/__tests__/hooks/use-websocket.test.ts b/__tests__/hooks/use-websocket.test.ts
index 39f7ee5bf5..63fa9d0be7 100644
--- a/__tests__/hooks/use-websocket.test.ts
+++ b/__tests__/hooks/use-websocket.test.ts
@@ -163,23 +163,72 @@ describe("useWebSocket", () => {
});
it("should support query parameters in WebSocket URL", async () => {
- const baseUrl = "ws://acme.com/ws";
- const queryParams = {
- token: "abc123",
- userId: "user456",
- version: "v1",
- };
+ // Stub WebSocket deterministically (mirrors the `onClose` test below).
+ // The MSW-backed variant was flaky in CI — `wsLink.broadcast()` from
+ // other tests leaks across the shared mock server, and this assertion
+ // only needs to observe the constructed URL, not a real connection.
+ class MockWebSocket {
+ static readonly CONNECTING = 0;
+ static readonly OPEN = 1;
+ static readonly CLOSING = 2;
+ static readonly CLOSED = 3;
- const { result } = renderHook(() => useWebSocket(baseUrl, { queryParams }));
+ readonly url: string;
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((event: Event) => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onclose: ((event: CloseEvent) => void) | null = null;
+ onerror: ((event: Event) => void) | null = null;
- // Wait for connection to be established
- await waitForConnection(result);
+ constructor(url: string) {
+ this.url = url;
+ queueMicrotask(() => {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.(new Event("open"));
+ });
+ }
- // Verify that the WebSocket was created with query parameters
- expect(result.current.socket).toBeTruthy();
- expect(result.current.socket!.url).toBe(
- "ws://acme.com/ws?token=abc123&userId=user456&version=v1",
- );
+ send() {}
+
+ close() {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.(
+ new CloseEvent("close", {
+ code: 1000,
+ reason: "Normal closure",
+ wasClean: true,
+ }),
+ );
+ }
+ }
+
+ const originalWebSocket = globalThis.WebSocket;
+ vi.stubGlobal("WebSocket", MockWebSocket);
+
+ try {
+ const baseUrl = "ws://acme.com/ws";
+ const queryParams = {
+ token: "abc123",
+ userId: "user456",
+ version: "v1",
+ };
+
+ const { result, unmount } = renderHook(() =>
+ useWebSocket(baseUrl, { queryParams }),
+ );
+
+ await waitForConnection(result);
+
+ // Verify that the WebSocket was created with query parameters
+ expect(result.current.socket).toBeTruthy();
+ expect(result.current.socket!.url).toBe(
+ "ws://acme.com/ws?token=abc123&userId=user456&version=v1",
+ );
+
+ unmount();
+ } finally {
+ globalThis.WebSocket = originalWebSocket;
+ }
});
// Skipped: flaky in CI - see comment at top of file
diff --git a/src/hooks/query/use-batch-app-conversations.ts b/src/hooks/query/use-batch-app-conversations.ts
index 3dab66c6bb..9cb05c2379 100644
--- a/src/hooks/query/use-batch-app-conversations.ts
+++ b/src/hooks/query/use-batch-app-conversations.ts
@@ -1,11 +1,23 @@
import { useQuery } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
-export const useBatchAppConversations = (ids: string[]) =>
- useQuery({
- queryKey: ["v1-batch-get-app-conversations", ids],
+export const useBatchAppConversations = (ids: string[]) => {
+ const active = useActiveBackend();
+
+ return useQuery({
+ // Backend-keyed so cross-backend switches do not return another
+ // backend's cached results. Same invariant as
+ // `useUserConversation` and `usePaginatedConversations`.
+ queryKey: [
+ "v1-batch-get-app-conversations",
+ ids,
+ active.backend.id,
+ active.orgId,
+ ],
queryFn: () => AgentServerConversationService.batchGetAppConversations(ids),
enabled: ids.length > 0,
staleTime: 1000 * 60 * 5, // 5 minutes
gcTime: 1000 * 60 * 15, // 15 minutes
});
+};
diff --git a/src/hooks/query/use-sub-conversations.ts b/src/hooks/query/use-sub-conversations.ts
index adba820cbf..5dd3922480 100644
--- a/src/hooks/query/use-sub-conversations.ts
+++ b/src/hooks/query/use-sub-conversations.ts
@@ -1,6 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { useActiveBackend } from "#/contexts/active-backend-context";
const FIVE_MINUTES = 1000 * 60 * 5;
const FIFTEEN_MINUTES = 1000 * 60 * 15;
@@ -22,9 +23,15 @@ export const useSubConversations = (
subConversationIds: string[] | null | undefined,
) => {
const ids = subConversationIds || [];
+ const active = useActiveBackend();
return useQuery<(AppConversation | null)[]>({
- queryKey: ["v1", "sub-conversations", ids],
+ // Backend-keyed: a local→cloud→local switch must produce a fresh
+ // cache identity for these per-conversation fetches, otherwise a
+ // `null` result captured while the cloud backend was active can
+ // bleed through to the next local visit. Same invariant as
+ // `useUserConversation` and `usePaginatedConversations`.
+ queryKey: ["v1", "sub-conversations", ids, active.backend.id, active.orgId],
queryFn: async () => {
if (ids.length === 0) {
return [];
diff --git a/src/hooks/query/use-user-conversation.ts b/src/hooks/query/use-user-conversation.ts
index 538118312f..ef8815e8d1 100644
--- a/src/hooks/query/use-user-conversation.ts
+++ b/src/hooks/query/use-user-conversation.ts
@@ -3,6 +3,7 @@ import { Query, useQuery } from "@tanstack/react-query";
import { AxiosError } from "axios";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import { useActiveBackend } from "#/contexts/active-backend-context";
const FIVE_MINUTES = 1000 * 60 * 5;
const FIFTEEN_MINUTES = 1000 * 60 * 15;
@@ -19,9 +20,18 @@ type RefetchInterval = (
export const useUserConversation = (
cid: string | null,
refetchInterval?: RefetchInterval,
-) =>
- useQuery({
- queryKey: ["user", "conversation", cid],
+) => {
+ const active = useActiveBackend();
+
+ return useQuery({
+ // Include the active backend identity so each (backend, org) pair
+ // maintains its own per-conversation cache entry. Without this, a
+ // local→cloud→local switch can leave a `null` cached value (from a
+ // refetch that ran while the cloud backend was active) under the
+ // shared cid key, which then makes the conversation route toast
+ // "conversation not available or no permission" until the user
+ // hard-refreshes the page. Mirrors `usePaginatedConversations`.
+ queryKey: ["user", "conversation", cid, active.backend.id, active.orgId],
queryFn: async () => {
if (!cid) return null;
@@ -36,3 +46,4 @@ export const useUserConversation = (
staleTime: FIVE_MINUTES,
gcTime: FIFTEEN_MINUTES,
});
+};