π OpenHands: AI-Driven Development
test: preserve unrelated conversation caches (#17337)
aivong-openhands905d1066af9b
diff --git a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts b/__tests__/hooks/mutation/conversation-mutation-utils.test.tsindex de45b1c4bc..a1f4bb40b7 100644--- a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts+++ b/__tests__/hooks/mutation/conversation-mutation-utils.test.ts@@ -1,25 +1,73 @@-/**- * Tests for patchConversationInCache and updateConversationExecutionStatusInCache- * in conversation-mutation-utils.ts.- *- * These functions are the mechanism that keeps the React Query cache in sync- * with optimistic UI updates after stop/resume mutations. The most critical- * invariant is that after pauseConversation succeeds the cache carries BOTH- * execution_status AND sandbox_status as "PAUSED" β if sandbox_status is not- * updated, WebSocketProviderWrapper's sandbox_status === "PAUSED" gate never- * fires and the WebSocket tries to connect to the dead sandbox.- */-+import type { StartGoalRequest } from "@openhands/typescript-client";+import { ConversationClient } from "@openhands/typescript-client/clients";import { QueryClient } from "@tanstack/react-query";-import { describe, expect, it, beforeEach } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import {+ askAgent,+ invalidateConversationQueries,patchConversationInCache,- updateConversationExecutionStatusInCache,+ pauseConversation,+ resumeConversation,+ resumeGoal,+ startGoal,+ stopGoal,} from "#/hooks/mutation/conversation-mutation-utils";-import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import { ExecutionStatus } from "#/types/agent-server/core/base/common";+const mocks = vi.hoisted(() => ({+ askAgent: vi.fn(),+ batchGetAppConversations: vi.fn(),+ getActiveBackend: vi.fn(),+ getAgentServerClientOptions: vi.fn(),+ interruptConversation: vi.fn(),+ pauseCloudSandbox: vi.fn(),+ resumeGoal: vi.fn(),+ runConversation: vi.fn(),+ startGoal: vi.fn(),+ stopGoal: vi.fn(),+}));++vi.mock("@openhands/typescript-client/clients", () => ({+ ConversationClient: vi.fn(function ConversationClientMock() {+ return {+ askAgent: mocks.askAgent,+ interruptConversation: mocks.interruptConversation,+ resumeGoal: mocks.resumeGoal,+ runConversation: mocks.runConversation,+ startGoal: mocks.startGoal,+ stopGoal: mocks.stopGoal,+ };+ }),+}));++vi.mock("#/api/backend-registry/active-store", () => ({+ getActiveBackend: mocks.getActiveBackend,+}));++vi.mock("#/api/cloud/conversation-service.api", () => ({+ pauseCloudSandbox: mocks.pauseCloudSandbox,+}));++vi.mock("#/api/agent-server-client-options", () => ({+ getAgentServerClientOptions: mocks.getAgentServerClientOptions,+}));++vi.mock(+ "#/api/conversation-service/agent-server-conversation-service.api",+ () => ({+ default: {+ batchGetAppConversations: mocks.batchGetAppConversations,+ },+ }),+);+const CONV_ID = "conv-test-1";+const CLIENT_OPTIONS = {+ host: "https://runtime.example.com",+ apiKey: "runtime-session-key",+ workingDir: "/workspace/project",+};const makeConversation = (overrides: Partial<AppConversation> = {},@@ -37,130 +85,332 @@ const makeConversation = (created_at: "2024-01-01T00:00:00Z",updated_at: "2024-01-01T00:00:00Z",execution_status: null,- conversation_url: "https://sandbox.example.com/api/conversations/conv-test-1",- session_api_key: "sess-key",- sandbox_id: "sbx-1",+ conversation_url: "https://runtime.example.com/api/conversations/conv-test-1",+ session_api_key: "runtime-session-key",+ sandbox_id: "sandbox-1",sandbox_status: "RUNNING",sub_conversation_ids: [],...overrides,});-let queryClient: QueryClient;--beforeEach(() => {- queryClient = new QueryClient({+const makeQueryClient = () =>+ new QueryClient({defaultOptions: { queries: { retry: false } },});++const loadFreshConversationMutationUtils = async () => {+ vi.resetModules();+ return import("#/hooks/mutation/conversation-mutation-utils");+};++const prepareRuntimeConversation = (+ overrides: Partial<AppConversation> = {},+) => {+ const conversation = makeConversation(overrides);+ mocks.batchGetAppConversations.mockResolvedValueOnce([conversation]);+ mocks.getAgentServerClientOptions.mockReturnValue(CLIENT_OPTIONS);+ return conversation;+};++const expectRuntimeClient = (+ conversationId: string,+ conversation: AppConversation,+) => {+ expect(mocks.batchGetAppConversations).toHaveBeenCalledOnce();+ expect(mocks.batchGetAppConversations).toHaveBeenCalledWith([conversationId]);+ expect(mocks.getAgentServerClientOptions).toHaveBeenCalledOnce();+ expect(mocks.getAgentServerClientOptions).toHaveBeenCalledWith({+ conversationUrl: conversation.conversation_url,+ sessionApiKey: conversation.session_api_key,+ });+ expect(ConversationClient).toHaveBeenCalledOnce();+ expect(ConversationClient).toHaveBeenCalledWith(CLIENT_OPTIONS);+};++afterEach(() => {+ vi.clearAllMocks();});-// βββ patchConversationInCache βββββββββββββββββββββββββββββββββββββββββββββββββ+describe("conversation runtime commands", () => {+ it("reports the requested id when the conversation cannot be loaded", async () => {+ mocks.batchGetAppConversations.mockResolvedValueOnce([]);++ await expect(+ askAgent("missing-conversation", "Are you there?"),+ ).rejects.toThrow("V1 conversation not found: missing-conversation");++ expect(mocks.batchGetAppConversations).toHaveBeenCalledWith([+ "missing-conversation",+ ]);+ expect(mocks.getAgentServerClientOptions).not.toHaveBeenCalled();+ expect(ConversationClient).not.toHaveBeenCalled();+ expect(mocks.askAgent).not.toHaveBeenCalled();+ });++ it("interrupts a local conversation through its runtime client", async () => {+ const conversation = prepareRuntimeConversation();+ const response = { success: true };+ mocks.getActiveBackend.mockReturnValueOnce({+ backend: { kind: "local" },+ });+ mocks.interruptConversation.mockResolvedValueOnce(response);++ await expect(pauseConversation(CONV_ID)).resolves.toBe(response);-describe("patchConversationInCache", () => {- it("patches the single-item conversation cache", () => {- queryClient.setQueryData(- ["user", "conversation", CONV_ID],- makeConversation({ sandbox_status: "RUNNING" }),+ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.interruptConversation).toHaveBeenCalledOnce();+ expect(mocks.interruptConversation).toHaveBeenCalledWith(CONV_ID);+ expect(mocks.pauseCloudSandbox).not.toHaveBeenCalled();+ });++ it("pauses a cloud sandbox without constructing a runtime client", async () => {+ prepareRuntimeConversation({ sandbox_id: "sandbox-cloud-7" });+ mocks.getActiveBackend.mockReturnValueOnce({+ backend: { kind: "cloud" },+ });+ mocks.pauseCloudSandbox.mockResolvedValueOnce(undefined);++ await expect(pauseConversation(CONV_ID)).resolves.toEqual({+ success: true,+ });++ expect(mocks.pauseCloudSandbox).toHaveBeenCalledOnce();+ expect(mocks.pauseCloudSandbox).toHaveBeenCalledWith("sandbox-cloud-7");+ expect(mocks.getAgentServerClientOptions).not.toHaveBeenCalled();+ expect(ConversationClient).not.toHaveBeenCalled();+ expect(mocks.interruptConversation).not.toHaveBeenCalled();+ });++ it("rejects a cloud pause when the conversation has no sandbox", async () => {+ prepareRuntimeConversation({ sandbox_id: null });+ mocks.getActiveBackend.mockReturnValueOnce({+ backend: { kind: "cloud" },+ });++ await expect(pauseConversation(CONV_ID)).rejects.toThrow(+ `Cannot stop runtime: cloud conversation ${CONV_ID} has no sandbox_id.`,);- patchConversationInCache(queryClient, CONV_ID, { sandbox_status: "PAUSED" });+ expect(mocks.pauseCloudSandbox).not.toHaveBeenCalled();+ expect(mocks.getAgentServerClientOptions).not.toHaveBeenCalled();+ expect(ConversationClient).not.toHaveBeenCalled();+ });++ it("asks the runtime agent the exact side question", async () => {+ const conversation = prepareRuntimeConversation();+ const response = { response: "The build is green." };+ mocks.askAgent.mockResolvedValueOnce(response);- const cached = queryClient.getQueryData<AppConversation>([- "user",- "conversation",+ await expect(askAgent(CONV_ID, "What is the build status?")).resolves.toBe(+ response,+ );++ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.askAgent).toHaveBeenCalledOnce();+ expect(mocks.askAgent).toHaveBeenCalledWith(CONV_ID,- ]);- expect(cached?.sandbox_status).toBe("PAUSED");+ "What is the build status?",+ );+ });++ it("starts a goal with the complete request", async () => {+ const conversation = prepareRuntimeConversation();+ const request: StartGoalRequest = {+ objective: "Finish the focused test suite",+ max_iterations: 4,+ };+ mocks.startGoal.mockResolvedValueOnce(undefined);++ await expect(startGoal(CONV_ID, request)).resolves.toBeUndefined();++ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.startGoal).toHaveBeenCalledOnce();+ expect(mocks.startGoal).toHaveBeenCalledWith(CONV_ID, request);+ });++ it("stops the active goal for the requested conversation", async () => {+ const conversation = prepareRuntimeConversation();+ mocks.stopGoal.mockResolvedValueOnce(undefined);++ await expect(stopGoal(CONV_ID)).resolves.toBeUndefined();++ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.stopGoal).toHaveBeenCalledOnce();+ expect(mocks.stopGoal).toHaveBeenCalledWith(CONV_ID);});- it("patches conversation inside the paginated list cache", () => {- queryClient.setQueryData(["user", "conversations"], {- pages: [{ items: [makeConversation({ sandbox_status: "RUNNING" })] }],- pageParams: [],+ it("resumes the interrupted goal for the requested conversation", async () => {+ const conversation = prepareRuntimeConversation();+ mocks.resumeGoal.mockResolvedValueOnce(undefined);++ await expect(resumeGoal(CONV_ID)).resolves.toBeUndefined();++ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.resumeGoal).toHaveBeenCalledOnce();+ expect(mocks.resumeGoal).toHaveBeenCalledWith(CONV_ID);+ });++ it("runs a paused conversation through its runtime client", async () => {+ const conversation = prepareRuntimeConversation();+ const response = { status: "running" };+ mocks.runConversation.mockResolvedValueOnce(response);++ await expect(resumeConversation(CONV_ID)).resolves.toBe(response);++ expectRuntimeClient(CONV_ID, conversation);+ expect(mocks.runConversation).toHaveBeenCalledOnce();+ expect(mocks.runConversation).toHaveBeenCalledWith(CONV_ID);+ });+});++describe("conversation cache synchronization", () => {+ it("patches the matching single-item cache across backend key variants", () => {+ const queryClient = makeQueryClient();+ const queryKey = ["user", "conversation", CONV_ID, "backend-local", null];+ const conversation = makeConversation({ sandbox_status: "RUNNING" });+ queryClient.setQueryData(queryKey, conversation);++ patchConversationInCache(queryClient, CONV_ID, {+ sandbox_status: "PAUSED",});- patchConversationInCache(queryClient, CONV_ID, { sandbox_status: "PAUSED" });+ expect(queryClient.getQueryData(queryKey)).toEqual({+ ...conversation,+ sandbox_status: "PAUSED",+ });+ });++ it("does not alter unrelated query families", () => {+ const queryClient = makeQueryClient();+ const unrelatedKey = ["settings", "conversation"];+ const unrelatedData = {+ activeProfile: "default",+ confirmationPolicy: "never",+ };+ queryClient.setQueryData(unrelatedKey, unrelatedData);++ patchConversationInCache(queryClient, CONV_ID, {+ sandbox_status: "PAUSED",+ });- const list = queryClient.getQueryData<{- pages: Array<{ items: AppConversation[] }>;- }>(["user", "conversations"]);- expect(list?.pages[0]?.items[0]?.sandbox_status).toBe("PAUSED");+ expect(queryClient.getQueryData(unrelatedKey)).toBe(unrelatedData);});- it("patches multiple fields atomically", () => {- queryClient.setQueryData(- ["user", "conversation", CONV_ID],- makeConversation({- execution_status: ExecutionStatus.RUNNING,- sandbox_status: "RUNNING",- }),- );+ it("patches every matching list item while preserving pages and other conversations", () => {+ const queryClient = makeQueryClient();+ const queryKey = ["user", "conversations", "backend-local", null];+ const firstMatch = makeConversation({ title: "First match" });+ const secondMatch = makeConversation({ title: "Second match" });+ const other = makeConversation({ id: "conv-other", title: "Other" });+ const firstPage = { items: [firstMatch, other], next_page_id: "page-2" };+ const secondPage = { items: [secondMatch], next_page_id: null };+ queryClient.setQueryData(queryKey, {+ pages: [firstPage, secondPage],+ pageParams: [null, "page-2"],+ });patchConversationInCache(queryClient, CONV_ID, {execution_status: ExecutionStatus.PAUSED,sandbox_status: "PAUSED",});- const cached = queryClient.getQueryData<AppConversation>([- "user",- "conversation",- CONV_ID,- ]);- expect(cached?.execution_status).toBe(ExecutionStatus.PAUSED);- expect(cached?.sandbox_status).toBe("PAUSED");+ const cached = queryClient.getQueryData<{+ pages: Array<{ items: AppConversation[]; next_page_id: string | null }>;+ pageParams: Array<string | null>;+ }>(queryKey);+ expect(cached?.pages[0]).toEqual({+ ...firstPage,+ items: [+ {+ ...firstMatch,+ execution_status: ExecutionStatus.PAUSED,+ sandbox_status: "PAUSED",+ },+ other,+ ],+ });+ expect(cached?.pages[1]).toEqual({+ ...secondPage,+ items: [+ {+ ...secondMatch,+ execution_status: ExecutionStatus.PAUSED,+ sandbox_status: "PAUSED",+ },+ ],+ });+ expect(cached?.pages[0]?.items[1]).toBe(other);+ expect(cached?.pageParams).toEqual([null, "page-2"]);});- it("does not modify other conversations in the list", () => {- const other = makeConversation({- id: "conv-other",- sandbox_status: "RUNNING",+ it("leaves registered caches without data empty", () => {+ const queryClient = makeQueryClient();+ const conversationKey = ["user", "conversation", CONV_ID];+ const conversationsKey = ["user", "conversations"];+ queryClient.getQueryCache().build(queryClient, {+ queryKey: conversationKey,});- queryClient.setQueryData(["user", "conversations"], {- pages: [{ items: [makeConversation(), other] }],- pageParams: [],+ queryClient.getQueryCache().build(queryClient, {+ queryKey: conversationsKey,});- patchConversationInCache(queryClient, CONV_ID, { sandbox_status: "PAUSED" });+ patchConversationInCache(queryClient, CONV_ID, {+ sandbox_status: "PAUSED",+ });- const list = queryClient.getQueryData<{- pages: Array<{ items: AppConversation[] }>;- }>(["user", "conversations"]);- const otherCached = list?.pages[0]?.items.find((c) => c.id === "conv-other");- expect(otherCached?.sandbox_status).toBe("RUNNING");+ expect(queryClient.getQueryState(conversationKey)?.data).toBeUndefined();+ expect(queryClient.getQueryState(conversationsKey)?.data).toBeUndefined();});- it("is a no-op when the single-item cache is empty", () => {- // No query data seeded β should not throw.- expect(() =>- patchConversationInCache(queryClient, CONV_ID, { sandbox_status: "PAUSED" }),- ).not.toThrow();+ it("updates execution status without disturbing other cached fields", async () => {+ const { updateConversationExecutionStatusInCache: updateExecutionStatus } =+ await loadFreshConversationMutationUtils();+ const queryClient = makeQueryClient();+ const queryKey = ["user", "conversation", CONV_ID];+ const conversation = makeConversation({+ execution_status: ExecutionStatus.RUNNING,+ sandbox_status: "RUNNING",+ });+ queryClient.setQueryData(queryKey, conversation);++ updateExecutionStatus(queryClient, CONV_ID, ExecutionStatus.PAUSED);++ expect(queryClient.getQueryData(queryKey)).toEqual({+ ...conversation,+ execution_status: ExecutionStatus.PAUSED,+ });});-});-// βββ updateConversationExecutionStatusInCache (backwards compat wrapper) βββββ+ it("updates the LLM model without disturbing other cached fields", async () => {+ const { updateConversationLlmModelInCache: updateLlmModel } =+ await loadFreshConversationMutationUtils();+ const queryClient = makeQueryClient();+ const queryKey = ["user", "conversation", CONV_ID];+ const conversation = makeConversation({+ llm_model: "provider/old-model",+ sandbox_status: "RUNNING",+ });+ queryClient.setQueryData(queryKey, conversation);-describe("updateConversationExecutionStatusInCache", () => {- it("updates execution_status without disturbing sandbox_status", () => {- queryClient.setQueryData(- ["user", "conversation", CONV_ID],- makeConversation({- execution_status: ExecutionStatus.RUNNING,- sandbox_status: "RUNNING",- }),- );+ updateLlmModel(queryClient, CONV_ID, "provider/new-model");- updateConversationExecutionStatusInCache(- queryClient,- CONV_ID,- ExecutionStatus.PAUSED,- );+ expect(queryClient.getQueryData(queryKey)).toEqual({+ ...conversation,+ llm_model: "provider/new-model",+ });+ });- const cached = queryClient.getQueryData<AppConversation>([- "user",- "conversation",- CONV_ID,+ it("invalidates every conversation-dependent query family", () => {+ const queryClient = makeQueryClient();+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");++ expect(invalidateConversationQueries(queryClient, CONV_ID)).toBeUndefined();++ expect(invalidateQueries.mock.calls).toEqual([+ [{ queryKey: ["user", "conversation", CONV_ID] }],+ [{ queryKey: ["user", "conversations"] }],+ [{ queryKey: ["v1-batch-get-app-conversations"] }],+ [{ queryKey: ["unified", "vscode_url"] }],]);- expect(cached?.execution_status).toBe(ExecutionStatus.PAUSED);- // sandbox_status must remain unchanged β this wrapper only touches execution_status- expect(cached?.sandbox_status).toBe("RUNNING");});});