π OpenHands: AI-Driven Development
test: strengthen conversation websocket runtime (#17351)
aivong-openhands53bb808b5fae
diff --git a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsxnew file mode 100644index 0000000000..59acdc3f39--- /dev/null+++ b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx@@ -0,0 +1,2180 @@+import React from "react";+import { act, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ ConversationWebSocketProvider,+ useConversationWebSocket,+} from "#/contexts/conversation-websocket-context";+import type { WebSocketHookOptions } from "#/hooks/use-websocket";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";+import type { MessageEvent as AgentMessageEvent } from "#/types/agent-server/core/events/message-event";+import type { OpenHandsEvent } from "#/types/agent-server/core";+import { useEventStore } from "#/stores/use-event-store";+import { useErrorMessageStore } from "#/stores/error-message-store";+import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";+import { useConversationStateStore } from "#/stores/conversation-state-store";+import { useConversationStore } from "#/stores/conversation-store";+import { useCommandStore } from "#/stores/command-store";+import { useBrowserStore } from "#/stores/browser-store";+import { useGoalStore } from "#/stores/goal-store";+import { useModelStore } from "#/stores/model-store";+import useMetricsStore from "#/stores/metrics-store";+import { useFilesTabStore } from "#/stores/files-tab-store";+import EventService from "#/api/event-service/event-service.api";+import { SERVER_CONNECTION_ERROR_MESSAGE } from "#/constants/server-connection-error";+import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";+import {+ getConversationState,+ setConversationState,+} from "#/utils/conversation-local-storage";++interface TestSocket {+ readonly readyState: number;+ send: WebSocket["send"];+}++const socketCapture = vi.hoisted(() => ({+ callIndex: 0,+ mainUrl: "",+ planningUrl: "",+ mainOptions: null as WebSocketHookOptions | null,+ planningOptions: null as WebSocketHookOptions | null,+ mainSocket: null as TestSocket | null,+ planningSocket: null as TestSocket | null,+ reconnectMain: vi.fn(),+ reconnectPlanning: vi.fn(),+ queueMessage: vi.fn(),+ readConversationFile: vi.fn(),+ trackError: vi.fn(),+ launchChild: vi.fn(),+}));++const historyCapture = vi.hoisted(() => ({+ result: {+ data: { events: [] as OpenHandsEvent[] } as+ | { events: OpenHandsEvent[] }+ | undefined,+ isPending: false,+ isFetching: false,+ isError: false,+ },+}));++vi.mock("#/hooks/use-websocket", () => ({+ useWebSocket: vi.fn((url: string, options?: WebSocketHookOptions) => {+ const isMain = socketCapture.callIndex % 2 === 0;+ socketCapture.callIndex += 1;++ if (isMain) {+ socketCapture.mainUrl = url;+ socketCapture.mainOptions = options ?? null;+ return {+ socket: socketCapture.mainSocket,+ reconnect: socketCapture.reconnectMain,+ };+ }++ socketCapture.planningUrl = url;+ socketCapture.planningOptions = options ?? null;+ return {+ socket: socketCapture.planningSocket,+ reconnect: socketCapture.reconnectPlanning,+ };+ }),+}));++vi.mock("#/hooks/query/use-conversation-history", () => ({+ useConversationHistory: () => historyCapture.result,+}));++vi.mock("#/hooks/mutation/use-read-conversation-file", () => ({+ useReadConversationFile: () => ({+ mutate: socketCapture.readConversationFile,+ }),+}));++vi.mock("#/services/child-conversation-launch", () => ({+ handleLaunchChildConversationAction: (...args: unknown[]) =>+ socketCapture.launchChild(...args),+}));++vi.mock("#/utils/error-handler", () => ({+ trackError: (...args: unknown[]) => socketCapture.trackError(...args),+}));++vi.mock("#/api/agent-server-client-options", () => ({+ getAgentServerClientOptions: () => ({ baseUrl: "http://agent-server.test" }),+}));++vi.mock("@openhands/typescript-client/clients", () => ({+ ConversationClient: class ConversationClient {+ sendEvent(...args: unknown[]) {+ return socketCapture.queueMessage(...args);+ }+ },+}));++const contextCapture: {+ current: ReturnType<typeof useConversationWebSocket>;+} = { current: null };++function ContextProbe() {+ const context = useConversationWebSocket();+ contextCapture.current = context;++ return (+ <>+ <div data-testid="connection-state">{context?.connectionState}</div>+ <div data-testid="loading-history">+ {String(context?.isLoadingHistory)}+ </div>+ </>+ );+}++type ProviderProps = Omit<+ React.ComponentProps<typeof ConversationWebSocketProvider>,+ "children"+>;++function renderProvider(overrides: Partial<ProviderProps> = {}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const props: ProviderProps = {+ conversationId: "conv-main",+ conversationUrl: "http://localhost:8000/api/conversations/conv-main",+ ...overrides,+ };++ const view = render(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider {...props}>+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ return { ...view, queryClient };+}++function makeSocket(readyState: number = WebSocket.OPEN): TestSocket {+ return {+ readyState,+ send: vi.fn(),+ };+}++const makeSendRequest = (text: string) => ({+ role: "user" as const,+ content: [{ type: "text" as const, text }],+});++function makeSubConversation(+ overrides: Partial<AppConversation> = {},+): AppConversation {+ return {+ id: "conv-planning",+ created_by_user_id: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ title: "Planning",+ trigger: null,+ pr_number: [],+ llm_model: null,+ metrics: null,+ created_at: "2024-01-01T00:00:00.000Z",+ updated_at: "2024-01-01T00:00:00.000Z",+ execution_status: null,+ conversation_url: "http://localhost:8000/api/conversations/conv-planning",+ session_api_key: "planning-key",+ sandbox_id: null,+ sub_conversation_ids: [],+ ...overrides,+ };+}++const baseEvent = (+ id: string,+ source: "agent" | "user" | "environment" = "environment",+) => ({+ id,+ timestamp: `2024-01-01T00:00:${id.padStart(2, "0")}.000Z`,+ source,+});++function makeMessageEvent(+ id: string,+ role: "user" | "assistant",+ textParts: string[],+): OpenHandsEvent {+ return {+ ...baseEvent(id, role === "user" ? "user" : "agent"),+ llm_message: {+ role,+ content: textParts.flatMap<+ AgentMessageEvent["llm_message"]["content"][number]+ >((text, index) =>+ index === 0+ ? [+ {+ type: "image" as const,+ image_urls: ["data:image/png;base64,AA"],+ },+ { type: "text" as const, text },+ ]+ : [{ type: "text" as const, text }],+ ),+ },+ activated_skills: [],+ extended_content: [],+ } as OpenHandsEvent;+}++function makeActionEvent(+ id: string,+ action: Record<string, unknown>,+ toolName = "execute_bash",+): OpenHandsEvent {+ return {+ ...baseEvent(id, "agent"),+ thought: [],+ thinking_blocks: [],+ action,+ tool_name: toolName,+ tool_call_id: `call-${id}`,+ tool_call: {+ id: `call-${id}`,+ type: "function",+ function: { name: toolName, arguments: "{}" },+ },+ llm_response_id: `response-${id}`,+ security_risk: "UNKNOWN",+ } as OpenHandsEvent;+}++function makeObservationEvent(+ id: string,+ observation: Record<string, unknown>,+ toolName = "execute_bash",+): OpenHandsEvent {+ return {+ ...baseEvent(id),+ action_id: `action-${id}`,+ tool_name: toolName,+ tool_call_id: `call-${id}`,+ observation,+ } as OpenHandsEvent;+}++function makeStateEvent(+ id: string,+ key: "full_state" | "execution_status" | "stats" | "goal",+ value: unknown,+): OpenHandsEvent {+ return {+ ...baseEvent(id),+ kind: "ConversationStateUpdateEvent",+ key,+ value,+ } as OpenHandsEvent;+}++function mainOptions(): WebSocketHookOptions {+ expect(socketCapture.mainOptions).not.toBeNull();+ return socketCapture.mainOptions!;+}++function planningOptions(): WebSocketHookOptions {+ expect(socketCapture.planningOptions).not.toBeNull();+ return socketCapture.planningOptions!;+}++function dispatchMain(event: unknown) {+ act(() => {+ mainOptions().onMessage?.({ data: JSON.stringify(event) } as MessageEvent);+ });+}++function dispatchPlanning(event: unknown) {+ act(() => {+ planningOptions().onMessage?.({+ data: JSON.stringify(event),+ } as MessageEvent);+ });+}++describe("Conversation websocket behavior", () => {+ beforeEach(() => {+ socketCapture.callIndex = 0;+ socketCapture.mainUrl = "";+ socketCapture.planningUrl = "";+ socketCapture.mainOptions = null;+ socketCapture.planningOptions = null;+ socketCapture.mainSocket = null;+ socketCapture.planningSocket = null;+ socketCapture.reconnectMain.mockReset();+ socketCapture.reconnectPlanning.mockReset();+ socketCapture.queueMessage.mockReset().mockResolvedValue(undefined);+ socketCapture.readConversationFile.mockReset();+ socketCapture.trackError.mockReset();+ socketCapture.launchChild.mockReset().mockResolvedValue(undefined);+ historyCapture.result = {+ data: { events: [] },+ isPending: false,+ isFetching: false,+ isError: false,+ };+ contextCapture.current = null;++ window.localStorage.clear();+ useEventStore.setState({+ events: [],+ eventIds: new Set(),+ uiEvents: [],+ loadedConversationId: null,+ });+ useErrorMessageStore.getState().removeErrorMessage();+ useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useConversationStateStore.getState().reset();+ useConversationStore.setState({+ conversationMode: "code",+ planContent: null,+ });+ useCommandStore.getState().clearTerminal();+ useBrowserStore.getState().reset();+ useGoalStore.setState({ statusByConversation: {} });+ useModelStore.getState().clearAll();+ useMetricsStore.setState({+ cost: null,+ max_budget_per_task: null,+ usage: null,+ });+ useFilesTabStore.setState({+ selectedPath: null,+ selectedConversationId: null,+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+ });++ it("returns no websocket API outside the provider", () => {+ render(<ContextProbe />);++ expect(contextCapture.current).toBeNull();+ });++ it("hydrates history, consumes matching optimistic messages, and subscribes after the latest event", async () => {+ const first = makeMessageEvent("01", "assistant", ["first"]);+ const latest = makeMessageEvent("02", "user", ["hello", " world"]);+ historyCapture.result.data = { events: [first, latest] };+ const consumeMatchingPendingMessage = vi.spyOn(+ useOptimisticUserMessageStore.getState(),+ "consumeMatchingPendingMessage",+ );+ useOptimisticUserMessageStore.setState({+ pendingMessages: [+ {+ id: "pending-decoy",+ conversationId: "conv-main",+ text: "different message",+ content: "different message",+ status: "sending",+ imageUrls: [],+ fileUrls: [],+ timestamp: "2024-01-01T00:00:00.000Z",+ },+ {+ id: "pending-1",+ conversationId: "conv-main",+ text: "hello world",+ content: "hello world",+ status: "sending",+ imageUrls: [],+ fileUrls: [],+ timestamp: "2024-01-01T00:00:00.000Z",+ },+ ],+ });++ renderProvider({ sessionApiKey: "session-key" });++ await waitFor(() =>+ expect(useEventStore.getState().events).toHaveLength(2),+ );+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual([+ expect.objectContaining({ id: "pending-decoy" }),+ ]);+ expect(consumeMatchingPendingMessage).toHaveBeenCalledOnce();+ expect(consumeMatchingPendingMessage).toHaveBeenCalledWith(+ "conv-main",+ "hello world",+ );+ expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");+ // The session key is now passed via the dedicated `sessionApiKey` option+ // rather than folded into the query string.+ expect(mainOptions().queryParams).toEqual({+ resend_mode: "since",+ after_timestamp: latest.timestamp,+ });+ expect(mainOptions().sessionApiKey).toBe("session-key");+ expect(planningOptions().queryParams).toEqual({+ resend_all: true,+ });+ expect(planningOptions().sessionApiKey).toBe("session-key");+ expect(mainOptions().reconnect).toEqual({ enabled: true });+ expect(planningOptions().reconnect).toEqual({ enabled: true });+ });++ it("waits for the first history load before opening the main socket", () => {+ // The socket gate keys on `isPending` (the genuine first load with no+ // cached data) rather than `isFetching`, so background refetches never+ // tear down a live socket. During that first load the URL stays blank.+ historyCapture.result.data = undefined;+ historyCapture.result.isPending = true;++ renderProvider();++ expect(socketCapture.mainUrl).toBe("");+ expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "CONNECTING",+ );+ });++ it("shows first-load history only for a selected conversation", () => {+ historyCapture.result.isPending = true;++ const selected = renderProvider();+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");+ selected.unmount();++ socketCapture.callIndex = 0;+ renderProvider({ conversationId: undefined });+ expect(screen.getByTestId("loading-history")).toHaveTextContent("false");+ });++ it("falls back to an all-events socket when history loading fails", () => {+ historyCapture.result.isFetching = true;+ historyCapture.result.isError = true;++ renderProvider();++ expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");+ expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ });++ it("does not build socket URLs without complete conversation coordinates", () => {+ const missingBoth = renderProvider({+ conversationId: undefined,+ conversationUrl: null,+ });++ expect(socketCapture.mainUrl).toBe("");+ expect(socketCapture.planningUrl).toBe("");+ expect(useEventStore.getState().loadedConversationId).toBeNull();+ missingBoth.unmount();++ socketCapture.callIndex = 0;+ const missingUrl = renderProvider({ conversationUrl: null });+ expect(socketCapture.mainUrl).toBe("");+ missingUrl.unmount();++ socketCapture.callIndex = 0;+ renderProvider({+ conversationId: undefined,+ conversationUrl: "http://localhost:8000/api/conversations/conv-main",+ });+ expect(socketCapture.mainUrl).toBe("");+ });++ it("accepts absent history and history without a selected conversation", () => {+ const addEvents = vi.spyOn(useEventStore.getState(), "addEvents");+ const empty = renderProvider();+ expect(addEvents).not.toHaveBeenCalled();+ empty.unmount();++ socketCapture.callIndex = 0;+ historyCapture.result.data = undefined;+ const first = renderProvider();+ expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ expect(addEvents).not.toHaveBeenCalled();+ first.unmount();++ socketCapture.callIndex = 0;+ const consumeMatchingPendingMessage = vi.spyOn(+ useOptimisticUserMessageStore.getState(),+ "consumeMatchingPendingMessage",+ );+ historyCapture.result.data = {+ events: [makeMessageEvent("04", "user", ["unscoped history"])],+ };+ renderProvider({ conversationId: undefined });+ expect(useEventStore.getState().events).toHaveLength(1);+ expect(consumeMatchingPendingMessage).not.toHaveBeenCalled();+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual(+ [],+ );+ });++ it("clears conversation-owned stores once per conversation identity", () => {+ useEventStore+ .getState()+ .addEvent(makeMessageEvent("05", "assistant", ["old conversation"]));+ useEventStore.setState({ loadedConversationId: "conv-old" });+ useBrowserStore.getState().setUrl("https://old.example");++ const first = renderProvider();+ expect(useEventStore.getState()).toMatchObject({+ events: [],+ loadedConversationId: "conv-main",+ });+ expect(useBrowserStore.getState().url).toBe("");+ first.unmount();++ useEventStore+ .getState()+ .addEvent(makeMessageEvent("06", "assistant", ["keep on remount"]));+ useBrowserStore.getState().setUrl("https://current.example");+ socketCapture.callIndex = 0;+ const sameConversation = renderProvider();+ expect(useEventStore.getState().events).toHaveLength(1);+ expect(useBrowserStore.getState().url).toBe("https://current.example");++ sameConversation.rerender(+ <QueryClientProvider client={sameConversation.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-next"+ conversationUrl="http://localhost:8000/api/conversations/conv-next"+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ expect(useEventStore.getState()).toMatchObject({+ events: [],+ loadedConversationId: "conv-next",+ });+ expect(useBrowserStore.getState().url).toBe("");+ });++ it("hydrates and opens the socket when an in-flight history query settles", async () => {+ historyCapture.result.data = undefined;+ historyCapture.result.isPending = true;+ const view = renderProvider();+ expect(socketCapture.mainUrl).toBe("");++ const latest = makeMessageEvent("07", "assistant", ["fresh tail"]);+ historyCapture.result = {+ data: { events: [latest] },+ isPending: false,+ isFetching: false,+ isError: false,+ };+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ await waitFor(() =>+ expect(useEventStore.getState().events).toHaveLength(1),+ );+ expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");+ expect(mainOptions().queryParams).toEqual({+ resend_mode: "since",+ after_timestamp: latest.timestamp,+ });+ expect(+ Object.hasOwn(mainOptions().queryParams ?? {}, "session_api_key"),+ ).toBe(false);+ expect(+ Object.hasOwn(planningOptions().queryParams ?? {}, "session_api_key"),+ ).toBe(false);+ });++ it("ignores incomplete planning conversations and connects complete ones", () => {+ const { rerender, queryClient } = renderProvider({+ subConversations: [makeSubConversation({ conversation_url: null })],+ });+ expect(socketCapture.planningUrl).toBe("");++ rerender(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ subConversations={[makeSubConversation()]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ expect(socketCapture.planningUrl).toContain(+ "/sockets/events/conv-planning",+ );+ });++ it("safely ignores an empty planning conversation slot", () => {+ expect(() =>+ renderProvider({+ subConversations: [undefined as unknown as AppConversation],+ }),+ ).not.toThrow();+ expect(socketCapture.planningUrl).toBe("");+ });++ it("reports the main socket lifecycle and only surfaces errors after a successful connection", () => {+ renderProvider();++ act(() => mainOptions().onError?.(new Event("error")));+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ useErrorMessageStore+ .getState()+ .setErrorMessage("old connection error", "connection");+ act(() => mainOptions().onOpen?.(new Event("open")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("OPEN");+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();++ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ act(() => mainOptions().onError?.(new Event("error")));+ expect(useErrorMessageStore.getState()).toMatchObject({+ errorMessage: SERVER_CONNECTION_ERROR_MESSAGE,+ errorType: "connection",+ });+ });++ it("merges main and planning connection lifecycles", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(0);+ renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "CONNECTING",+ );+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");++ await act(async () => {+ mainOptions().onOpen?.(new Event("open"));+ await planningOptions().onOpen?.(new Event("open"));+ });+ expect(screen.getByTestId("connection-state")).toHaveTextContent("OPEN");+ expect(screen.getByTestId("loading-history")).toHaveTextContent("false");++ act(() => planningOptions().onClose?.(new CloseEvent("close")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ act(() => planningOptions().onError?.(new Event("error")));+ expect(useErrorMessageStore.getState()).toMatchObject({+ errorMessage: SERVER_CONNECTION_ERROR_MESSAGE,+ errorType: "connection",+ });+ });++ for (const [label, readyState, expected] of [+ ["connecting", WebSocket.CONNECTING, "CONNECTING"],+ ["open", WebSocket.OPEN, "OPEN"],+ ["closing", WebSocket.CLOSING, "CLOSING"],+ ["closed", WebSocket.CLOSED, "CLOSED"],+ ["unknown", 99, "CLOSED"],+ ] as const) {+ it(`reflects a ${label} main socket ready state`, async () => {+ socketCapture.mainSocket = makeSocket(readyState);+ renderProvider();++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ expected,+ ),+ );+ });+ }++ it("uses planning socket ready state when both conversations are connected", async () => {+ socketCapture.mainSocket = makeSocket(WebSocket.OPEN);+ socketCapture.planningSocket = makeSocket(WebSocket.CLOSING);+ renderProvider({ subConversations: [makeSubConversation()] });++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "CLOSING",+ ),+ );+ });++ it("keeps the planning connection in its initial connecting state", async () => {+ socketCapture.mainSocket = makeSocket(WebSocket.OPEN);+ renderProvider({ subConversations: [makeSubConversation()] });++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "CONNECTING",+ ),+ );+ });++ for (const [label, mainReadyState, planningReadyState, expected] of [+ ["main connecting", WebSocket.CONNECTING, WebSocket.OPEN, "CONNECTING"],+ ["main closed", WebSocket.CLOSED, WebSocket.OPEN, "CLOSED"],+ ["planning closing", WebSocket.CLOSED, WebSocket.CLOSING, "CLOSING"],+ ["main closing", WebSocket.CLOSING, WebSocket.CLOSED, "CLOSING"],+ ] as const) {+ it(`merges ${label} with the other socket`, async () => {+ socketCapture.mainSocket = makeSocket(mainReadyState);+ socketCapture.planningSocket = makeSocket(planningReadyState);+ renderProvider({ subConversations: [makeSubConversation()] });++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ expected,+ ),+ );+ });+ }++ for (const [label, readyState, expected] of [+ ["connecting", WebSocket.CONNECTING, "CONNECTING"],+ ["closed", WebSocket.CLOSED, "CLOSED"],+ ["unknown", 99, "CLOSED"],+ ] as const) {+ it(`reflects a ${label} planning socket ready state`, async () => {+ socketCapture.mainSocket = makeSocket(WebSocket.OPEN);+ socketCapture.planningSocket = makeSocket(readyState);+ renderProvider({ subConversations: [makeSubConversation()] });++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ expected,+ ),+ );+ });+ }++ it("resets connection history and planning loading when identities change", () => {+ const view = renderProvider({ subConversations: [makeSubConversation()] });+ act(() => mainOptions().onOpen?.(new Event("open")));++ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ subConversations={[makeSubConversation()]}+ subConversationIds={["conv-planning"]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");+ act(() => mainOptions().onError?.(new Event("error")));+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();++ act(() => mainOptions().onOpen?.(new Event("open")));+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-next"+ conversationUrl="http://localhost:8000/api/conversations/conv-next"+ subConversations={[makeSubConversation()]}+ subConversationIds={["conv-planning"]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ act(() => mainOptions().onError?.(new Event("error")));+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ });++ it("forgets a successful main connection when the conversation changes", () => {+ const view = renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));++ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-next"+ conversationUrl="http://localhost:8000/api/conversations/conv-next"+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ act(() => mainOptions().onError?.(new Event("error")));++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ });++ it("dismisses the error and reconnects the socket for the active mode", () => {+ const { unmount } = renderProvider({+ subConversations: [makeSubConversation()],+ });+ useErrorMessageStore.getState().setErrorMessage("retry me", "connection");+ useConversationStore.setState({ conversationMode: "plan" });++ act(() => contextCapture.current?.reconnect());++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(socketCapture.reconnectPlanning).toHaveBeenCalledOnce();+ expect(socketCapture.reconnectMain).not.toHaveBeenCalled();++ useConversationStore.setState({ conversationMode: "code" });+ act(() => contextCapture.current?.reconnect());+ expect(socketCapture.reconnectMain).toHaveBeenCalledOnce();+ expect(socketCapture.reconnectPlanning).toHaveBeenCalledOnce();++ unmount();+ socketCapture.callIndex = 0;+ socketCapture.reconnectMain.mockClear();+ renderProvider();+ useConversationStore.setState({ conversationMode: "plan" });+ act(() => contextCapture.current?.reconnect());+ expect(socketCapture.reconnectMain).toHaveBeenCalledOnce();+ });++ it("uses sockets and reconnect routing introduced after the first render", async () => {+ const view = renderProvider();+ const mainSocket = makeSocket(WebSocket.OPEN);+ const planningSocket = makeSocket(WebSocket.OPEN);+ socketCapture.mainSocket = mainSocket;+ socketCapture.planningSocket = planningSocket;++ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ subConversations={[makeSubConversation()]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ await waitFor(() =>+ expect(screen.getByTestId("connection-state")).toHaveTextContent("OPEN"),+ );+ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("new socket")),+ ).resolves.toEqual({ queued: false });+ expect(mainSocket.send).toHaveBeenCalledWith(+ JSON.stringify({ ...makeSendRequest("new socket"), run: true }),+ );+ expect(socketCapture.queueMessage).not.toHaveBeenCalled();++ useConversationStore.setState({ conversationMode: "plan" });+ act(() => contextCapture.current?.reconnect());+ expect(socketCapture.reconnectPlanning).toHaveBeenCalledOnce();+ expect(socketCapture.reconnectMain).not.toHaveBeenCalled();+ });++ it("sends code and plan messages through their open sockets", async () => {+ const mainSocket = makeSocket();+ const planningSocket = makeSocket();+ socketCapture.mainSocket = mainSocket;+ socketCapture.planningSocket = planningSocket;+ renderProvider({ subConversations: [makeSubConversation()] });++ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("code message")),+ ).resolves.toEqual({ queued: false });+ expect(mainSocket.send).toHaveBeenCalledWith(+ JSON.stringify({ ...makeSendRequest("code message"), run: true }),+ );++ useConversationStore.setState({ conversationMode: "plan" });+ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("plan message")),+ ).resolves.toEqual({ queued: false });+ expect(planningSocket.send).toHaveBeenCalledWith(+ JSON.stringify({ ...makeSendRequest("plan message"), run: true }),+ );+ });++ it("queues messages over REST while the socket is unavailable", async () => {+ renderProvider();++ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("queue me")),+ ).resolves.toEqual({ queued: true });+ expect(socketCapture.queueMessage).toHaveBeenCalledWith(+ "conv-main",+ { role: "user", content: makeSendRequest("queue me").content },+ { run: true },+ );+ });++ it("queues plan messages for the latest planner ID after it changes", async () => {+ const view = renderProvider({ subConversationIds: ["planner-old"] });+ act(() => useConversationStore.setState({ conversationMode: "plan" }));+ await contextCapture.current?.sendMessage(makeSendRequest("old plan"));+ expect(socketCapture.queueMessage).toHaveBeenLastCalledWith(+ "planner-old",+ makeSendRequest("old plan"),+ { run: true },+ );+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ subConversationIds={["planner-new"]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ await contextCapture.current?.sendMessage(makeSendRequest("new plan"));+ expect(socketCapture.queueMessage).toHaveBeenLastCalledWith(+ "planner-new",+ makeSendRequest("new plan"),+ { run: true },+ );+ });++ it("reports missing conversations and REST queue failures", async () => {+ renderProvider({ conversationId: undefined });++ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("orphan")),+ ).rejects.toThrow("No conversation ID available");+ expect(useErrorMessageStore.getState().errorMessage).toBe(+ "No conversation ID available",+ );++ socketCapture.callIndex = 0;+ socketCapture.queueMessage.mockRejectedValueOnce(new Error("queue broke"));+ renderProvider();+ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("retry")),+ ).rejects.toThrow("queue broke");+ expect(useErrorMessageStore.getState().errorMessage).toBe("queue broke");+ });++ it("uses a safe error for non-Error queue failures", async () => {+ socketCapture.queueMessage.mockRejectedValueOnce("offline");+ renderProvider();++ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("retry")),+ ).rejects.toBe("offline");+ expect(useErrorMessageStore.getState().errorMessage).toBe(+ "Failed to queue message for delivery",+ );+ });++ it("reports WebSocket send failures", async () => {+ const socket = makeSocket();+ vi.mocked(socket.send).mockImplementationOnce(() => {+ throw new Error("send broke");+ });+ socketCapture.mainSocket = socket;+ renderProvider();++ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("hello")),+ ).rejects.toThrow("send broke");+ expect(useErrorMessageStore.getState().errorMessage).toBe("send broke");++ vi.mocked(socket.send).mockImplementationOnce(() => {+ throw "closed";+ });+ await expect(+ contextCapture.current?.sendMessage(makeSendRequest("again")),+ ).rejects.toBe("closed");+ expect(useErrorMessageStore.getState().errorMessage).toBe(+ "Failed to send message",+ );+ });++ it("routes main-conversation events to their user-visible stores", () => {+ const consumeMatchingPendingMessage = vi.spyOn(+ useOptimisticUserMessageStore.getState(),+ "consumeMatchingPendingMessage",+ );+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ const { queryClient } = renderProvider();+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");++ useErrorMessageStore.getState().setErrorMessage("temporary", "connection");+ dispatchMain(makeMessageEvent("10", "assistant", ["connected"]));+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(consumeMatchingPendingMessage).not.toHaveBeenCalled();+ expect(socketCapture.trackError).not.toHaveBeenCalled();+ expect(warn).not.toHaveBeenCalled();++ dispatchMain({+ ...baseEvent("11"),+ kind: "ConversationErrorEvent",+ code: "BadRequest",+ detail: "Conversation failed",+ });+ expect(useErrorMessageStore.getState()).toMatchObject({+ errorMessage: "Conversation failed",+ errorType: "conversation",+ errorCode: "BadRequest",+ });+ expect(socketCapture.trackError).toHaveBeenCalledWith(+ expect.objectContaining({+ source: "conversation",+ metadata: expect.objectContaining({+ eventId: "11",+ errorCode: "BadRequest",+ }),+ }),+ );+ expect(socketCapture.trackError).toHaveBeenCalledTimes(1);++ dispatchMain(makeMessageEvent("12", "assistant", ["still connected"]));+ expect(useErrorMessageStore.getState().errorMessage).toBe(+ "Conversation failed",+ );++ dispatchMain({+ ...baseEvent("13", "agent"),+ tool_name: "llm",+ tool_call_id: "call-13",+ error: "Model failed",+ });+ expect(socketCapture.trackError).toHaveBeenCalledWith(+ expect.objectContaining({+ source: "agent",+ metadata: expect.objectContaining({+ eventId: "13",+ toolName: "llm",+ toolCallId: "call-13",+ }),+ }),+ );+ expect(socketCapture.trackError).toHaveBeenCalledTimes(2);++ useOptimisticUserMessageStore.setState({+ pendingMessages: [+ {+ id: "pending-main",+ conversationId: "conv-main",+ text: "hello world",+ content: "hello world",+ status: "sending",+ imageUrls: [],+ fileUrls: [],+ timestamp: "2024-01-01T00:00:00.000Z",+ },+ ],+ });+ setConversationState("conv-main", { draftMessage: "hello world" });+ dispatchMain(makeMessageEvent("14", "user", ["hello", " world"]));+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual(+ [],+ );+ expect(consumeMatchingPendingMessage).toHaveBeenCalledOnce();+ expect(consumeMatchingPendingMessage).toHaveBeenCalledWith(+ "conv-main",+ "hello world",+ );+ expect(getConversationState("conv-main").draftMessage).toBeNull();++ dispatchMain(+ makeActionEvent("15", {+ kind: "ExecuteBashAction",+ command: "pwd",+ is_input: false,+ timeout: null,+ reset: false,+ }),+ );+ expect(useCommandStore.getState().commands).toContainEqual({+ type: "input",+ content: "pwd",+ });+ expect(invalidateQueries).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "conv-main"] },+ { cancelRefetch: false },+ );++ dispatchMain(+ makeStateEvent("16", "full_state", {+ execution_status: "running",+ }),+ );+ // Execution status is now scoped per conversation id.+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-main"+ ],+ ).toBe("running");+ dispatchMain(makeStateEvent("17", "execution_status", "paused"));+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-main"+ ],+ ).toBe("paused");++ dispatchMain(+ makeStateEvent("18-no-metrics", "stats", {+ usage_to_metrics: undefined,+ }),+ );+ dispatchMain(makeStateEvent("18", "stats", { usage_to_metrics: {} }));+ expect(warn).not.toHaveBeenCalled();+ dispatchMain(+ makeStateEvent("19", "stats", {+ usage_to_metrics: {+ agent: {+ accumulated_cost: 1.25,+ max_budget_per_task: undefined,+ accumulated_token_usage: null,+ },+ },+ }),+ );+ expect(useMetricsStore.getState()).toMatchObject({+ cost: 1.25,+ usage: null,+ });+ // A stats update whose budget is absent passes the value through as+ // undefined rather than coercing it to null.+ expect(useMetricsStore.getState().max_budget_per_task).toBeUndefined();+ dispatchMain(+ makeStateEvent("20", "stats", {+ usage_to_metrics: {+ agent: {+ accumulated_cost: 2.5,+ max_budget_per_task: 8,+ accumulated_token_usage: {+ prompt_tokens: 10,+ completion_tokens: 20,+ cache_read_tokens: 3,+ cache_write_tokens: 4,+ context_window: 128000,+ per_turn_token: 30,+ },+ },+ },+ }),+ );+ expect(useMetricsStore.getState()).toMatchObject({+ cost: 2.5,+ max_budget_per_task: 8,+ usage: {+ prompt_tokens: 10,+ completion_tokens: 20,+ cache_read_tokens: 3,+ cache_write_tokens: 4,+ context_window: 128000,+ per_turn_token: 30,+ },+ });+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-main"+ ],+ ).toBe("paused");++ const goalStatus = {+ active: false,+ status: "complete",+ iteration: 2,+ max_iterations: 3,+ objective: "Ship it",+ verdict: { score: 1, complete: true, missing: "" },+ };+ dispatchMain(makeStateEvent("21", "goal", goalStatus));+ expect(useGoalStore.getState().statusByConversation["conv-main"]).toEqual(+ goalStatus,+ );+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-main"+ ],+ ).toBe("paused");++ dispatchMain(+ makeObservationEvent("22", {+ kind: "ExecuteBashObservation",+ content: [+ { type: "text", text: "line one" },+ { type: "image", image_urls: ["ignored"] },+ { type: "text", text: "line two" },+ ],+ }),+ );+ expect(useCommandStore.getState().commands).toContainEqual({+ type: "output",+ content: "line one\nline two",+ });++ dispatchMain(+ makeObservationEvent(+ "23",+ { kind: "BrowserObservation", screenshot_data: "raw-image" },+ "browser",+ ),+ );+ expect(useBrowserStore.getState().screenshotSrc).toBe(+ "data:image/png;base64,raw-image",+ );+ dispatchMain(+ makeObservationEvent(+ "24",+ {+ kind: "BrowserObservation",+ screenshot_data: "data:image/webp;base64,ready",+ },+ "browser",+ ),+ );+ expect(useBrowserStore.getState().screenshotSrc).toBe(+ "data:image/webp;base64,ready",+ );+ dispatchMain(+ makeObservationEvent(+ "25",+ { kind: "BrowserObservation", screenshot_data: null },+ "browser",+ ),+ );++ dispatchMain(+ makeActionEvent(+ "26",+ { kind: "BrowserNavigateAction", url: "https://example.com" },+ "browser",+ ),+ );+ expect(useBrowserStore.getState().url).toBe("https://example.com");++ queryClient.setQueryData(["user", "conversation", "conv-main"], {+ id: "conv-main",+ llm_model: "old-model",+ });+ dispatchMain(+ makeObservationEvent(+ "27",+ {+ kind: "SwitchLLMObservation",+ content: [{ type: "text", text: "Switched" }],+ is_error: false,+ profile_name: "fast-profile",+ reason: null,+ active_model: "new-model",+ },+ "switch_llm",+ ),+ );+ expect(+ useModelStore.getState().activeProfileByConversation["conv-main"],+ ).toBe("fast-profile");+ // The live stamp merges only the profile fields over the default+ // repo/branch/provider scaffold; optional fields it doesn't own+ // (selected_workspace, plugins) are left unset rather than nulled.+ expect(getStoredConversationMetadata("conv-main")).toMatchObject({+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ active_profile: "fast-profile",+ });+ expect(+ queryClient.getQueryData(["user", "conversation", "conv-main"]),+ ).toMatchObject({ llm_model: "new-model" });++ dispatchMain(+ makeObservationEvent(+ "28",+ {+ kind: "SwitchLLMObservation",+ content: [],+ is_error: true,+ profile_name: "failed-profile",+ reason: "unavailable",+ active_model: null,+ },+ "switch_llm",+ ),+ );+ expect(+ useModelStore.getState().activeProfileByConversation["conv-main"],+ ).toBe("fast-profile");++ dispatchMain(+ makeObservationEvent(+ "28-without-model",+ {+ kind: "SwitchLLMObservation",+ content: [{ type: "text", text: "Profile switched" }],+ is_error: false,+ profile_name: "profile-without-model",+ reason: null,+ active_model: null,+ },+ "switch_llm",+ ),+ );+ expect(+ useModelStore.getState().activeProfileByConversation["conv-main"],+ ).toBe("profile-without-model");+ expect(getStoredConversationMetadata("conv-main")).toMatchObject({+ active_profile: "profile-without-model",+ });+ expect(+ queryClient.getQueryData(["user", "conversation", "conv-main"]),+ ).toMatchObject({ llm_model: "new-model" });++ dispatchMain(+ makeActionEvent(+ "29",+ {+ kind: "CanvasUIAction",+ command: "open_tab",+ tab: "terminal",+ },+ "canvas_ui",+ ),+ );+ expect(useConversationStore.getState()).toMatchObject({+ selectedTab: "terminal",+ isRightPanelShown: true,+ });+ expect(warn).not.toHaveBeenCalled();+ });++ it("uses the latest conversation identity for canvas file navigation", () => {+ const view = renderProvider();+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-next"+ conversationUrl="http://localhost:8000/api/conversations/conv-next"+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ dispatchMain(+ makeActionEvent(+ "30",+ {+ kind: "CanvasUIAction",+ command: "navigate_to_file",+ path: "/workspace/src/index.ts",+ },+ "canvas_ui",+ ),+ );+ // The canvas navigation handler normalizes the agent path to a+ // workspace-relative one, stripping the `/workspace/<root>/` prefix.+ expect(useFilesTabStore.getState()).toMatchObject({+ selectedPath: "index.ts",+ selectedConversationId: "conv-next",+ });+ });++ it("ignores malformed and non-event messages without disrupting the socket", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ renderProvider();++ act(() => mainOptions().onMessage?.({ data: "not-json" } as MessageEvent));+ dispatchMain({ type: "not-an-event" });++ expect(warn).toHaveBeenCalledWith(+ "Failed to parse WebSocket message as JSON:",+ expect.any(SyntaxError),+ );+ expect(useEventStore.getState().events).toEqual([]);+ });++ it("keeps conversation-scoped effects inactive when no main conversation is selected", () => {+ const consumeMatchingPendingMessage = vi.spyOn(+ useOptimisticUserMessageStore.getState(),+ "consumeMatchingPendingMessage",+ );+ const { queryClient } = renderProvider({ conversationId: undefined });+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");+ useOptimisticUserMessageStore.setState({+ pendingMessages: [+ {+ id: "pending-orphan",+ conversationId: "conv-main",+ text: "orphan",+ content: "orphan",+ status: "sending",+ imageUrls: [],+ fileUrls: [],+ timestamp: "2024-01-01T00:00:00.000Z",+ },+ ],+ });++ dispatchMain(makeMessageEvent("31", "user", ["orphan"]));+ dispatchMain(+ makeActionEvent("32", {+ kind: "ExecuteBashAction",+ command: "echo fallback",+ is_input: false,+ timeout: null,+ reset: false,+ }),+ );+ dispatchMain(+ makeStateEvent("33", "goal", {+ active: true,+ status: "running",+ iteration: 0,+ max_iterations: 2,+ objective: "No owner",+ verdict: null,+ }),+ );+ dispatchMain(+ makeActionEvent(+ "34",+ { kind: "CanvasUIAction", command: "open_tab", tab: "files" },+ "canvas_ui",+ ),+ );++ expect(+ useOptimisticUserMessageStore.getState().pendingMessages,+ ).toHaveLength(1);+ expect(consumeMatchingPendingMessage).not.toHaveBeenCalled();+ expect(useGoalStore.getState().statusByConversation).toEqual({});+ expect(invalidateQueries).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "test-conversation-id"] },+ { cancelRefetch: false },+ );+ });++ it("loads the last planning Plan.md after streamed history completes", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(2);+ socketCapture.readConversationFile.mockImplementation(+ (_variables, callbacks) => callbacks.onSuccess("# Loaded plan"),+ );+ const view = renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });++ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");+ dispatchPlanning(+ makeObservationEvent(+ "35",+ {+ kind: "PlanningFileEditorObservation",+ content: [{ type: "text", text: "history" }],+ is_error: false,+ command: "create",+ path: "/workspace/Plan.md",+ prev_exist: false,+ old_content: null,+ new_content: "history",+ },+ "planning_file_editor",+ ),+ );+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");+ expect(socketCapture.readConversationFile).not.toHaveBeenCalled();+ dispatchPlanning(makeMessageEvent("36", "assistant", ["planned"]));++ await waitFor(() =>+ expect(screen.getByTestId("loading-history")).toHaveTextContent("false"),+ );+ await waitFor(() =>+ expect(socketCapture.readConversationFile).toHaveBeenCalledWith(+ {+ conversationId: "conv-planning",+ filePath: "/workspace/Plan.md",+ },+ expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }),+ ),+ );+ expect(useConversationStore.getState().planContent).toBe("# Loaded plan");+ expect(useEventStore.getState().events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: "35", isFromPlanningAgent: true }),+ expect.objectContaining({ id: "36", isFromPlanningAgent: true }),+ ]),+ );+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-next"+ conversationUrl="http://localhost:8000/api/conversations/conv-next"+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ expect(useConversationStore.getState().planContent).toBeNull();+ });++ it("finishes planning history when the expected count arrives after its events", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(2);+ renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });++ dispatchPlanning({ type: "history-envelope" });+ dispatchPlanning({ type: "history-envelope" });+ expect(screen.getByTestId("loading-history")).toHaveTextContent("true");+ expect(useEventStore.getState().events).toEqual([]);++ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });++ await waitFor(() =>+ expect(screen.getByTestId("loading-history")).toHaveTextContent("false"),+ );+ });++ it("reports a deferred Plan.md read failure after history completes", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(1);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ socketCapture.readConversationFile.mockImplementation(+ (_variables, callbacks) =>+ callbacks.onError(new Error("deferred read failed")),+ );+ renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });+ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });++ dispatchPlanning(+ makeObservationEvent(+ "53",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/PLAN.md",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );++ await waitFor(() =>+ expect(warn).toHaveBeenCalledWith(+ "Failed to read conversation file:",+ expect.objectContaining({ message: "deferred read failed" }),+ ),+ );+ });++ it("reads live planning files immediately and reports read failures", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(0);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ socketCapture.readConversationFile.mockImplementation(+ (_variables, callbacks) => callbacks.onError(new Error("read failed")),+ );+ renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });+ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });++ dispatchPlanning(+ makeObservationEvent(+ "37",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/PLAN.MD",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );++ expect(socketCapture.readConversationFile).toHaveBeenCalledWith(+ {+ conversationId: "conv-planning",+ filePath: "/workspace/PLAN.MD",+ },+ expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }),+ );+ expect(warn).toHaveBeenCalledWith(+ "Failed to read conversation file:",+ expect.objectContaining({ message: "read failed" }),+ );+ warn.mockClear();++ dispatchPlanning(+ makeObservationEvent(+ "37-not-plan",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/notes.md",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ dispatchPlanning(+ makeObservationEvent(+ "37-null-path",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: null,+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ expect(socketCapture.readConversationFile).toHaveBeenCalledOnce();+ expect(warn).not.toHaveBeenCalled();++ socketCapture.readConversationFile.mockImplementation(+ (_variables, callbacks) => callbacks.onSuccess("# Live plan"),+ );+ dispatchPlanning(+ makeObservationEvent(+ "54",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/PLAN.MD",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ expect(useConversationStore.getState().planContent).toBe("# Live plan");+ });++ it("falls through planning history when event counting fails", async () => {+ vi.spyOn(EventService, "getEventCount").mockRejectedValue(+ new Error("count unavailable"),+ );+ renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });++ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });++ expect(screen.getByTestId("loading-history")).toHaveTextContent("false");+ });++ it("does not request a planning history count without coordinates", async () => {+ const getEventCount = vi+ .spyOn(EventService, "getEventCount")+ .mockResolvedValue(0);+ renderProvider({+ subConversations: [+ makeSubConversation({ id: "", conversation_url: null }),+ ],+ });++ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });++ expect(getEventCount).not.toHaveBeenCalled();+ });++ it("does not show a planning connection error before its first open", () => {+ renderProvider({ subConversations: [makeSubConversation()] });++ act(() => planningOptions().onError?.(new Event("error")));++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ });++ it.each(["main", "planning"])(+ "flushes %s streaming deltas on the next frame and clears connection errors",+ (source) => {+ let frame: FrameRequestCallback | undefined;+ vi.spyOn(window, "requestAnimationFrame").mockImplementation(+ (callback) => {+ frame = callback;+ return 1;+ },+ );+ renderProvider({ subConversations: [makeSubConversation()] });+ useErrorMessageStore+ .getState()+ .setErrorMessage("disconnected", "connection");+ const dispatch = source === "main" ? dispatchMain : dispatchPlanning;+ dispatch({+ ...baseEvent("delta", "agent"),+ kind: "StreamingDeltaEvent",+ content: "Streaming",+ reasoning_content: null,+ });+ expect(useEventStore.getState().eventIds.has("delta")).toBe(false);+ act(() => {+ if (!frame) throw new Error("Missing scheduled flush");+ frame(0);+ });+ expect(useEventStore.getState().uiEvents).toEqual([+ expect.objectContaining({+ kind: "StreamingDeltaEvent",+ content: "Streaming",+ ...(source === "planning" ? { isFromPlanningAgent: true } : {}),+ }),+ ]);+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ },+ );++ it("flushes planning deltas before later events and ignores replayed error side effects", () => {+ vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);+ const view = renderProvider({ subConversations: [makeSubConversation()] });+ dispatchPlanning({+ ...baseEvent("delta-plan", "agent"),+ kind: "StreamingDeltaEvent",+ content: "Planning",+ reasoning_content: null,+ });+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-main"+ conversationUrl="http://localhost:8000/api/conversations/conv-main"+ subConversations={[makeSubConversation()]}+ >+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ const classification = {+ kind: "auth",+ retryable: false,+ user_action: "settings",+ };+ const error = {+ ...baseEvent("planning-error"),+ kind: "ConversationErrorEvent",+ code: "Auth",+ detail: "Credentials rejected",+ classification,+ };+ dispatchPlanning(error);+ expect(useEventStore.getState().uiEvents[0]).toMatchObject({+ kind: "StreamingDeltaEvent",+ content: "Planning",+ isFromPlanningAgent: true,+ });+ expect(useErrorMessageStore.getState().errorClassification).toEqual(+ classification,+ );+ expect(socketCapture.trackError).toHaveBeenCalledWith(+ expect.objectContaining({+ classification,+ source: "planning_conversation",+ }),+ );+ dispatchPlanning(error);+ expect(socketCapture.trackError).toHaveBeenCalledTimes(1);+ });++ it("forwards the child-launch action with the parent and tool-call IDs", () => {+ renderProvider();+ const action = {+ kind: "ClientAction_launch_child_conversation",+ target: "local",+ task: "Inspect tests",+ };+ dispatchMain(+ makeActionEvent("launch", action, "launch_child_conversation"),+ );+ expect(socketCapture.launchChild).toHaveBeenCalledWith(+ action,+ "conv-main",+ "call-launch",+ );+ });++ it("does not launch a child for unrelated actions or without a parent ID", () => {+ const view = renderProvider();+ dispatchMain(+ makeActionEvent(+ "think",+ { kind: "ThinkAction", thought: "Review" },+ "think",+ ),+ );+ expect(socketCapture.launchChild).not.toHaveBeenCalled();+ view.rerender(+ <QueryClientProvider client={view.queryClient}>+ <ConversationWebSocketProvider>+ <ContextProbe />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );+ dispatchMain(+ makeActionEvent(+ "orphan-launch",+ {+ kind: "ClientAction_launch_child_conversation",+ target: "local",+ task: "Inspect tests",+ },+ "launch_child_conversation",+ ),+ );+ expect(socketCapture.launchChild).not.toHaveBeenCalled();+ });++ it("combines multiple LLM costs and preserves the first non-null budget", () => {+ renderProvider();+ dispatchMain(+ makeStateEvent("multi-metrics", "stats", {+ usage_to_metrics: {+ first: {+ accumulated_cost: 1,+ max_budget_per_task: null,+ accumulated_token_usage: null,+ },+ second: {+ accumulated_cost: 2,+ max_budget_per_task: 10,+ accumulated_token_usage: null,+ },+ third: {+ accumulated_cost: 3,+ max_budget_per_task: 20,+ accumulated_token_usage: null,+ },+ },+ }),+ );+ expect(useMetricsStore.getState()).toMatchObject({+ cost: 6,+ max_budget_per_task: 10,+ });+ });++ it("routes planning-agent events to the shared conversation experience", () => {+ const consumeMatchingPendingMessage = vi.spyOn(+ useOptimisticUserMessageStore.getState(),+ "consumeMatchingPendingMessage",+ );+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ const { queryClient } = renderProvider({+ subConversations: [makeSubConversation()],+ subConversationIds: ["conv-planning"],+ });+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");++ useErrorMessageStore.getState().setErrorMessage("temporary", "connection");+ dispatchPlanning(makeMessageEvent("37-normal", "assistant", ["ready"]));+ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(consumeMatchingPendingMessage).not.toHaveBeenCalled();+ expect(socketCapture.trackError).not.toHaveBeenCalled();+ expect(warn).not.toHaveBeenCalled();++ dispatchPlanning({+ ...baseEvent("38"),+ kind: "ServerErrorEvent",+ code: "PlannerUnavailable",+ detail: "Planner failed",+ });+ expect(useErrorMessageStore.getState()).toMatchObject({+ errorMessage: "Planner failed",+ errorType: "conversation",+ errorCode: "PlannerUnavailable",+ });+ expect(socketCapture.trackError).toHaveBeenCalledWith(+ expect.objectContaining({+ source: "planning_conversation",+ metadata: expect.objectContaining({+ eventId: "38",+ errorCode: "PlannerUnavailable",+ }),+ }),+ );++ dispatchPlanning({+ ...baseEvent("39", "agent"),+ tool_name: "planner_llm",+ tool_call_id: "call-39",+ error: "Planner model failed",+ });+ expect(socketCapture.trackError).toHaveBeenCalledWith(+ expect.objectContaining({+ source: "planning_agent",+ metadata: expect.objectContaining({+ eventId: "39",+ toolName: "planner_llm",+ toolCallId: "call-39",+ }),+ }),+ );+ expect(socketCapture.trackError).toHaveBeenCalledTimes(2);++ useOptimisticUserMessageStore.setState({+ pendingMessages: [+ {+ id: "pending-plan",+ conversationId: "conv-main",+ text: "plan this",+ content: "plan this",+ status: "sending",+ imageUrls: [],+ fileUrls: [],+ timestamp: "2024-01-01T00:00:00.000Z",+ },+ ],+ });+ setConversationState("conv-main", { draftMessage: "plan this" });+ dispatchPlanning(makeMessageEvent("40", "user", ["plan this"]));+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual(+ [],+ );+ expect(consumeMatchingPendingMessage).toHaveBeenCalledOnce();+ expect(consumeMatchingPendingMessage).toHaveBeenCalledWith(+ "conv-main",+ "plan this",+ );+ expect(getConversationState("conv-main").draftMessage).toBeNull();++ dispatchPlanning(+ makeActionEvent("41", {+ kind: "ExecuteBashAction",+ command: "cat PLAN.md",+ is_input: false,+ timeout: null,+ reset: false,+ }),+ );+ expect(useCommandStore.getState().commands).toContainEqual({+ type: "input",+ content: "cat PLAN.md",+ });+ expect(invalidateQueries).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "conv-planning"] },+ { cancelRefetch: false },+ );++ dispatchPlanning(+ makeStateEvent("42", "full_state", {+ execution_status: "running",+ }),+ );+ // The planning socket scopes execution status to the planning agent's own+ // conversation id, never the main conversation.+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-planning"+ ],+ ).toBe("running");+ dispatchPlanning(makeStateEvent("43", "execution_status", "finished"));+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-planning"+ ],+ ).toBe("finished");+ dispatchPlanning(+ makeStateEvent("44", "stats", {+ usage_to_metrics: {+ agent: {+ accumulated_cost: 4,+ max_budget_per_task: 10,+ accumulated_token_usage: null,+ },+ },+ }),+ );+ expect(useMetricsStore.getState().cost).toBe(4);+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-planning"+ ],+ ).toBe("finished");++ const planningGoal = {+ active: true,+ status: "running",+ iteration: 1,+ max_iterations: 4,+ objective: "Plan",+ verdict: null,+ };+ dispatchPlanning(makeStateEvent("45", "goal", planningGoal));+ expect(useGoalStore.getState().statusByConversation["conv-main"]).toEqual(+ planningGoal,+ );+ expect(+ useConversationStateStore.getState().executionStatusByConversation[+ "conv-planning"+ ],+ ).toBe("finished");++ dispatchPlanning(+ makeObservationEvent("46", {+ kind: "ExecuteBashObservation",+ content: [+ { type: "text", text: "plan output" },+ { type: "image", image_urls: [] },+ { type: "text", text: "second line" },+ ],+ }),+ );+ expect(useCommandStore.getState().commands).toContainEqual({+ type: "output",+ content: "plan output\nsecond line",+ });++ dispatchPlanning(+ makeObservationEvent(+ "47",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/notes.md",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ expect(socketCapture.readConversationFile).not.toHaveBeenCalled();+ expect(warn).not.toHaveBeenCalled();+ });++ it("keeps planning fallbacks safe without conversation identities", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ const { queryClient } = renderProvider({+ conversationId: undefined,+ subConversations: undefined,+ subConversationIds: undefined,+ });+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");++ await act(async () => {+ await planningOptions().onOpen?.(new Event("open"));+ });+ dispatchPlanning(makeMessageEvent("48", "user", ["unscoped"]));+ dispatchPlanning(+ makeActionEvent("49", {+ kind: "ExecuteBashAction",+ command: "echo fallback",+ is_input: false,+ timeout: null,+ reset: false,+ }),+ );+ dispatchPlanning(+ makeStateEvent("50", "goal", {+ active: false,+ status: "interrupted",+ iteration: 1,+ max_iterations: 2,+ objective: "No owner",+ verdict: null,+ }),+ );+ dispatchPlanning(+ makeObservationEvent(+ "51",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: null,+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ dispatchPlanning(+ makeObservationEvent(+ "52",+ {+ kind: "PlanningFileEditorObservation",+ content: [],+ is_error: false,+ command: "view",+ path: "/workspace/PLAN.md",+ prev_exist: true,+ old_content: null,+ new_content: null,+ },+ "planning_file_editor",+ ),+ );+ expect(warn).not.toHaveBeenCalled();+ act(() =>+ planningOptions().onMessage?.({ data: "not-json" } as MessageEvent),+ );++ expect(invalidateQueries).toHaveBeenCalledWith(+ { queryKey: ["file_changes", "test-conversation-id"] },+ { cancelRefetch: false },+ );+ expect(useGoalStore.getState().statusByConversation).toEqual({});+ expect(socketCapture.readConversationFile).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalledWith(+ "Failed to parse WebSocket message as JSON:",+ expect.any(SyntaxError),+ );+ expect(warn).toHaveBeenCalledTimes(1);+ });+});diff --git a/__tests__/hooks/use-websocket-regressions.test.ts b/__tests__/hooks/use-websocket-regressions.test.tsnew file mode 100644index 0000000000..2dcc7bdf85--- /dev/null+++ b/__tests__/hooks/use-websocket-regressions.test.ts@@ -0,0 +1,403 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { describe, it, expect, vi } from "vitest";+import { useWebSocket } from "#/hooks/use-websocket";++describe("useWebSocket", () => {+ const waitForConnection = async (result: {+ current: {+ isConnected: boolean;+ };+ }) => {+ await waitFor(+ () => {+ expect(result.current.isConnected).toBe(true);+ },+ { timeout: 5000 },+ );+ };++ it("should send the session key before application messages on every connection", async () => {+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static instance: MockWebSocket | null = null;+ static readonly instances: MockWebSocket[] = [];++ readonly url: string;+ readonly sent: 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;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instance = this;+ MockWebSocket.instances.push(this);+ queueMicrotask(() => {+ this.readyState = MockWebSocket.OPEN;+ this.onopen?.(new Event("open"));+ });+ }++ send(data: string) {+ if (this.readyState !== MockWebSocket.OPEN) {+ throw new DOMException("WebSocket is not open", "InvalidStateError");+ }+ this.sent.push(data);+ }++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);+ const sessionApiKey = `sk-oh-${"a".repeat(64)}`;+ const expectedFrames = [+ JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),+ "application-message",+ ];++ try {+ const { result, unmount } = renderHook(() =>+ useWebSocket("ws://acme.com/ws", {+ sessionApiKey,+ onOpen: () => MockWebSocket.instance?.send("application-message"),+ }),+ );+ const firstSocket = MockWebSocket.instance!;++ expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);+ expect(firstSocket.sent).toEqual([]);+ await waitForConnection(result);++ expect(firstSocket.url).toBe("ws://acme.com/ws");+ expect(firstSocket.sent).toEqual(expectedFrames);++ act(() => {+ result.current.reconnect();+ });++ await waitFor(() => {+ expect(MockWebSocket.instances).toHaveLength(2);+ expect(MockWebSocket.instances[1].sent).toEqual(expectedFrames);+ });++ unmount();+ } finally {+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instance = null;+ MockWebSocket.instances.length = 0;+ }+ });++ it("closes a handshake stuck in CONNECTING at the timeout and retries", async () => {+ // Arrange: a socket whose handshake never completes. Closing it while+ // CONNECTING fires error + close(1006), as browsers do.+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static readonly instances: MockWebSocket[] = [];++ 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;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instances.push(this);+ }++ send() {}++ close() {+ this.readyState = MockWebSocket.CLOSED;+ this.onerror?.(new Event("error"));+ this.onclose?.(+ new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),+ );+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0); // deterministic backoff++ try {+ const { unmount } = renderHook(() =>+ useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),+ );+ const firstSocket = MockWebSocket.instances[0];++ // Act/Assert: just before the timeout the handshake is still pending.+ await act(async () => {+ vi.advanceTimersByTime(9_999);+ });+ expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);+ expect(MockWebSocket.instances).toHaveLength(1);++ // At the timeout the stuck socket is closed (releasing the browser's+ // per-host handshake lock)...+ await act(async () => {+ vi.advanceTimersByTime(1);+ });+ expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED);++ // ...and a fresh attempt follows after the first backoff delay.+ await act(async () => {+ vi.advanceTimersByTime(1_000);+ });+ expect(MockWebSocket.instances).toHaveLength(2);++ unmount();+ } finally {+ vi.useRealTimers();+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instances.length = 0;+ }+ });++ it("does not close a socket that finished its handshake in time", async () => {+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static instance: MockWebSocket | null = null;++ 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;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instance = this;+ }++ send() {}++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);+ vi.useFakeTimers();++ try {+ const { unmount } = renderHook(() => useWebSocket("ws://acme.com/ws"));+ const socket = MockWebSocket.instance!;+ const closeSpy = vi.spyOn(socket, "close");++ // Act: the handshake completes, then the watchdog window elapses.+ await act(async () => {+ socket.readyState = MockWebSocket.OPEN;+ socket.onopen?.(new Event("open"));+ });+ await act(async () => {+ vi.advanceTimersByTime(60_000);+ });++ // Assert: the cleared watchdog never touched the healthy socket.+ expect(closeSpy).not.toHaveBeenCalled();+ expect(socket.readyState).toBe(MockWebSocket.OPEN);++ unmount();+ } finally {+ vi.useRealTimers();+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instance = null;+ }+ });++ it("spaces reconnect attempts with exponential backoff capped at 30s", async () => {+ // Arrange: every connection attempt fails immediately.+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static readonly instances: MockWebSocket[] = [];++ 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;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instances.push(this);+ queueMicrotask(() => {+ this.readyState = MockWebSocket.CLOSED;+ this.onclose?.(+ new CloseEvent("close", {+ code: 1006,+ reason: "",+ wasClean: false,+ }),+ );+ });+ }++ send() {}++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0); // strip the jitter++ const expectInstancesAfter = async (+ advanceMs: number,+ expected: number,+ ) => {+ await act(async () => {+ vi.advanceTimersByTime(advanceMs);+ });+ expect(MockWebSocket.instances).toHaveLength(expected);+ };++ try {+ const { unmount } = renderHook(() =>+ useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),+ );+ // Flush the first attempt's immediate failure.+ await act(async () => {});+ expect(MockWebSocket.instances).toHaveLength(1);++ // Act/Assert: retries land at 1s, then 2s, then 4s after each failure.+ await expectInstancesAfter(999, 1);+ await expectInstancesAfter(1, 2);+ await expectInstancesAfter(1_999, 2);+ await expectInstancesAfter(1, 3);+ await expectInstancesAfter(3_999, 3);+ await expectInstancesAfter(1, 4);+ await expectInstancesAfter(7_999, 4);+ await expectInstancesAfter(1, 5);+ await expectInstancesAfter(15_999, 5);+ await expectInstancesAfter(1, 6);++ // The sixth failure would double to 32s; the cap holds it at 30s...+ await expectInstancesAfter(29_999, 6);+ await expectInstancesAfter(1, 7);++ // ...and every failure after that stays at 30s rather than growing.+ await expectInstancesAfter(29_999, 7);+ await expectInstancesAfter(1, 8);++ unmount();+ } finally {+ vi.useRealTimers();+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instances.length = 0;+ }+ });++ it("ignores close/error events from a socket that was replaced", async () => {+ // Arrange: sockets that only emit events when the test fires them, so the+ // old socket's close can land *after* its replacement is open β the race+ // that used to overwrite the new socket's OPEN state.+ class MockWebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static readonly instances: MockWebSocket[] = [];++ 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;++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instances.push(this);+ }++ send() {}++ close() {+ this.readyState = MockWebSocket.CLOSED;+ }++ emitOpen() {+ this.readyState = MockWebSocket.OPEN;+ this.onopen?.(new Event("open"));+ }++ emitFailure() {+ this.onerror?.(new Event("error"));+ this.emitClose();+ }++ emitClose() {+ this.onclose?.(+ new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),+ );+ }+ }++ const originalWebSocket = globalThis.WebSocket;+ vi.stubGlobal("WebSocket", MockWebSocket);++ const onCloseSpy = vi.fn();+ const onErrorSpy = vi.fn();++ try {+ const { result, unmount } = renderHook(() =>+ useWebSocket("ws://acme.com/ws", {+ onClose: onCloseSpy,+ onError: onErrorSpy,+ }),+ );+ const staleSocket = MockWebSocket.instances[0];+ act(() => staleSocket.emitOpen());++ // Act: replace the socket, open the replacement, then let the stale+ // socket's error + close events land late.+ act(() => {+ result.current.reconnect();+ });+ const currentSocket = MockWebSocket.instances[1];+ act(() => currentSocket.emitOpen());+ act(() => staleSocket.emitFailure());++ // Assert: the stale socket's events reach neither handler...+ expect(onCloseSpy).not.toHaveBeenCalled();+ expect(onErrorSpy).not.toHaveBeenCalled();++ // ...while the current socket's close still notifies as before.+ act(() => currentSocket.emitClose());+ expect(onCloseSpy).toHaveBeenCalledOnce();+ expect(onErrorSpy).toHaveBeenCalledOnce();++ unmount();+ } finally {+ globalThis.WebSocket = originalWebSocket;+ MockWebSocket.instances.length = 0;+ }+ });+});diff --git a/__tests__/hooks/use-websocket.test.ts b/__tests__/hooks/use-websocket.test.tsindex bbba20a619..04daae4784 100644--- a/__tests__/hooks/use-websocket.test.ts+++ b/__tests__/hooks/use-websocket.test.ts@@ -1,857 +1,573 @@-/**- * TODO: Fix flaky WebSocket tests (https://github.com/OpenHands/OpenHands/issues/11944)- *- * Several tests in this file are skipped because they fail intermittently in CI- * but pass locally. The SUSPECTED root cause is that `wsLink.broadcast()` sends messages- * to ALL connected clients across all tests, causing cross-test contamination- * when tests run in parallel with Vitest v4.- */-import { act, renderHook, waitFor } from "@testing-library/react";-import {- describe,- it,- expect,- beforeAll,- afterAll,- afterEach,- vi,-} from "vitest";-import { ws } from "msw";-import { setupServer } from "msw/node";-import { useWebSocket } from "#/hooks/use-websocket";--describe("useWebSocket", () => {- // MSW WebSocket mock setup- const wsLink = ws.link("ws://acme.com/ws");-- const mswServer = setupServer(- wsLink.addEventListener("connection", ({ client, server }) => {- // Establish the connection- server.connect();-- // Send a welcome message to confirm connection- client.send("Welcome to the WebSocket!");- }),- );-- beforeAll(() =>- mswServer.listen({- onUnhandledRequest: "warn",- }),- );- afterEach(() => mswServer.resetHandlers());- afterAll(() => mswServer.close());-- const waitForConnection = async (result: {- current: {- isConnected: boolean;- };- }) => {- await waitFor(- () => {- expect(result.current.isConnected).toBe(true);- },- { timeout: 5000 },- );- };+import { act, renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useWebSocket, type WebSocketHookOptions } from "#/hooks/use-websocket";++class BrowserWebSocketDouble {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static instances: BrowserWebSocketDouble[] = [];++ readonly url: string;+ readyState = BrowserWebSocketDouble.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;+ readonly send = vi.fn();+ readonly close = vi.fn(() => {+ if (+ this.readyState === BrowserWebSocketDouble.CLOSING ||+ this.readyState === BrowserWebSocketDouble.CLOSED+ ) {+ return;+ }- it("should establish a WebSocket connection", async () => {- const messages: string[] = [];- const { result } = renderHook(() =>- useWebSocket("ws://acme.com/ws", {- onMessage: (event) => messages.push(event.data),+ this.emitClose(1000, "Normal closure");+ });++ constructor(url: string) {+ this.url = url;+ BrowserWebSocketDouble.instances.push(this);+ }++ open() {+ this.readyState = BrowserWebSocketDouble.OPEN;+ this.onopen?.(new Event("open"));+ }++ receive(data: unknown) {+ this.onmessage?.(new MessageEvent("message", { data }));+ }++ emitError() {+ this.onerror?.(new Event("error"));+ }++ emitClose(code: number, reason = "") {+ this.readyState = BrowserWebSocketDouble.CLOSED;+ this.onclose?.(+ new CloseEvent("close", {+ code,+ reason,+ wasClean: code === 1000,}),);+ }++ static reset() {+ BrowserWebSocketDouble.instances = [];+ }+}++const renderWebSocket = (url: string, options?: WebSocketHookOptions) => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ return renderHook(() => useWebSocket(url, options));+};++const getSocket = (index = BrowserWebSocketDouble.instances.length - 1) => {+ const socket = BrowserWebSocketDouble.instances[index];+ if (!socket) {+ throw new Error(`Expected WebSocket instance at index ${index}`);+ }+ return socket;+};++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ BrowserWebSocketDouble.reset();+});- // Initially should not be connected+describe("useWebSocket connection lifecycle", () => {+ it("connects with serialized query parameters and reports an open connection", () => {+ const onOpen = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", {+ queryParams: { token: "abc 123", includeDrafts: false },+ onOpen,+ });+ const socket = getSocket();++ expect(socket.url).toBe(+ "ws://acme.test/events?token=abc+123&includeDrafts=false",+ );expect(result.current.isConnected).toBe(false);+ expect(result.current.socket).toBe(null);- // Wait for connection to be established- await waitForConnection(result);+ act(() => socket.open());- // Should deliver the welcome message from our mock via onMessage- await waitFor(() => {- expect(messages).toContain("Welcome to the WebSocket!");- });-- // Confirm that the WebSocket connection is established when the hook is used- expect(result.current.socket).toBeTruthy();+ expect(result.current.isConnected).toBe(true);+ expect(result.current.socket).toBe(socket);+ expect(result.current.error).toBe(null);+ expect(result.current.isReconnecting).toBe(false);+ expect(result.current.attemptCount).toBe(0);+ expect(onOpen).toHaveBeenCalledWith(+ expect.objectContaining({ type: "open" }),+ );});- it("should not retain an unbounded raw message history", async () => {- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static instance: MockWebSocket | null = null;-- 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instance = this;- queueMicrotask(() => {- this.readyState = MockWebSocket.OPEN;- this.onopen?.(new Event("open"));- });- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- this.onclose?.(- new CloseEvent("close", {- code: 1000,- reason: "Normal closure",- wasClean: true,- }),- );- }- }+ it("does not connect until the URL becomes non-blank", () => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ const { result, rerender } = renderHook(+ ({ url }: { url: string }) => useWebSocket(url),+ { initialProps: { url: "" } },+ );- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);+ expect(BrowserWebSocketDouble.instances).toHaveLength(0);+ expect(result.current.socket).toBe(null);- try {- const messages: string[] = [];- const { result, unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", {- onMessage: (event) => messages.push(event.data),+ rerender({ url: " " });+ expect(BrowserWebSocketDouble.instances).toHaveLength(0);++ rerender({ url: "ws://acme.test/events" });+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ expect(getSocket().url).toBe("ws://acme.test/events");+ });++ it("uses the latest callbacks without replacing the active connection", () => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ const originalOnMessage = vi.fn();+ const latestOnMessage = vi.fn();+ const { result, rerender } = renderHook(+ ({ onMessage }: { onMessage: (event: MessageEvent) => void }) =>+ useWebSocket("ws://acme.test/events", {+ onMessage,}),- );-- await waitForConnection(result);-- act(() => {- MockWebSocket.instance?.onmessage?.(- new MessageEvent("message", { data: "first" }),- );- MockWebSocket.instance?.onmessage?.(- new MessageEvent("message", { data: "second" }),- );- MockWebSocket.instance?.onmessage?.(- new MessageEvent("message", { data: "third" }),- );- });-- // Every frame is delivered via onMessage, but the hook retains no raw- // message history of its own β not even the latest.- expect(messages).toEqual(["first", "second", "third"]);- expect("lastMessage" in result.current).toBe(false);- expect("messages" in result.current).toBe(false);-- unmount();- } finally {- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instance = null;- }+ { initialProps: { onMessage: originalOnMessage } },+ );+ const socket = getSocket();++ act(() => socket.open());+ rerender({ onMessage: latestOnMessage });+ act(() => socket.receive({ sequence: 7 }));++ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ expect(originalOnMessage).not.toHaveBeenCalled();+ expect(latestOnMessage).toHaveBeenCalledWith(+ expect.objectContaining({ data: { sequence: 7 } }),+ );+ expect("messages" in result.current).toBe(false);+ // The hook intentionally does not expose per-message state; consumers+ // read messages through the onMessage callback only.+ expect("lastMessage" in result.current).toBe(false);});- it("should handle connection errors gracefully", async () => {- // Create a mock that will simulate an error- const errorLink = ws.link("ws://error-test.com/ws");- mswServer.use(- errorLink.addEventListener("connection", ({ client }) => {- // Simulate an error by closing the connection immediately- client.close(1006, "Connection failed");+ it("delivers the final asynchronous close after clearing the URL", () => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ const onClose = vi.fn();+ const { rerender } = renderHook(+ ({ url }: { url: string }) => useWebSocket(url, { onClose }),+ { initialProps: { url: "ws://acme.test/events" } },+ );+ const socket = getSocket();+ act(() => socket.open());+ socket.close.mockImplementation(() => {+ socket.readyState = BrowserWebSocketDouble.CLOSED;+ });+ rerender({ url: "" });+ expect(socket.close).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();+ act(() => socket.emitClose(1000, "Finished after URL cleared"));+ expect(onClose).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ code: 1000,+ reason: "Finished after URL cleared",}),);+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ });++ it("handles messages and native errors without optional callbacks", () => {+ const { result } = renderWebSocket("ws://acme.test/events");+ const socket = getSocket();- const { result } = renderHook(() => useWebSocket("ws://error-test.com/ws"));+ act(() => socket.open());+ // Delivering a message without any onMessage callback must not throw or+ // disturb the connection state.+ act(() => socket.receive({ sequence: 8 }));+ expect(result.current.isConnected).toBe(true);- // Initially should not be connected and no error+ act(() => socket.emitError());expect(result.current.isConnected).toBe(false);expect(result.current.error).toBe(null);+ });- // Wait for the connection to fail- await waitFor(() => {- expect(result.current.isConnected).toBe(false);- });-- // Should have error information (the close event should trigger error state)- await waitFor(() => {- expect(result.current.error).not.toBe(null);- });+ it("handles messages and native errors when options omit callbacks", () => {+ const { result } = renderWebSocket("ws://acme.test/events", {});+ const socket = getSocket();- expect(result.current.error).toBeInstanceOf(Error);- // Should have meaningful error message (could be from onerror or onclose)- expect(- result.current.error?.message.includes("WebSocket closed with code 1006"),- ).toBe(true);+ act(() => socket.open());+ // An empty options object still omits onMessage; delivery must be a no-op+ // that leaves the connection intact.+ act(() => socket.receive({ sequence: 9 }));+ expect(result.current.isConnected).toBe(true);- // Should not crash the application- expect(result.current.socket).toBeTruthy();+ act(() => socket.emitError());+ expect(result.current.isConnected).toBe(false);+ expect(result.current.error).toBe(null);});- it.skip("should close the WebSocket connection on unmount", async () => {- const { result, unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws"),+ it("reports native socket errors through the current error callback", () => {+ const onError = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", { onError });+ const socket = getSocket();++ act(() => socket.open());+ expect(result.current.isConnected).toBe(true);++ act(() => socket.emitError());++ expect(result.current.isConnected).toBe(false);+ expect(result.current.error).toBe(null);+ expect(onError).toHaveBeenCalledWith(+ expect.objectContaining({ type: "error" }),);+ });- // Wait for connection to be established- await waitFor(() => {- expect(result.current.isConnected).toBe(true);+ it("reports a normal close without treating it as an error", () => {+ const onClose = vi.fn();+ const onError = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", {+ onClose,+ onError,});+ const socket = getSocket();- // Verify connection is active- expect(result.current.isConnected).toBe(true);- expect(result.current.socket).toBeTruthy();+ act(() => socket.open());+ act(() => socket.emitClose(1000, "Finished"));++ expect(result.current.isConnected).toBe(false);+ expect(result.current.error).toBe(null);+ expect(result.current.isReconnecting).toBe(false);+ expect(onClose).toHaveBeenCalledWith(+ expect.objectContaining({ code: 1000, reason: "Finished" }),+ );+ expect(onError).not.toHaveBeenCalled();+ });- const closeSpy = vi.spyOn(result.current.socket!, "close");+ it("turns an unexpected close into an error for consumers", () => {+ const onClose = vi.fn();+ const onError = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", {+ onClose,+ onError,+ });+ const socket = getSocket();- // Unmount the component (this should trigger the useEffect cleanup)- unmount();+ act(() => socket.emitClose(4001, "Authentication expired"));- // Verify that WebSocket close was called during cleanup- expect(closeSpy).toHaveBeenCalledOnce();+ expect(result.current.error).toEqual(+ new Error("WebSocket closed with code 4001: Authentication expired"),+ );+ expect(onError).toHaveBeenCalledWith(+ expect.objectContaining({ code: 4001 }),+ );+ expect(onClose).toHaveBeenCalledWith(+ expect.objectContaining({ code: 4001 }),+ );});- it("should support query parameters in WebSocket URL", async () => {- // 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;-- 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;-- constructor(url: string) {- this.url = url;- queueMicrotask(() => {- this.readyState = MockWebSocket.OPEN;- this.onopen?.(new Event("open"));- });- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- this.onclose?.(- new CloseEvent("close", {- code: 1000,- reason: "Normal closure",- wasClean: true,- }),- );- }- }+ it("provides a useful fallback when an unexpected close has no reason", () => {+ const { result } = renderWebSocket("ws://acme.test/events");- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);+ act(() => getSocket().emitClose(1006));- try {- const baseUrl = "ws://acme.com/ws";- const queryParams = {- token: "abc123",- userId: "user456",- version: "v1",- };+ expect(result.current.error?.message).toBe(+ "WebSocket closed with code 1006: Connection closed unexpectedly",+ );+ });+});- const { result, unmount } = renderHook(() =>- useWebSocket(baseUrl, { queryParams }),- );+describe("useWebSocket messaging", () => {+ it("sends data only while the connection is open", () => {+ const { result } = renderWebSocket("ws://acme.test/events");+ const socket = getSocket();+ const payload = new Blob(["payload"]);- await waitForConnection(result);+ act(() => result.current.sendMessage("too early"));+ expect(socket.send).not.toHaveBeenCalled();- // 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",- );+ act(() => socket.open());+ act(() => result.current.sendMessage(payload));+ expect(socket.send).toHaveBeenCalledWith(payload);- unmount();- } finally {- globalThis.WebSocket = originalWebSocket;- }+ act(() => socket.emitClose(1000));+ act(() => result.current.sendMessage("too late"));+ expect(socket.send).toHaveBeenCalledOnce();});- it("should send the session key before application messages on every connection", async () => {- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static instance: MockWebSocket | null = null;- static readonly instances: MockWebSocket[] = [];-- readonly url: string;- readonly sent: 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instance = this;- MockWebSocket.instances.push(this);- queueMicrotask(() => {- this.readyState = MockWebSocket.OPEN;- this.onopen?.(new Event("open"));- });- }-- send(data: string) {- if (this.readyState !== MockWebSocket.OPEN) {- throw new DOMException("WebSocket is not open", "InvalidStateError");- }- this.sent.push(data);- }-- close() {- this.readyState = MockWebSocket.CLOSED;- }- }+ it("ignores sends before a socket exists", () => {+ const { result } = renderWebSocket("");- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);- const sessionApiKey = `sk-oh-${"a".repeat(64)}`;- const expectedFrames = [- JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),- "application-message",- ];-- try {- const { result, unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", {- sessionApiKey,- onOpen: () => MockWebSocket.instance?.send("application-message"),- }),- );- const firstSocket = MockWebSocket.instance!;-- expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);- expect(firstSocket.sent).toEqual([]);- await waitForConnection(result);-- expect(firstSocket.url).toBe("ws://acme.com/ws");- expect(firstSocket.sent).toEqual(expectedFrames);-- act(() => {- result.current.reconnect();- });-- await waitFor(() => {- expect(MockWebSocket.instances).toHaveLength(2);- expect(MockWebSocket.instances[1].sent).toEqual(expectedFrames);- });-- unmount();- } finally {- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instance = null;- MockWebSocket.instances.length = 0;- }+ act(() => result.current.sendMessage("not connected"));++ expect(BrowserWebSocketDouble.instances).toHaveLength(0);});+});- // Skipped: flaky in CI - see comment at top of file- it.skip("should call onOpen handler when WebSocket connection opens", async () => {- const onOpenSpy = vi.fn();- const options = { onOpen: onOpenSpy };+describe("useWebSocket reconnection", () => {+ it("adds nonzero jitter to successive retry delays", () => {+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ renderWebSocket("ws://acme.test/events", { reconnect: { enabled: true } });+ act(() => getSocket().emitClose(1011, "Restart"));+ act(() => vi.advanceTimersByTime(1149));+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ act(() => vi.advanceTimersByTime(1));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ act(() => getSocket().emitClose(1011, "Still restarting"));+ act(() => vi.advanceTimersByTime(2299));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ act(() => vi.advanceTimersByTime(1));+ expect(BrowserWebSocketDouble.instances).toHaveLength(3);+ });- const { result } = renderHook(() =>- useWebSocket("ws://acme.com/ws", options),+ it("automatically retries after the reconnect delay and resets state on success", () => {+ vi.useFakeTimers();+ // Pin the jitter to zero so the first backoff is exactly the 1s base delay.+ vi.spyOn(Math, "random").mockReturnValue(0);+ const onError = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true },+ onError,+ });+ const firstSocket = getSocket();++ act(() => firstSocket.emitClose(1011, "Server restarted"));++ expect(result.current.isReconnecting).toBe(true);+ expect(result.current.attemptCount).toBe(1);+ expect(result.current.error).toEqual(+ new Error("WebSocket closed with code 1011: Server restarted"),);- // Initially should not be connected- expect(result.current.isConnected).toBe(false);- expect(onOpenSpy).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(999));+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);++ act(() => vi.advanceTimersByTime(1));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);- // Wait for connection to be established- await waitForConnection(result);+ const replacementSocket = getSocket();+ act(() => replacementSocket.open());- // onOpen handler should have been called- expect(onOpenSpy).toHaveBeenCalledOnce();+ expect(result.current.isConnected).toBe(true);+ expect(result.current.error).toBe(null);+ expect(result.current.isReconnecting).toBe(false);+ expect(result.current.attemptCount).toBe(0);+ expect(onError).toHaveBeenCalledOnce();});- it("should call onClose handler when WebSocket connection closes", async () => {- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;-- 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;-- constructor(url: string) {- this.url = url;- queueMicrotask(() => {- this.readyState = MockWebSocket.OPEN;- this.onopen?.(new Event("open"));- });- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- this.onclose?.(- new CloseEvent("close", {- code: 1000,- reason: "Normal closure",- wasClean: true,- }),- );- }- }+ it("stops retrying after the configured maximum number of attempts", () => {+ vi.useFakeTimers();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true, maxAttempts: 1 },+ });++ act(() => getSocket().emitClose(1000));+ expect(result.current.attemptCount).toBe(1);- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);- const onCloseSpy = vi.fn();- const options = { onClose: onCloseSpy };+ act(() => getSocket().emitClose(1000));+ expect(result.current.isReconnecting).toBe(false);+ expect(result.current.attemptCount).toBe(1);- try {- const { result, unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", options),- );+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ });- await waitForConnection(result);+ it("disconnects an active connection without scheduling a retry", () => {+ vi.useFakeTimers();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true, maxAttempts: 3 },+ });+ const socket = getSocket();- act(() => {- result.current.disconnect();- });+ act(() => socket.open());+ act(() => result.current.disconnect());- await waitFor(() => {- expect(onCloseSpy).toHaveBeenCalledOnce();- });+ expect(socket.close).toHaveBeenCalledOnce();+ expect(result.current.isConnected).toBe(false);+ expect(result.current.isReconnecting).toBe(false);- unmount();- } finally {- globalThis.WebSocket = originalWebSocket;- }+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);});- it.skip("should call onMessage handler when WebSocket receives a message", async () => {- const onMessageSpy = vi.fn();- const options = { onMessage: onMessageSpy };+ it("does not report a disconnected socket's late close as a reconnectable error", () => {+ vi.useFakeTimers();+ const onError = vi.fn();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true },+ onError,+ });+ const socket = getSocket();++ act(() => socket.open());+ act(() => result.current.disconnect());+ act(() => socket.emitClose(1006, "Late network failure"));- const { result } = renderHook(() =>- useWebSocket("ws://acme.com/ws", options),+ expect(result.current.error?.message).toBe(+ "WebSocket closed with code 1006: Late network failure",);+ expect(onError).not.toHaveBeenCalled();+ expect(result.current.isReconnecting).toBe(false);- // Wait for connection to be established- await waitFor(() => {- expect(result.current.isConnected).toBe(true);- });+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ });- // onMessage handler should have been called for the welcome message- await waitFor(() => {- expect(onMessageSpy).toHaveBeenCalledOnce();+ it("cancels a pending automatic retry when disconnected", () => {+ vi.useFakeTimers();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true },});- // Send another message from the mock server- wsLink.broadcast("Hello from server!");+ act(() => getSocket().emitClose(1000));+ expect(result.current.isReconnecting).toBe(true);- // onMessage handler should have been called twice now- await waitFor(() => {- expect(onMessageSpy).toHaveBeenCalledTimes(2);- });- });+ act(() => result.current.disconnect());+ expect(result.current.isReconnecting).toBe(false);- it("should call onError handler when WebSocket encounters an error", async () => {- const onErrorSpy = vi.fn();- const options = { onError: onErrorSpy };+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ });- // Create a mock that will simulate an error- const errorLink = ws.link("ws://error-test.com/ws");- mswServer.use(- errorLink.addEventListener("connection", ({ client }) => {- // Simulate an error by closing the connection immediately- client.close(1006, "Connection failed");- }),- );+ it("manually replaces an active connection immediately", () => {+ const { result } = renderWebSocket("ws://acme.test/events");+ const firstSocket = getSocket();- const { result } = renderHook(() =>- useWebSocket("ws://error-test.com/ws", options),- );+ act(() => firstSocket.open());+ act(() => result.current.reconnect());- // Initially should not be connected and no error+ expect(firstSocket.close).toHaveBeenCalledOnce();+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);expect(result.current.isConnected).toBe(false);- expect(onErrorSpy).not.toHaveBeenCalled();+ expect(result.current.isReconnecting).toBe(false);+ expect(result.current.error).toBe(null);+ expect(result.current.attemptCount).toBe(0);+ });- // Wait for the connection to fail- await waitFor(() => {- expect(result.current.isConnected).toBe(false);+ it("manual reconnect supersedes a pending retry without creating a duplicate", () => {+ vi.useFakeTimers();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true },});+ const firstSocket = getSocket();- // Should have error information- await waitFor(() => {- expect(result.current.error).not.toBe(null);- });+ act(() => firstSocket.emitClose(1012, "Restarting"));+ expect(result.current.error).not.toBe(null);- // onError handler should have been called- expect(onErrorSpy).toHaveBeenCalled();- });+ act(() => result.current.reconnect());+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ expect(firstSocket.close).not.toHaveBeenCalled();+ expect(result.current.error).toBe(null);+ expect(result.current.attemptCount).toBe(0);- it.skip("should provide sendMessage function to send messages to WebSocket", async () => {- const { result } = renderHook(() => useWebSocket("ws://acme.com/ws"));+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ });- // Wait for connection to be established- await waitFor(() => {- expect(result.current.isConnected).toBe(true);+ it("keeps automatic retries enabled after a manual reconnect", () => {+ vi.useFakeTimers();+ const { result } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true, maxAttempts: 2 },});+ const firstSocket = getSocket();- // Should have a sendMessage function- expect(result.current.sendMessage).toBeDefined();- expect(typeof result.current.sendMessage).toBe("function");-- // Mock the WebSocket send method- const sendSpy = vi.spyOn(result.current.socket!, "send");+ act(() => result.current.reconnect());+ expect(firstSocket.close).toHaveBeenCalledOnce();+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);- // Send a message- result.current.sendMessage("Hello WebSocket!");+ act(() => getSocket().emitClose(1000));+ expect(result.current.isReconnecting).toBe(true);+ expect(result.current.attemptCount).toBe(1);- // Verify that WebSocket.send was called with the correct message- expect(sendSpy).toHaveBeenCalledOnce();- expect(sendSpy).toHaveBeenCalledWith("Hello WebSocket!");+ act(() => vi.advanceTimersByTime(3000));+ expect(BrowserWebSocketDouble.instances).toHaveLength(3);});- it("closes a handshake stuck in CONNECTING at the timeout and retries", async () => {- // Arrange: a socket whose handshake never completes. Closing it while- // CONNECTING fires error + close(1006), as browsers do.- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static readonly instances: MockWebSocket[] = [];-- 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instances.push(this);- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- this.onerror?.(new Event("error"));- this.onclose?.(- new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),- );- }- }+ it("manually reconnects with the latest URL", () => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ const { result, rerender } = renderHook(+ ({ url }: { url: string }) => useWebSocket(url),+ { initialProps: { url: "ws://acme.test/first" } },+ );- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);- vi.useFakeTimers();- vi.spyOn(Math, "random").mockReturnValue(0); // deterministic backoff-- try {- const { unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),- );- const firstSocket = MockWebSocket.instances[0];-- // Act/Assert: just before the timeout the handshake is still pending.- await act(async () => {- vi.advanceTimersByTime(9_999);- });- expect(firstSocket.readyState).toBe(MockWebSocket.CONNECTING);- expect(MockWebSocket.instances).toHaveLength(1);-- // At the timeout the stuck socket is closed (releasing the browser's- // per-host handshake lock)...- await act(async () => {- vi.advanceTimersByTime(1);- });- expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED);-- // ...and a fresh attempt follows after the first backoff delay.- await act(async () => {- vi.advanceTimersByTime(1_000);- });- expect(MockWebSocket.instances).toHaveLength(2);-- unmount();- } finally {- vi.useRealTimers();- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instances.length = 0;- }+ rerender({ url: "ws://acme.test/second" });+ const secondSocket = getSocket();+ expect(secondSocket.url).toBe("ws://acme.test/second");++ act(() => result.current.reconnect());++ expect(secondSocket.close).toHaveBeenCalledOnce();+ expect(BrowserWebSocketDouble.instances).toHaveLength(3);+ expect(getSocket().url).toBe("ws://acme.test/second");});- it("does not close a socket that finished its handshake in time", async () => {- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static instance: MockWebSocket | null = null;-- 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instance = this;- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- }- }+ it("can be explicitly connected after starting without a URL", () => {+ const { result } = renderWebSocket("");- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);- vi.useFakeTimers();+ act(() => result.current.disconnect());+ expect(BrowserWebSocketDouble.instances).toHaveLength(0);+ expect(result.current.isReconnecting).toBe(false);- try {- const { unmount } = renderHook(() => useWebSocket("ws://acme.com/ws"));- const socket = MockWebSocket.instance!;- const closeSpy = vi.spyOn(socket, "close");-- // Act: the handshake completes, then the watchdog window elapses.- await act(async () => {- socket.readyState = MockWebSocket.OPEN;- socket.onopen?.(new Event("open"));- });- await act(async () => {- vi.advanceTimersByTime(60_000);- });-- // Assert: the cleared watchdog never touched the healthy socket.- expect(closeSpy).not.toHaveBeenCalled();- expect(socket.readyState).toBe(MockWebSocket.OPEN);-- unmount();- } finally {- vi.useRealTimers();- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instance = null;- }+ act(() => result.current.reconnect());+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);+ expect(getSocket().url).toBe("");+ expect(result.current.isReconnecting).toBe(true);});+});- it("spaces reconnect attempts with exponential backoff capped at 30s", async () => {- // Arrange: every connection attempt fails immediately.- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static readonly instances: MockWebSocket[] = [];-- 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instances.push(this);- queueMicrotask(() => {- this.readyState = MockWebSocket.CLOSED;- this.onclose?.(- new CloseEvent("close", {- code: 1006,- reason: "",- wasClean: false,- }),- );- });- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- }- }+describe("useWebSocket cleanup", () => {+ it("closes a connecting socket on unmount", () => {+ const { unmount } = renderWebSocket("ws://acme.test/events");+ const socket = getSocket();- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);- vi.useFakeTimers();- vi.spyOn(Math, "random").mockReturnValue(0); // strip the jitter-- const expectInstancesAfter = async (- advanceMs: number,- expected: number,- ) => {- await act(async () => {- vi.advanceTimersByTime(advanceMs);- });- expect(MockWebSocket.instances).toHaveLength(expected);- };-- try {- const { unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", { reconnect: { enabled: true } }),- );- // Flush the first attempt's immediate failure.- await act(async () => {});- expect(MockWebSocket.instances).toHaveLength(1);-- // Act/Assert: retries land at 1s, then 2s, then 4s after each failure.- await expectInstancesAfter(999, 1);- await expectInstancesAfter(1, 2);- await expectInstancesAfter(1_999, 2);- await expectInstancesAfter(1, 3);- await expectInstancesAfter(3_999, 3);- await expectInstancesAfter(1, 4);- await expectInstancesAfter(7_999, 4);- await expectInstancesAfter(1, 5);- await expectInstancesAfter(15_999, 5);- await expectInstancesAfter(1, 6);-- // The sixth failure would double to 32s; the cap holds it at 30s...- await expectInstancesAfter(29_999, 6);- await expectInstancesAfter(1, 7);-- // ...and every failure after that stays at 30s rather than growing.- await expectInstancesAfter(29_999, 7);- await expectInstancesAfter(1, 8);-- unmount();- } finally {- vi.useRealTimers();- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instances.length = 0;- }- });+ unmount();- it("ignores close/error events from a socket that was replaced", async () => {- // Arrange: sockets that only emit events when the test fires them, so the- // old socket's close can land *after* its replacement is open β the race- // that used to overwrite the new socket's OPEN state.- class MockWebSocket {- static readonly CONNECTING = 0;- static readonly OPEN = 1;- static readonly CLOSING = 2;- static readonly CLOSED = 3;- static readonly instances: MockWebSocket[] = [];-- 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;-- constructor(url: string) {- this.url = url;- MockWebSocket.instances.push(this);- }-- send() {}-- close() {- this.readyState = MockWebSocket.CLOSED;- }-- emitOpen() {- this.readyState = MockWebSocket.OPEN;- this.onopen?.(new Event("open"));- }-- emitFailure() {- this.onerror?.(new Event("error"));- this.emitClose();- }-- emitClose() {- this.onclose?.(- new CloseEvent("close", { code: 1006, reason: "", wasClean: false }),- );- }- }+ expect(socket.close).toHaveBeenCalledOnce();+ });- const originalWebSocket = globalThis.WebSocket;- vi.stubGlobal("WebSocket", MockWebSocket);+ it("closes an open socket when the URL changes", () => {+ vi.stubGlobal("WebSocket", BrowserWebSocketDouble);+ const { rerender } = renderHook(+ ({ url }: { url: string }) => useWebSocket(url),+ { initialProps: { url: "ws://acme.test/first" } },+ );+ const firstSocket = getSocket();+ act(() => firstSocket.open());- const onCloseSpy = vi.fn();- const onErrorSpy = vi.fn();+ rerender({ url: "ws://acme.test/second" });- try {- const { result, unmount } = renderHook(() =>- useWebSocket("ws://acme.com/ws", {- onClose: onCloseSpy,- onError: onErrorSpy,- }),- );- const staleSocket = MockWebSocket.instances[0];- act(() => staleSocket.emitOpen());-- // Act: replace the socket, open the replacement, then let the stale- // socket's error + close events land late.- act(() => {- result.current.reconnect();- });- const currentSocket = MockWebSocket.instances[1];- act(() => currentSocket.emitOpen());- act(() => staleSocket.emitFailure());-- // Assert: the stale socket's events reach neither handler...- expect(onCloseSpy).not.toHaveBeenCalled();- expect(onErrorSpy).not.toHaveBeenCalled();-- // ...while the current socket's close still notifies as before.- act(() => currentSocket.emitClose());- expect(onCloseSpy).toHaveBeenCalledOnce();- expect(onErrorSpy).toHaveBeenCalledOnce();-- unmount();- } finally {- globalThis.WebSocket = originalWebSocket;- MockWebSocket.instances.length = 0;- }+ expect(firstSocket.close).toHaveBeenCalledOnce();+ expect(BrowserWebSocketDouble.instances).toHaveLength(2);+ expect(getSocket().url).toBe("ws://acme.test/second");});- it("should not send message when WebSocket is not connected", () => {- const { result } = renderHook(() => useWebSocket("ws://acme.com/ws"));+ it("does not close a socket that has already closed", () => {+ const { unmount } = renderWebSocket("ws://acme.test/events");+ const socket = getSocket();+ act(() => socket.emitClose(1000));- // Initially should not be connected- expect(result.current.isConnected).toBe(false);- expect(result.current.sendMessage).toBeDefined();+ unmount();- // Mock the WebSocket send method (even though socket might be null)- const sendSpy = vi.fn();- if (result.current.socket) {- vi.spyOn(result.current.socket, "send").mockImplementation(sendSpy);- }+ expect(socket.close).not.toHaveBeenCalled();+ });- // Try to send a message when not connected- result.current.sendMessage("Hello WebSocket!");+ it("cancels a pending retry on unmount", () => {+ vi.useFakeTimers();+ const { unmount } = renderWebSocket("ws://acme.test/events", {+ reconnect: { enabled: true },+ });+ act(() => getSocket().emitClose(1000));++ unmount();+ act(() => vi.advanceTimersByTime(3000));- // Verify that WebSocket.send was not called- expect(sendSpy).not.toHaveBeenCalled();+ expect(BrowserWebSocketDouble.instances).toHaveLength(1);});});