π OpenHands: AI-Driven Development
refactor: remove test-conversation-id fallbacks in websocket context + add state-update tests (#16516)
Mayank Joshi92d5ceff3a93
diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsxindex 98caec8ef7..071cf15cbd 100644--- a/__tests__/contexts/conversation-websocket-context.test.tsx+++ b/__tests__/contexts/conversation-websocket-context.test.tsx@@ -14,6 +14,9 @@ import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-import { useBrowserStore } from "#/stores/browser-store";import { useCommandStore } from "#/stores/command-store";import { useErrorMessageStore } from "#/stores/error-message-store";+import { useConversationStateStore } from "#/stores/conversation-state-store";+import { useGoalStore } from "#/stores/goal-store";+import { ExecutionStatus } from "#/types/agent-server/core";import { useUserConversation } from "#/hooks/query/use-user-conversation";import { useWebSocket } from "#/hooks/use-websocket";import EventService from "#/api/event-service/event-service.api";@@ -35,6 +38,7 @@ const wsCapture = vi.hoisted(() => ({mainOnMessage: null as null | ((event: { data: string }) => void),mainOptions: null as CapturedWebSocketOptions | null,planningOnMessage: null as null | ((event: { data: string }) => void),+ planningOptions: null as CapturedWebSocketOptions | null,calls: [] as Array<{url: string;options?: CapturedWebSocketOptions;@@ -62,6 +66,10 @@ vi.mock("#/hooks/use-websocket", () => ({wsCapture.mainOnMessage = options.onMessage;wsCapture.mainOptions = options;}+ // The planning socket is the only connection the provider opens with+ // `resend_all` (the main socket uses `resend_mode`), so its presence in+ // queryParams is what distinguishes the two captured connections. If the+ // planning params are ever renamed, update this discriminator too.if (url &&options?.onMessage &&@@ -69,6 +77,7 @@ vi.mock("#/hooks/use-websocket", () => ({"resend_all" in options.queryParams) {wsCapture.planningOnMessage = options.onMessage;+ wsCapture.planningOptions = options;}return { socket: null, reconnect: vi.fn() };}),@@ -128,6 +137,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()wsCapture.mainOnMessage = null;wsCapture.mainOptions = null;wsCapture.planningOnMessage = null;+ wsCapture.planningOptions = null;wsCapture.calls.length = 0;window.localStorage.clear();queryClient = new QueryClient({@@ -145,6 +155,8 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()useMetricsStore.getState().resetMetrics();useCommandStore.setState({ commands: [] });useErrorMessageStore.getState().removeErrorMessage();+ useConversationStateStore.getState().reset();+ useGoalStore.setState({ statusByConversation: {} });vi.mocked(useUserConversation).mockReturnValue({data: { conversation_url: "http://localhost/api", session_api_key: null },@@ -758,6 +770,250 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()});});+ // The `isConversationStateUpdateEvent` branches used to carry a bare+ // `// TODO: Tests`. The main socket is covered for every key (`full_state`,+ // `execution_status`, `stats`, `goal`); the planning socket is covered for+ // its duplicated `execution_status` branch, where the conversation-keyed+ // store is what keeps the two conversations from overwriting each other.+ describe("conversation state update events", () => {+ const makeStateUpdate = (key: string, value: unknown) => ({+ id: `evt-state-${key}`,+ timestamp: new Date().toISOString(),+ source: "environment" as const,+ kind: "ConversationStateUpdateEvent",+ key,+ value,+ });++ const renderMainCaptured = async (conversationId: string) => {+ render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId={conversationId}+ conversationUrl="http://localhost/api"+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ };++ const deliverMain = (event: unknown) =>+ act(() => {+ wsCapture.mainOnMessage!({ data: JSON.stringify(event) });+ });++ const makePlanningConversation = (id: string): AppConversation => ({+ id,+ created_by_user_id: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ title: "Planner",+ trigger: null,+ pr_number: [],+ llm_model: null,+ metrics: null,+ created_at: "2026-07-28T00:00:00Z",+ updated_at: "2026-07-28T00:00:00Z",+ execution_status: null,+ conversation_url: `http://planner.example/api/conversations/${id}`,+ session_api_key: null,+ sandbox_id: null,+ sub_conversation_ids: [],+ });++ it("sets execution status from a full_state update", async () => {+ await renderMainCaptured("conv-state");++ deliverMain(+ makeStateUpdate("full_state", {+ execution_status: ExecutionStatus.RUNNING,+ }),+ );++ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-state"+ ],+ ).toBe(ExecutionStatus.RUNNING);+ });++ it("sets execution status from an execution_status update", async () => {+ await renderMainCaptured("conv-state");++ deliverMain(makeStateUpdate("execution_status", ExecutionStatus.PAUSED));++ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-state"+ ],+ ).toBe(ExecutionStatus.PAUSED);+ });++ it("updates the metrics store from a stats update", async () => {+ await renderMainCaptured("conv-state");++ deliverMain(+ makeStateUpdate("stats", {+ usage_to_metrics: {+ default: {+ model_name: "gpt-4o",+ accumulated_cost: 1.25,+ max_budget_per_task: 10,+ accumulated_token_usage: {+ model: "gpt-4o",+ prompt_tokens: 100,+ completion_tokens: 50,+ cache_read_tokens: 10,+ cache_write_tokens: 5,+ reasoning_tokens: 0,+ context_window: 128_000,+ per_turn_token: 500,+ response_id: "resp-1",+ },+ costs: [],+ response_latencies: [],+ token_usages: [],+ },+ },+ }),+ );++ const metrics = useMetricsStore.getState();+ expect(metrics.cost).toBe(1.25);+ expect(metrics.max_budget_per_task).toBe(10);+ expect(metrics.usage).toMatchObject({+ prompt_tokens: 100,+ completion_tokens: 50,+ cache_read_tokens: 10,+ cache_write_tokens: 5,+ context_window: 128_000,+ per_turn_token: 500,+ });+ });++ it("mirrors goal status into the goal store keyed by conversation", async () => {+ await renderMainCaptured("conv-state");++ const goalStatus = {+ active: true,+ status: "running" as const,+ iteration: 1,+ max_iterations: 5,+ objective: "Fix the bug",+ verdict: null,+ };+ deliverMain(makeStateUpdate("goal", goalStatus));++ expect(+ useGoalStore.getState().statusByConversation["conv-state"],+ ).toEqual(goalStatus);+ });++ it("scopes cache invalidation to the main conversation id", async () => {+ await renderMainCaptured("conv-main");+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");++ deliverMain({+ id: "evt-action-1",+ timestamp: new Date().toISOString(),+ source: "agent",+ thought: [],+ thinking_blocks: [],+ action: { kind: "ExecuteBashAction", command: "echo hi" },+ tool_name: "execute_bash",+ tool_call_id: "call-1",+ });++ expect(invalidateSpy).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "conv-main"] },+ { cancelRefetch: false },+ );+ });++ it("scopes cache invalidation to the planning sub-conversation id", async () => {+ const planningConversation = makePlanningConversation("planning-cache");++ render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost/api"+ subConversationIds={[planningConversation.id]}+ subConversations={[planningConversation]}+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ await waitFor(() => expect(wsCapture.planningOnMessage).not.toBeNull());++ // Sanity-check the captured planning socket before delivering events:+ // it must be the planning connection (resend_all) so the invalidation+ // below is provably scoped by the sub-conversation id, not the main one.+ expect(wsCapture.planningOptions?.queryParams).toEqual({+ resend_all: true,+ });++ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");++ act(() => {+ wsCapture.planningOnMessage!({+ data: JSON.stringify({+ id: "evt-plan-action-1",+ timestamp: new Date().toISOString(),+ source: "agent",+ thought: [],+ thinking_blocks: [],+ action: { kind: "ExecuteBashAction", command: "echo hi" },+ tool_name: "execute_bash",+ tool_call_id: "call-plan-1",+ }),+ });+ });++ expect(invalidateSpy).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "planning-cache"] },+ { cancelRefetch: false },+ );+ });++ it("keys a planning execution_status update to the planning conversation", async () => {+ const planningConversation = makePlanningConversation("planning-state");++ render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost/api"+ subConversationIds={[planningConversation.id]}+ subConversations={[planningConversation]}+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ await waitFor(() => expect(wsCapture.planningOnMessage).not.toBeNull());++ act(() => {+ wsCapture.planningOnMessage!({+ data: JSON.stringify(+ makeStateUpdate("execution_status", ExecutionStatus.PAUSED),+ ),+ });+ });++ const { executionStatusByConversation } =+ useConversationStateStore.getState();+ expect(executionStatusByConversation["planning-state"]).toBe(+ ExecutionStatus.PAUSED,+ );+ expect(executionStatusByConversation["conv-main"]).toBeUndefined();+ });+ });+it("clears the previous conversation's events when switching conversations", async () => {// Arrange + Act: open conversation A.const { rerender } = renderProvider("conv-a");diff --git a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsxindex 59acdc3f39..dc8c0594cc 100644--- a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx+++ b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx@@ -1459,7 +1459,9 @@ describe("Conversation websocket behavior", () => {).toHaveLength(1);expect(consumeMatchingPendingMessage).not.toHaveBeenCalled();expect(useGoalStore.getState().statusByConversation).toEqual({});- expect(invalidateQueries).toHaveBeenCalledWith(+ // Without a conversation identity there is nothing to invalidate: the+ // handler is skipped outright rather than aimed at a placeholder key.+ expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ["file_changes", "test-conversation-id"] },{ cancelRefetch: false },);@@ -2165,7 +2167,9 @@ describe("Conversation websocket behavior", () => {planningOptions().onMessage?.({ data: "not-json" } as MessageEvent),);- expect(invalidateQueries).toHaveBeenCalledWith(+ // Without a conversation identity there is nothing to invalidate: the+ // handler is skipped outright rather than aimed at a placeholder key.+ expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ["file_changes", "test-conversation-id"] },{ cancelRefetch: false },);diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex 8cf712ec5b..32cd815627 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -636,19 +636,18 @@ export function ConversationWebSocketProvider({}}- // Handle cache invalidation for ActionEvent- if (isActionEvent(event)) {- const currentConversationId =- conversationId || "test-conversation-id"; // TODO: Get from context+ // Handle cache invalidation for ActionEvent. The main WebSocket only+ // opens when `conversationId` is present (see `wsUrl` below), so it+ // is always defined for events arriving over this socket.+ if (isActionEvent(event) && conversationId) {handleActionEventCacheInvalidation(event,- currentConversationId,+ conversationId,queryClient,);}// Handle conversation state updates- // TODO: Testsif (isConversationStateUpdateEvent(event)) {if (isFullStateConversationStateUpdateEvent(event) &&@@ -869,20 +868,21 @@ export function ConversationWebSocketProvider({}}- // Handle cache invalidation for ActionEvent+ // Handle cache invalidation for ActionEvent. The planning socket only+ // opens when the first sub-conversation has an id (see+ // `planningAgentWsUrl` below), so it is always defined here.if (isActionEvent(event)) {const planningAgentConversation = subConversations?.[0];- const currentConversationId =- planningAgentConversation?.id || "test-conversation-id"; // TODO: Get from context- handleActionEventCacheInvalidation(- event,- currentConversationId,- queryClient,- );+ if (planningAgentConversation?.id) {+ handleActionEventCacheInvalidation(+ event,+ planningAgentConversation.id,+ queryClient,+ );+ }}// Handle conversation state updates- // TODO: Testsif (isConversationStateUpdateEvent(event)) {// Scope to the planning agent's own conversation id, not the main// `conversationId` β this socket reports the planning helper