🙌 OpenHands: AI-Driven Development
fix(websocket): reconnect on foreground, disconnect cleanly on mobile background (#17982)
Tim O'Farrell6eba4c78c6f5
diff --git a/__tests__/components/chat/message-display-continuity.test.tsx b/__tests__/components/chat/message-display-continuity.test.tsxindex 09f00f4684..9844e725d2 100644--- a/__tests__/components/chat/message-display-continuity.test.tsx+++ b/__tests__/components/chat/message-display-continuity.test.tsx@@ -1,9 +1,7 @@import { describe, expect, it, vi, beforeEach } from "vitest";-import { screen } from "@testing-library/react";-import { QueryClient } from "@tanstack/react-query";+import { screen, render } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { MemoryRouter, Route, Routes } from "react-router";-import { render } from "@testing-library/react";-import { QueryClientProvider } from "@tanstack/react-query";import { useParamsMock, createUserMessageEvent } from "test-utils";import { ChatInterface } from "#/components/features/chat/chat-interface";import {@@ -16,7 +14,6 @@ import { useConfig } from "#/hooks/query/use-config";import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files";import { useEventStore } from "#/stores/use-event-store";import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";-import { useAgentState } from "#/hooks/use-agent-state";import { AgentState } from "#/types/agent-state";// Module-level mocks@@ -152,6 +149,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {mainConnectionState: "OPEN",sendMessage: vi.fn(),reconnect: vi.fn(),+ hasConnectedOnce: true,});// Put agent-server user events in the store@@ -183,6 +181,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {mainConnectionState: "OPEN",sendMessage: vi.fn(),reconnect: vi.fn(),+ hasConnectedOnce: true,});// Store is empty@@ -205,6 +204,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {mainConnectionState: "OPEN",sendMessage: vi.fn(),reconnect: vi.fn(),+ hasConnectedOnce: true,});useEventStore.setState({@@ -236,6 +236,7 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {mainConnectionState: "OPEN",sendMessage: vi.fn(),reconnect: vi.fn(),+ hasConnectedOnce: true,});// agent-server events in storediff --git a/__tests__/components/features/conversation/agent-status.test.tsx b/__tests__/components/features/conversation/agent-status.test.tsxindex 68e392f4cf..d5dab269e8 100644--- a/__tests__/components/features/conversation/agent-status.test.tsx+++ b/__tests__/components/features/conversation/agent-status.test.tsx@@ -17,6 +17,7 @@ const agentStatusMocks = vi.hoisted(() => ({useSubConversationTaskPolling: vi.fn(),useTaskPolling: vi.fn(),useUnifiedWebSocketStatus: vi.fn(),+ useHasConnectedOnceWebSocket: vi.fn(),}));vi.mock("react-i18next", () => ({@@ -52,6 +53,7 @@ vi.mock("#/hooks/query/use-task-polling", () => ({vi.mock("#/hooks/use-unified-websocket-status", () => ({useUnifiedWebSocketStatus: agentStatusMocks.useUnifiedWebSocketStatus,+ useHasConnectedOnceWebSocket: agentStatusMocks.useHasConnectedOnceWebSocket,}));vi.mock("#/icons/u-clock-three.svg?react", () => ({@@ -71,6 +73,7 @@ interface AgentStatusScenario {subConversationTaskStatus?: AppConversationStartTaskStatus;taskStatus?: AppConversationStartTaskStatus;webSocketStatus?: WebSocketConnectionState;+ hasConnectedOnce?: boolean;}function renderAgentStatus({@@ -84,6 +87,7 @@ function renderAgentStatus({subConversationTaskStatus,taskStatus,webSocketStatus = "OPEN",+ hasConnectedOnce = false,}: AgentStatusScenario = {}) {const handleResumeAgent = vi.fn();const handleStop = vi.fn();@@ -105,6 +109,9 @@ function renderAgentStatus({});agentStatusMocks.useTaskPolling.mockReturnValue({ taskStatus });agentStatusMocks.useUnifiedWebSocketStatus.mockReturnValue(webSocketStatus);+ agentStatusMocks.useHasConnectedOnceWebSocket.mockReturnValue(+ hasConnectedOnce,+ );const view = render(<AgentStatus@@ -168,6 +175,34 @@ describe("AgentStatus", () => {expect(setShouldShownAgentLoading).toHaveBeenCalledWith(true);});+ it("labels a first-ever connect as Connecting", () => {+ renderAgentStatus({+ webSocketStatus: "CONNECTING",+ hasConnectedOnce: false,+ });++ expect(+ screen.getByText(I18nKey.CHAT_INTERFACE$CONNECTING),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(I18nKey.CHAT_INTERFACE$RECONNECTING),+ ).not.toBeInTheDocument();+ });++ it("labels a reconnect after a prior successful connection as Reconnecting", () => {+ renderAgentStatus({+ webSocketStatus: "CONNECTING",+ hasConnectedOnce: true,+ });++ expect(+ screen.getByText(I18nKey.CHAT_INTERFACE$RECONNECTING),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(I18nKey.CHAT_INTERFACE$CONNECTING),+ ).not.toBeInTheDocument();+ });+it("shows local pause progress without reporting the agent as loading", () => {const { setShouldShownAgentLoading } = renderAgentStatus({isPausing: true,diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsxindex 6baf1bd9aa..5732154eef 100644--- a/__tests__/contexts/conversation-websocket-context.test.tsx+++ b/__tests__/contexts/conversation-websocket-context.test.tsx@@ -91,7 +91,7 @@ vi.mock("#/hooks/use-websocket", () => ({wsCapture.planningOptions = options;}}- return { socket: null, reconnect: vi.fn() };+ return { socket: null, reconnect: vi.fn(), disconnect: vi.fn() };}),}));vi.mock("#/hooks/query/use-user-conversation", () => ({diff --git a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsxindex c833f3b39d..b4e5af7483 100644--- a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx+++ b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx@@ -44,6 +44,8 @@ const socketCapture = vi.hoisted(() => ({planningSocket: null as TestSocket | null,reconnectMain: vi.fn(),reconnectPlanning: vi.fn(),+ disconnectMain: vi.fn(),+ disconnectPlanning: vi.fn(),queueMessage: vi.fn(),readConversationFile: vi.fn(),trackError: vi.fn(),@@ -72,6 +74,7 @@ vi.mock("#/hooks/use-websocket", () => ({return {socket: socketCapture.mainSocket,reconnect: socketCapture.reconnectMain,+ disconnect: socketCapture.disconnectMain,};}@@ -80,6 +83,7 @@ vi.mock("#/hooks/use-websocket", () => ({return {socket: socketCapture.planningSocket,reconnect: socketCapture.reconnectPlanning,+ disconnect: socketCapture.disconnectPlanning,};}),}));@@ -335,6 +339,8 @@ describe("Conversation websocket behavior", () => {socketCapture.planningSocket = null;socketCapture.reconnectMain.mockReset();socketCapture.reconnectPlanning.mockReset();+ socketCapture.disconnectMain.mockReset();+ socketCapture.disconnectPlanning.mockReset();socketCapture.queueMessage.mockReset().mockResolvedValue(undefined);socketCapture.readConversationFile.mockReset();socketCapture.trackError.mockReset();@@ -2245,3 +2251,273 @@ describe("Conversation websocket behavior", () => {expect(warn).toHaveBeenCalledTimes(1);});});++const MOBILE_USER_AGENT =+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15";+const DESKTOP_USER_AGENT =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36";++function setUserAgent(userAgent: string) {+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(userAgent);+}++function setVisibility(state: "visible" | "hidden") {+ Object.defineProperty(document, "visibilityState", {+ value: state,+ configurable: true,+ });+ document.dispatchEvent(new Event("visibilitychange"));+}++describe("Conversation websocket — page visibility reconnect (#17894)", () => {+ const originalVisibilityDescriptor = Object.getOwnPropertyDescriptor(+ Document.prototype,+ "visibilityState",+ );++ 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.disconnectMain.mockReset();+ socketCapture.disconnectPlanning.mockReset();+ contextCapture.current = null;+ historyCapture.result = {+ data: { events: [] },+ isPending: false,+ isFetching: false,+ isError: false,+ };+ useConversationStore.setState({+ conversationMode: "code",+ planContent: null,+ });+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ if (originalVisibilityDescriptor) {+ Object.defineProperty(+ document,+ "visibilityState",+ originalVisibilityDescriptor,+ );+ }+ });++ it("disconnects both sockets once the hide debounce elapses on a mobile user agent", () => {+ setUserAgent(MOBILE_USER_AGENT);+ renderProvider({ subConversations: [makeSubConversation()] });++ act(() => setVisibility("hidden"));+ // Still within the grace period: nothing torn down yet.+ expect(socketCapture.disconnectMain).not.toHaveBeenCalled();+ expect(socketCapture.disconnectPlanning).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(3_000);+ });++ expect(socketCapture.disconnectMain).toHaveBeenCalledOnce();+ expect(socketCapture.disconnectPlanning).toHaveBeenCalledOnce();+ });++ it("never tears a socket down for a quick glance away (flap guard)", () => {+ setUserAgent(MOBILE_USER_AGENT);+ renderProvider();++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(1_000);+ setVisibility("visible");+ vi.advanceTimersByTime(10_000);+ });++ expect(socketCapture.disconnectMain).not.toHaveBeenCalled();+ });++ it("does not disconnect on hide for a desktop user agent", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider();++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(10_000);+ });++ expect(socketCapture.disconnectMain).not.toHaveBeenCalled();+ expect(socketCapture.disconnectPlanning).not.toHaveBeenCalled();+ });++ it("immediately reconnects a stale socket on return to the foreground, regardless of platform", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider();+ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ // Nothing waits on a backoff timer: the foreground check fires the+ // reconnect synchronously off the visibility event itself.+ expect(socketCapture.reconnectMain).toHaveBeenCalledOnce();+ });++ it("does not reconnect an already-open socket on a foreground health check", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ const mainSocket = makeSocket(WebSocket.OPEN);+ socketCapture.mainSocket = mainSocket;+ renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));+ expect(screen.getByTestId("connection-state")).toHaveTextContent("OPEN");++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ expect(socketCapture.reconnectMain).not.toHaveBeenCalled();+ });++ it("reconnects whichever sockets are stale independent of the active conversation mode", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider({ subConversations: [makeSubConversation()] });+ useConversationStore.setState({ conversationMode: "plan" });+ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ act(() => planningOptions().onClose?.(new CloseEvent("close")));++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ // Unlike the manual `reconnect()` action (mode-gated), the foreground+ // health check always covers both — a mode switch while backgrounded+ // must not leave the other socket stale.+ expect(socketCapture.reconnectMain).toHaveBeenCalledOnce();+ expect(socketCapture.reconnectPlanning).toHaveBeenCalledOnce();+ });++ it("stops reacting to visibility changes after the provider unmounts", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const { unmount } = renderProvider();+ unmount();++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(10_000);+ });++ expect(socketCapture.disconnectMain).not.toHaveBeenCalled();+ });++ it("does not surface the connection-error banner for a drop that happens while the tab is hidden", () => {+ setUserAgent(MOBILE_USER_AGENT);+ renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));++ act(() => {+ setVisibility("hidden");+ // The OS kills the socket mid-background, ahead of our own debounced+ // disconnect — exactly the race this guards against.+ mainOptions().onError?.(new Event("error"));+ });++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(screen.getByTestId("connection-state")).toHaveTextContent("CLOSED");++ act(() => setVisibility("visible"));+ });++ it("still surfaces the connection-error banner for a drop that happens while visible", () => {+ setUserAgent(MOBILE_USER_AGENT);+ renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));++ act(() => mainOptions().onError?.(new Event("error")));++ expect(useErrorMessageStore.getState()).toMatchObject({+ errorMessage: SERVER_CONNECTION_ERROR_MESSAGE,+ errorType: "connection",+ });+ });++ it("does not surface the planning socket's connection-error banner while hidden", async () => {+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(0);+ setUserAgent(MOBILE_USER_AGENT);+ renderProvider({ subConversations: [makeSubConversation()] });+ await act(async () => planningOptions().onOpen?.(new Event("open")));++ act(() => {+ setVisibility("hidden");+ planningOptions().onError?.(new Event("error"));+ });++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();++ // Settle the pending (fake-timer) hide-debounce before the test ends: an+ // un-settled `setTimeout` surviving into `vi.useRealTimers()` in this+ // suite's `afterEach` otherwise leaks past this test.+ act(() => setVisibility("visible"));+ });++ it("clears a stale connection-error banner the instant the tab is foregrounded, ahead of the reconnect actually completing", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));+ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ useErrorMessageStore+ .getState()+ .setErrorMessage(SERVER_CONNECTION_ERROR_MESSAGE, "connection");++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ expect(useErrorMessageStore.getState().errorMessage).toBeNull();+ expect(socketCapture.reconnectMain).toHaveBeenCalledOnce();+ });++ it("leaves an unrelated sticky error alone on a foreground reconnect", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider();+ act(() => mainOptions().onOpen?.(new Event("open")));+ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ useErrorMessageStore+ .getState()+ .setErrorMessage("Bad API key", "conversation");++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ expect(useErrorMessageStore.getState().errorMessage).toBe("Bad API key");+ });++ it("exposes hasConnectedOnce so the UI can tell a reconnect from the first-ever connect", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ renderProvider();+ expect(contextCapture.current?.hasConnectedOnce).toBe(false);++ act(() => mainOptions().onOpen?.(new Event("open")));+ expect(contextCapture.current?.hasConnectedOnce).toBe(true);++ // Staying true through a subsequent drop is the whole point: it's what+ // lets the status badge read "Reconnecting" instead of "Connecting"+ // while the foreground health check is retrying.+ act(() => mainOptions().onClose?.(new CloseEvent("close")));+ expect(contextCapture.current?.hasConnectedOnce).toBe(true);+ });+});diff --git a/__tests__/hooks/use-page-visibility-reconnect.test.ts b/__tests__/hooks/use-page-visibility-reconnect.test.tsnew file mode 100644index 0000000000..ffa1c9b006--- /dev/null+++ b/__tests__/hooks/use-page-visibility-reconnect.test.ts@@ -0,0 +1,276 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { usePageVisibilityReconnect } from "#/hooks/use-page-visibility-reconnect";++const MOBILE_USER_AGENT =+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15";+const DESKTOP_USER_AGENT =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36";++function setUserAgent(userAgent: string) {+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(userAgent);+}++function setVisibility(state: "visible" | "hidden") {+ Object.defineProperty(document, "visibilityState", {+ value: state,+ configurable: true,+ });+ document.dispatchEvent(new Event("visibilitychange"));+}++describe("usePageVisibilityReconnect", () => {+ const originalVisibilityDescriptor = Object.getOwnPropertyDescriptor(+ Document.prototype,+ "visibilityState",+ );++ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ if (originalVisibilityDescriptor) {+ Object.defineProperty(+ document,+ "visibilityState",+ originalVisibilityDescriptor,+ );+ }+ });++ it("disconnects on a mobile user agent only after the hide debounce elapses", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => setVisibility("hidden"));+ expect(disconnect).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(2_999));+ expect(disconnect).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1));+ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("cancels the pending disconnect when the tab returns before the debounce fires", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(1_000);+ setVisibility("visible");+ vi.advanceTimersByTime(10_000);+ });++ expect(disconnect).not.toHaveBeenCalled();+ // The visible transition still runs the health check.+ expect(reconnectIfStale).toHaveBeenCalled();+ });++ it("never disconnects on a desktop user agent, however long the tab stays hidden", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(60_000);+ });++ expect(disconnect).not.toHaveBeenCalled();+ });++ it("restarts the debounce on repeated flapping instead of stacking timers", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(2_000);+ setVisibility("visible");+ setVisibility("hidden");+ vi.advanceTimersByTime(2_000);+ });+ // 4s of cumulative "hidden" time has elapsed, but each hide restarted a+ // fresh 3s window, so still nothing torn down.+ expect(disconnect).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1_000));+ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("runs the foreground health check on every visible transition, even without a prior disconnect", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ setVisibility("visible");+ });++ expect(reconnectIfStale).toHaveBeenCalledOnce();+ });++ it("reacts to pagehide/pageshow in addition to visibilitychange", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ window.dispatchEvent(new Event("pagehide"));+ vi.advanceTimersByTime(3_000);+ });+ expect(disconnect).toHaveBeenCalledOnce();++ act(() => window.dispatchEvent(new Event("pageshow")));+ expect(reconnectIfStale).toHaveBeenCalledOnce();+ });++ it("disconnects immediately on `freeze`, bypassing the hide debounce, even on desktop", () => {+ setUserAgent(DESKTOP_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => document.dispatchEvent(new Event("freeze")));++ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("cancels a pending debounced disconnect once `freeze` has already handled it", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ document.dispatchEvent(new Event("freeze"));+ vi.advanceTimersByTime(10_000);+ });++ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("reconnects immediately on `resume`", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => document.dispatchEvent(new Event("resume")));++ expect(reconnectIfStale).toHaveBeenCalledOnce();+ });++ it("does nothing when disabled", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ renderHook(() =>+ usePageVisibilityReconnect({+ enabled: false,+ disconnect,+ reconnectIfStale,+ }),+ );++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(10_000);+ setVisibility("visible");+ });++ expect(disconnect).not.toHaveBeenCalled();+ expect(reconnectIfStale).not.toHaveBeenCalled();+ });++ it("stops reacting once unmounted", () => {+ setUserAgent(MOBILE_USER_AGENT);+ const disconnect = vi.fn();+ const reconnectIfStale = vi.fn();+ const { unmount } = renderHook(() =>+ usePageVisibilityReconnect({+ enabled: true,+ disconnect,+ reconnectIfStale,+ }),+ );++ unmount();+ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(10_000);+ });++ expect(disconnect).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/utils/status.test.ts b/__tests__/utils/status.test.tsindex 68193f9016..28be714a25 100644--- a/__tests__/utils/status.test.ts+++ b/__tests__/utils/status.test.ts@@ -35,6 +35,33 @@ describe("getStatusCode", () => {expect(result).toBe(I18nKey.CHAT_INTERFACE$DISCONNECTED);});+ it("returns CONNECTING for a first-ever connect (hasConnectedOnce omitted)", () => {+ const result = getStatusCode("CONNECTING", ExecutionStatus.IDLE);+ expect(result).toBe(I18nKey.CHAT_INTERFACE$CONNECTING);+ });++ it("returns CONNECTING, not RECONNECTING, while hasConnectedOnce is false", () => {+ const result = getStatusCode(+ "CONNECTING",+ ExecutionStatus.IDLE,+ undefined,+ undefined,+ false,+ );+ expect(result).toBe(I18nKey.CHAT_INTERFACE$CONNECTING);+ });++ it("returns RECONNECTING when a previously-open connection is connecting again", () => {+ const result = getStatusCode(+ "CONNECTING",+ ExecutionStatus.IDLE,+ undefined,+ undefined,+ true,+ );+ expect(result).toBe(I18nKey.CHAT_INTERFACE$RECONNECTING);+ });+it("returns COMMON$WAITING_FOR_SANDBOX when task is waiting for sandbox", () => {const result = getStatusCode("OPEN", null, "WAITING_FOR_SANDBOX");expect(result).toBe(I18nKey.COMMON$WAITING_FOR_SANDBOX);diff --git a/src/components/features/controls/agent-status.tsx b/src/components/features/controls/agent-status.tsxindex 36629c3d3c..c7f5cb4ba0 100644--- a/src/components/features/controls/agent-status.tsx+++ b/src/components/features/controls/agent-status.tsx@@ -12,7 +12,10 @@ import { AgentLoading } from "./agent-loading";import { useConversationStore } from "#/stores/conversation-store";import CircleErrorIcon from "#/icons/circle-error.svg?react";import { useAgentState } from "#/hooks/use-agent-state";-import { useUnifiedWebSocketStatus } from "#/hooks/use-unified-websocket-status";+import {+ useHasConnectedOnceWebSocket,+ useUnifiedWebSocketStatus,+} from "#/hooks/use-unified-websocket-status";import { useTaskPolling } from "#/hooks/query/use-task-polling";import { useSubConversationTaskPolling } from "#/hooks/query/use-sub-conversation-task-polling";import { useAgentNotification } from "#/hooks/use-agent-notification";@@ -40,6 +43,7 @@ export function AgentStatus({// Trigger browser tab flash and notification sound on state changesuseAgentNotification(curAgentState);const webSocketStatus = useUnifiedWebSocketStatus();+ const hasConnectedOnce = useHasConnectedOnceWebSocket();const { data: conversation } = useActiveConversation();const { taskStatus } = useTaskPolling();@@ -57,6 +61,7 @@ export function AgentStatus({executionStatus ?? null,taskStatus,subConversationTaskStatus,+ hasConnectedOnce,);const shouldShownAgentLoading =diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex 5f822235a5..32f2ca50e8 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -12,6 +12,7 @@ import { ConversationClient } from "@openhands/typescript-client/clients";import { useQueryClient } from "@tanstack/react-query";import { useWebSocket, WebSocketHookOptions } from "#/hooks/use-websocket";+import { usePageVisibilityReconnect } from "#/hooks/use-page-visibility-reconnect";import { SERVER_CONNECTION_ERROR_MESSAGE } from "#/constants/server-connection-error";import { useEventStore } from "#/stores/use-event-store";import { useErrorMessageStore } from "#/stores/error-message-store";@@ -102,6 +103,12 @@ interface ConversationWebSocketContextType {sendMessage: (message: SendMessageRequest) => Promise<SendMessageResult>;isLoadingHistory: boolean;reconnect: () => void;+ /**+ * True once the main or planning socket has opened at least once for the+ * current conversation. Lets the UI say "Reconnecting" instead of the+ * first-connect "Connecting" — see `getStatusCode`.+ */+ hasConnectedOnce: boolean;}const ConversationWebSocketContext = createContext<@@ -1125,8 +1132,17 @@ export function ConversationWebSocketProvider({},onError: () => {setMainConnectionState("CLOSED");- // Only show error message if we've previously connected successfully- if (hasConnectedRefMain.current) {+ // Only show an error if we've previously connected successfully, and+ // the page is actually visible: a hidden tab is never watching this+ // banner, and a background-caused drop (mobile freezing the tab) is+ // about to be cleaned up and silently retried by+ // `usePageVisibilityReconnect` the moment the tab is foregrounded —+ // surfacing "Unable to connect" for it would just be a stale flash+ // the user sees on return instead of "Reconnecting".+ if (+ hasConnectedRefMain.current &&+ document.visibilityState !== "hidden"+ ) {setErrorMessage(SERVER_CONNECTION_ERROR_MESSAGE, "connection");}},@@ -1190,8 +1206,12 @@ export function ConversationWebSocketProvider({},onError: () => {setPlanningConnectionState("CLOSED");- // Only show error message if we've previously connected successfully- if (hasConnectedRefPlanning.current) {+ // See the main socket's onError: skip the banner for a hidden-tab+ // drop, which is about to be silently retried on foreground.+ if (+ hasConnectedRefPlanning.current &&+ document.visibilityState !== "hidden"+ ) {setErrorMessage(SERVER_CONNECTION_ERROR_MESSAGE, "connection");}},@@ -1208,13 +1228,17 @@ export function ConversationWebSocketProvider({// Only attempt WebSocket connection when we have a valid URL// This prevents connection attempts during task polling phaseconst websocketUrl = wsUrl;- const { socket: mainSocket, reconnect: reconnectMain } = useWebSocket(- websocketUrl || "",- mainWebsocketOptions,- );-- const { socket: planningAgentSocket, reconnect: reconnectPlanning } =- useWebSocket(planningAgentWsUrl || "", planningWebsocketOptions);+ const {+ socket: mainSocket,+ reconnect: reconnectMain,+ disconnect: disconnectMain,+ } = useWebSocket(websocketUrl || "", mainWebsocketOptions);++ const {+ socket: planningAgentSocket,+ reconnect: reconnectPlanning,+ disconnect: disconnectPlanning,+ } = useWebSocket(planningAgentWsUrl || "", planningWebsocketOptions);const reconnect = useCallback(() => {removeErrorMessage();@@ -1231,6 +1255,47 @@ export function ConversationWebSocketProvider({removeErrorMessage,]);+ // Mobile browsers freeze and discard backgrounded tabs, silently killing+ // the socket; this pre-empts that with a clean close on the way out and an+ // immediate, explicit reconnect on the way back — see+ // `usePageVisibilityReconnect` for the full rationale. Both sockets are+ // covered regardless of `conversationMode`: a mode switch while+ // backgrounded must not leave the *other* one stale.+ const disconnectForBackground = useCallback(() => {+ disconnectMain();+ disconnectPlanning();+ }, [disconnectMain, disconnectPlanning]);++ const reconnectStaleOnForeground = useCallback(() => {+ // Drop any "Unable to connect" banner left over from a background-caused+ // close the instant the tab is foregrounded, so the UI reads+ // "Reconnecting" (via `hasConnectedOnce`) rather than a stale error while+ // the reconnect below is in flight. `clearConnectionError` only clears+ // the connection-classified message, leaving any unrelated sticky error+ // (e.g. a misconfigured API key) untouched.+ clearConnectionError();+ if (websocketUrl && mainConnectionState !== "OPEN") {+ reconnectMain();+ }+ if (planningAgentWsUrl && planningConnectionState !== "OPEN") {+ reconnectPlanning();+ }+ }, [+ websocketUrl,+ mainConnectionState,+ planningAgentWsUrl,+ planningConnectionState,+ reconnectMain,+ reconnectPlanning,+ clearConnectionError,+ ]);++ usePageVisibilityReconnect({+ enabled: !!(websocketUrl || planningAgentWsUrl),+ disconnect: disconnectForBackground,+ reconnectIfStale: reconnectStaleOnForeground,+ });+// V1 send message function via WebSocket// Falls back to REST API queue when WebSocket is not connectedconst sendMessage = useCallback(@@ -1365,10 +1430,13 @@ export function ConversationWebSocketProvider({sendMessage,isLoadingHistory,reconnect,+ hasConnectedOnce:+ hasConnectedRefMain.current || hasConnectedRefPlanning.current,}),[connectionState,mainConnectionState,+ planningConnectionState,sendMessage,isLoadingHistory,reconnect,diff --git a/src/hooks/use-page-visibility-reconnect.ts b/src/hooks/use-page-visibility-reconnect.tsnew file mode 100644index 0000000000..958816b025--- /dev/null+++ b/src/hooks/use-page-visibility-reconnect.ts@@ -0,0 +1,127 @@+import { useEffect, useRef } from "react";+import { isMobileUserAgent } from "#/utils/utils";++/**+ * Grace period between the tab going hidden and us tearing the socket down.+ * Absorbs a quick app-switcher glance or alt-tab without touching the+ * connection; a mobile browser that is actually about to freeze the page+ * gives JS at least this long to run first, so a genuine backgrounding still+ * gets caught well before the OS kills the socket itself.+ */+const HIDE_DEBOUNCE_MS = 3_000;++export interface UsePageVisibilityReconnectOptions {+ /** Skip wiring listeners entirely when there is nothing to manage yet. */+ enabled: boolean;+ /**+ * Close the socket(s) cleanly. The debounced `visibilitychange`-hidden path+ * only calls this on mobile user agents: desktop browsers keep sockets+ * alive across ordinary tab switches, so tearing them down there would stop+ * live updates for no reason. The immediate `freeze` path calls this on any+ * platform, since by the time `freeze` fires the browser has already+ * decided to suspend the page. Either way, a clean (code 1000) close here+ * beats letting the OS discard the tab, which often surfaces as a non-1000+ * close and an error toast once the hook catches up.+ */+ disconnect: () => void;+ /**+ * Re-check connection health and reconnect anything that isn't open. Runs+ * on every return to the foreground, on every platform — a socket can die+ * in the background for reasons that have nothing to do with our own+ * teardown (OS sleep, a network blip, a proxy timeout), and this is the+ * single hook that catches all of them. Reconnecting bypasses the normal+ * backoff timer, which may be hours stale after the tab was frozen.+ */+ reconnectIfStale: () => void;+}++/**+ * Ties the conversation WebSocket's lifecycle to the page's visibility so a+ * mobile background/foreground cycle produces one clean disconnect and one+ * explicit, immediate reconnect — instead of the OS silently killing the+ * socket and an exponential-backoff timer (frozen along with everything else+ * while hidden) replaying a burst of stale retries once the timers unfreeze.+ */+export function usePageVisibilityReconnect({+ enabled,+ disconnect,+ reconnectIfStale,+}: UsePageVisibilityReconnectOptions): void {+ // Refs so the effect below doesn't need `disconnect`/`reconnectIfStale` in+ // its dependency array — both are recreated most renders, and re-running+ // the effect on every one of those would thrash the listeners for no+ // behavioral change.+ const disconnectRef = useRef(disconnect);+ disconnectRef.current = disconnect;+ const reconnectRef = useRef(reconnectIfStale);+ reconnectRef.current = reconnectIfStale;++ useEffect(() => {+ if (!enabled) return undefined;++ let hideTimeout: ReturnType<typeof setTimeout> | null = null;+ const clearHideTimeout = () => {+ if (hideTimeout !== null) {+ clearTimeout(hideTimeout);+ hideTimeout = null;+ }+ };++ const handleHidden = () => {+ if (!isMobileUserAgent()) return;+ // Restart rather than stack: rapid flapping keeps pushing this out+ // rather than ever accumulating a second pending teardown.+ clearHideTimeout();+ hideTimeout = setTimeout(() => {+ hideTimeout = null;+ disconnectRef.current();+ }, HIDE_DEBOUNCE_MS);+ };++ const handleVisible = () => {+ // A return inside the grace period cancels the pending teardown before+ // it ever runs — the flap guard: quick background/foreground cycles+ // never touch the socket at all.+ clearHideTimeout();+ reconnectRef.current();+ };++ const handleVisibilityChange = () => {+ if (document.visibilityState === "hidden") {+ handleHidden();+ } else {+ handleVisible();+ }+ };++ // `freeze` (Page Lifecycle API; Chromium only) fires synchronously right+ // before the browser suspends JS execution entirely, so there is no time+ // left to debounce — any pending timer from `handleHidden` would lose+ // this race, since a frozen page can't run its own `setTimeout`+ // callback. No user-agent check either: once the browser has decided to+ // freeze the page (immediately on mobile, or after a long-hidden desktop+ // tab), the socket is already on borrowed time regardless of platform.+ const handleFreeze = () => {+ clearHideTimeout();+ disconnectRef.current();+ };++ // `pagehide` fires when iOS Safari discards a backgrounded tab outright,+ // which is not guaranteed to be preceded by `visibilitychange`; `pageshow`+ // and `resume` are its restore counterparts, including a bfcache restore.+ document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("pagehide", handleHidden);+ window.addEventListener("pageshow", handleVisible);+ document.addEventListener("freeze", handleFreeze);+ document.addEventListener("resume", handleVisible);++ return () => {+ clearHideTimeout();+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ window.removeEventListener("pagehide", handleHidden);+ window.removeEventListener("pageshow", handleVisible);+ document.removeEventListener("freeze", handleFreeze);+ document.removeEventListener("resume", handleVisible);+ };+ }, [enabled]);+}diff --git a/src/hooks/use-unified-websocket-status.ts b/src/hooks/use-unified-websocket-status.tsindex 8786a8fd9b..50bf220434 100644--- a/src/hooks/use-unified-websocket-status.ts+++ b/src/hooks/use-unified-websocket-status.ts@@ -23,3 +23,13 @@ export function useMainWebSocketStatus(): WebSocketConnectionState {? conversationContext.mainConnectionState: "CLOSED";}++/**+ * True once the conversation has connected at least once. Pair with a+ * `CONNECTING` status to tell a first-ever connect from a reconnect — see+ * `getStatusCode`.+ */+export function useHasConnectedOnceWebSocket(): boolean {+ const conversationContext = useConversationWebSocket();+ return conversationContext ? conversationContext.hasConnectedOnce : false;+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 2f2e722c30..97e8e7c5de 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -10709,6 +10709,23 @@"uk": "З'єднання","ca": "Connectant"},+ "CHAT_INTERFACE$RECONNECTING": {+ "en": "Reconnecting...",+ "ja": "再接続中...",+ "zh-CN": "正在重新连接...",+ "zh-TW": "正在重新連線...",+ "ko-KR": "다시 연결 중...",+ "no": "Kobler til på nytt...",+ "it": "Riconnessione in corso...",+ "pt": "Reconectando...",+ "es": "Reconectando...",+ "ar": "جارٍ إعادة الاتصال...",+ "fr": "Reconnexion en cours...",+ "tr": "Yeniden bağlanıyor...",+ "de": "Verbindung wird wiederhergestellt...",+ "uk": "Повторне з'єднання...",+ "ca": "Reconnectant..."+ },"CHAT_INTERFACE$STOPPED": {"en": "Stopped","ja": "停止しました",diff --git a/src/utils/status.ts b/src/utils/status.tsindex f853ef7e2a..2b9ac74534 100644--- a/src/utils/status.ts+++ b/src/utils/status.ts@@ -66,6 +66,10 @@ export function getStatusCode(executionStatus: ExecutionStatus | null,taskStatus?: AppConversationStartTaskStatus | null,subConversationTaskStatus?: AppConversationStartTaskStatus | null,+ // Distinguishes a connection drop-and-recover from the very first+ // connect, so a background-tab reconnect reads "Reconnecting" instead of+ // the more alarming-sounding (and less accurate) "Connecting".+ hasConnectedOnce?: boolean,) {if (taskStatus === "ERROR" ||@@ -90,7 +94,9 @@ export function getStatusCode(case "CLOSING":return I18nKey.CHAT_INTERFACE$DISCONNECTED;case "CONNECTING":- return I18nKey.CHAT_INTERFACE$CONNECTING;+ return hasConnectedOnce+ ? I18nKey.CHAT_INTERFACE$RECONNECTING+ : I18nKey.CHAT_INTERFACE$CONNECTING;default:throw new Error(`Unknown WebsocketConnectionState: ${webSocketConnectionState}`,