Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): recover foreground websocket liveness (#618)

Gener6a01ed0b8ae4
diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.ts
index fef530d10..ee136869e 100644
--- a/src/web/src/lib/analytics.test.ts
+++ b/src/web/src/lib/analytics.test.ts
@@ -31,6 +31,7 @@ import {
trackSettingsUpdated,
trackCanvasLayoutChanged,
trackCommunityWsFrameDropped,
+ trackCommunityWsLifecycleRecovery,
trackCommunityWsReconcileComplete,
trackCommunityWsReconcileFailure,
} from "./analytics"
@@ -292,5 +293,25 @@ describe("analytics utility", () => {
reason: "async-rejection",
})
})
+
+ it("reports only bounded visible lifecycle recovery metadata", () => {
+ trackCommunityWsLifecycleRecovery({
+ trigger: "sentinel",
+ strategy: "replace",
+ socketReadyState: "open",
+ suspensionDuration: "over-2m",
+ userId: "user-1",
+ token: "secret",
+ nonce: "private-nonce",
+ payload: "private payload",
+ } as never)
+ expect(mockSendGTMEvent).toHaveBeenCalledWith({
+ event: "community_ws_lifecycle_recovery",
+ trigger: "sentinel",
+ strategy: "replace",
+ socketReadyState: "open",
+ suspensionDuration: "over-2m",
+ })
+ })
})
})
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 5be5d2382..6eaa23e7e 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -177,6 +177,29 @@ export type CommunityWsReconcilePolicy =
| "machines"
| "bot-audits"
+export type CommunityWsLifecycleRecoveryTrigger =
+ | "focus"
+ | "online"
+ | "pageshow"
+ | "resume"
+ | "sentinel"
+ | "visibility"
+
+export type CommunityWsLifecycleRecoveryStrategy = "replace" | "validate"
+
+export type CommunityWsSocketReadyState =
+ | "closed"
+ | "closing"
+ | "connecting"
+ | "none"
+ | "open"
+
+export type CommunityWsSuspensionDurationBucket =
+ | "30s-2m"
+ | "over-2m"
+ | "under-30s"
+ | "unknown"
+
function sendCommunityWsGTMEvent(payload: Record<string, unknown>) {
try {
sendGTMEvent(payload)
@@ -226,6 +249,21 @@ export function trackCommunityWsReconcileFailure(params: {
});
}
+export function trackCommunityWsLifecycleRecovery(params: {
+ trigger: CommunityWsLifecycleRecoveryTrigger
+ strategy: CommunityWsLifecycleRecoveryStrategy
+ socketReadyState: CommunityWsSocketReadyState
+ suspensionDuration: CommunityWsSuspensionDurationBucket
+}) {
+ sendCommunityWsGTMEvent({
+ event: "community_ws_lifecycle_recovery",
+ trigger: params.trigger,
+ strategy: params.strategy,
+ socketReadyState: params.socketReadyState,
+ suspensionDuration: params.suspensionDuration,
+ });
+}
+
// ─── P3 — Page-Level Behavior ───────────────────────────────────────────────
export function trackLandingCtaClicked(params: { cta_name: string }) {
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 93ba1d2fa..b2ee46949 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -5,6 +5,12 @@ import {
} from "@alook/shared"
import type { UseUserWsOptions } from "./use-user-ws"
+const mockTrackCommunityWsLifecycleRecovery = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/analytics", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/analytics")>(),
+ trackCommunityWsLifecycleRecovery: mockTrackCommunityWsLifecycleRecovery,
+}))
+
// --- Mock WebSocket ---
class MockWebSocket {
static CONNECTING = 0
@@ -39,24 +45,39 @@ class MockWebSocket {
vi.stubGlobal("WebSocket", MockWebSocket)
class MockEventTarget {
- listeners = new Map<string, Set<() => void>>()
- addEventListener(type: string, listener: () => void) {
- const listeners = this.listeners.get(type) ?? new Set<() => void>()
+ listeners = new Map<string, Set<(event: { target: unknown; persisted: boolean }) => void>>()
+ addEventListener(
+ type: string,
+ listener: (event: { target: unknown; persisted: boolean }) => void,
+ ) {
+ const listeners = this.listeners.get(type)
+ ?? new Set<(event: { target: unknown; persisted: boolean }) => void>()
listeners.add(listener)
this.listeners.set(type, listeners)
}
- removeEventListener(type: string, listener: () => void) {
+ removeEventListener(
+ type: string,
+ listener: (event: { target: unknown; persisted: boolean }) => void,
+ ) {
this.listeners.get(type)?.delete(listener)
}
- dispatch(type: string) {
- for (const listener of this.listeners.get(type) ?? []) listener()
+ dispatch(type: string, event: { target?: unknown; persisted?: boolean } = {}) {
+ for (const listener of this.listeners.get(type) ?? []) {
+ listener({
+ target: event.target ?? this,
+ persisted: event.persisted ?? false,
+ })
+ }
}
reset() {
this.listeners.clear()
}
}
-const mockDocument = Object.assign(new MockEventTarget(), { visibilityState: "visible" })
+const mockDocument = Object.assign(new MockEventTarget(), {
+ visibilityState: "visible",
+ wasDiscarded: false,
+})
const mockWindow = Object.assign(new MockEventTarget(), { location: { origin: "http://localhost:3000" } })
vi.stubGlobal("document", mockDocument)
vi.stubGlobal("window", mockWindow)
@@ -164,9 +185,18 @@ function dispatchHiddenToVisible() {
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
mockDocument.visibilityState = "visible"
+ mockDocument.wasDiscarded = false
mockDocument.dispatch("visibilitychange")
}
+function dispatchPageShow(persisted = false) {
+ mockWindow.dispatch("pageshow", { persisted })
+}
+
+function dispatchWindowFocus() {
+ mockWindow.dispatch("focus", { target: mockWindow })
+}
+
function resetMockState() {
MockWebSocket.instances = []
mockFetch.mockReset()
@@ -178,6 +208,7 @@ function resetMockState() {
effectMemo = new Map()
effectCounter = 0
latestHookResult = null
+ mockTrackCommunityWsLifecycleRecovery.mockReset()
mockDocument.visibilityState = "visible"
mockDocument.reset()
mockWindow.reset()
@@ -635,6 +666,293 @@ describe("useUserWs", () => {
expect(onConnectionStateChange).not.toHaveBeenLastCalledWith("reconnecting")
})
+ it("does not recover for initial pageshow or element focus", async () => {
+ setupTokenFetch()
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ const fetchCount = mockFetch.mock.calls.length
+
+ dispatchPageShow(false)
+ mockWindow.dispatch("focus", { target: { tagName: "INPUT" } })
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ expect(MockWebSocket.instances).toEqual([ws])
+ expect(connectionPings(ws)).toEqual([])
+ expect(mockTrackCommunityWsLifecycleRecovery).not.toHaveBeenCalled()
+ })
+
+ it("validates once for page-level focus and coalesces the foreground event storm", async () => {
+ setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ const fetchCount = mockFetch.mock.calls.length
+
+ dispatchWindowFocus()
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ mockWindow.dispatch("online")
+ mockDocument.dispatch("visibilitychange")
+
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenCalledOnce()
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenCalledWith({
+ trigger: "focus",
+ strategy: "validate",
+ socketReadyState: "open",
+ suspensionDuration: "unknown",
+ })
+
+ const [{ nonce }] = connectionPings(ws)
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS + 1)
+ expect(ws.closed).toBe(false)
+ expect(MockWebSocket.instances).toEqual([ws])
+ })
+
+ it("replaces expired CONNECTING and CLOSING sockets with bounded ready-state telemetry", async () => {
+ setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const connecting = MockWebSocket.instances[0]!
+
+ vi.setSystemTime(Date.now() + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS + 1)
+ dispatchWindowFocus()
+ await flushPromises()
+
+ expect(connecting.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenLastCalledWith({
+ trigger: "focus",
+ strategy: "replace",
+ socketReadyState: "connecting",
+ suspensionDuration: "unknown",
+ })
+
+ const closing = MockWebSocket.instances[1]!
+ closing.readyState = MockWebSocket.CLOSING
+ dispatchWindowFocus()
+ await flushPromises()
+
+ expect(closing.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(3)
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenLastCalledWith({
+ trigger: "focus",
+ strategy: "replace",
+ socketReadyState: "closing",
+ suspensionDuration: "unknown",
+ })
+ })
+
+ it("clears a pending reconnect when the page becomes hidden", async () => {
+ setupTokenFetch()
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateClose()
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ const fetchCount = mockFetch.mock.calls.length
+ await vi.advanceTimersByTimeAsync(60_000)
+
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ expect(MockWebSocket.instances).toEqual([ws])
+ })
+
+ it("clears a pending reconnect before an immediate foreground replacement", async () => {
+ setupTokenFetch()
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateMessage({ type: "auth.ok" })
+ first.simulateClose()
+
+ dispatchWindowFocus()
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("retires on freeze, stays network-silent while hidden, and resumes one replacement", async () => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn()
+ const onReconnect = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onDisconnect,
+ onReconnect,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateMessage({ type: "auth.ok" })
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ const hiddenFetchCount = mockFetch.mock.calls.length
+ const hiddenFrameCount = first.sent.length
+ mockDocument.dispatch("freeze")
+
+ expect(first.closed).toBe(true)
+ expect(onDisconnect).toHaveBeenCalledOnce()
+ expect(mockTrackCommunityWsLifecycleRecovery).not.toHaveBeenCalled()
+
+ vi.setSystemTime(Date.now() + mod.WS_FOREGROUND_SUSPENSION_GAP_MS + 1)
+ await vi.advanceTimersByTimeAsync(mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS * 2)
+ mockDocument.dispatch("resume")
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(hiddenFetchCount)
+ expect(first.sent).toHaveLength(hiddenFrameCount)
+ expect(MockWebSocket.instances).toEqual([first])
+ expect(mockTrackCommunityWsLifecycleRecovery).not.toHaveBeenCalled()
+
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ dispatchWindowFocus()
+ mockWindow.dispatch("online")
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(hiddenFetchCount + 1)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenCalledOnce()
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenCalledWith({
+ trigger: "resume",
+ strategy: "replace",
+ socketReadyState: "none",
+ suspensionDuration: "30s-2m",
+ })
+
+ const replacement = MockWebSocket.instances[1]!
+ replacement.simulateOpen()
+ const replacementFetchCount = mockFetch.mock.calls.length
+ dispatchWindowFocus()
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ mockWindow.dispatch("online")
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(replacementFetchCount)
+ expect(MockWebSocket.instances).toEqual([first, replacement])
+ expect(replacement.closed).toBe(false)
+ replacement.simulateMessage({ type: "auth.ok" })
+ expect(onReconnect).toHaveBeenCalledOnce()
+ })
+
+ it("recovers a focus-only zombie OPEN without close or error", async () => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn()
+ const onReconnect = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onDisconnect,
+ onReconnect,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateMessage({ type: "auth.ok" })
+
+ dispatchWindowFocus()
+ const [{ nonce }] = connectionPings(first)
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ mockWindow.dispatch("online")
+ expect(connectionPings(first)).toEqual([{ type: "connection.ping", nonce }])
+
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ await flushPromises()
+
+ expect(first.closed).toBe(true)
+ expect(onDisconnect).toHaveBeenCalledOnce()
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(MockWebSocket.instances).toHaveLength(2)
+
+ const replacement = MockWebSocket.instances[1]!
+ replacement.simulateOpen()
+ replacement.simulateMessage({ type: "auth.ok" })
+ expect(onReconnect).toHaveBeenCalledOnce()
+
+ first.simulateMessage({ type: "connection.pong", nonce })
+ first.simulateMessage({ type: "auth.ok" })
+ first.simulateClose()
+ expect(onDisconnect).toHaveBeenCalledOnce()
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("uses a wall-clock gap as a local visible sentinel without ordinary polling", async () => {
+ setupTokenFetch()
+ const intervalSpy = vi.spyOn(globalThis, "setInterval")
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ const fetchCount = mockFetch.mock.calls.length
+
+ await vi.advanceTimersByTimeAsync(mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS)
+ expect(connectionPings(ws)).toEqual([])
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+
+ const sentinelTick = intervalSpy.mock.calls.find(([, delay]) =>
+ delay === mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS)?.[0]
+ expect(sentinelTick).toBeTypeOf("function")
+ vi.setSystemTime(Date.now() + mod.WS_FOREGROUND_SUSPENSION_GAP_MS + 1)
+ ;(sentinelTick as () => void)()
+
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ expect(mockTrackCommunityWsLifecycleRecovery).toHaveBeenCalledWith({
+ trigger: "sentinel",
+ strategy: "validate",
+ socketReadyState: "open",
+ suspensionDuration: "unknown",
+ })
+ intervalSpy.mockRestore()
+ })
+
+ it("keeps sentinel work local while hidden and clears it on cleanup", async () => {
+ setupTokenFetch()
+ const intervalSpy = vi.spyOn(globalThis, "setInterval")
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ const hiddenFetchCount = mockFetch.mock.calls.length
+ const hiddenFrameCount = ws.sent.length
+ const sentinelTick = intervalSpy.mock.calls.find(([, delay]) =>
+ delay === mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS)?.[0]
+ expect(sentinelTick).toBeTypeOf("function")
+ vi.setSystemTime(Date.now() + mod.WS_FOREGROUND_SUSPENSION_GAP_MS + 1)
+ ;(sentinelTick as () => void)()
+
+ expect(mockFetch).toHaveBeenCalledTimes(hiddenFetchCount)
+ expect(ws.sent).toHaveLength(hiddenFrameCount)
+ expect(mockTrackCommunityWsLifecycleRecovery).not.toHaveBeenCalled()
+
+ effectCleanup?.()
+ mockDocument.visibilityState = "visible"
+ vi.setSystemTime(Date.now() + mod.WS_FOREGROUND_SUSPENSION_GAP_MS + 1)
+ await vi.advanceTimersByTimeAsync(mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS * 2)
+
+ expect(mockFetch).toHaveBeenCalledTimes(hiddenFetchCount)
+ expect(mockDocument.listeners.get("freeze")?.size ?? 0).toBe(0)
+ expect(mockDocument.listeners.get("resume")?.size ?? 0).toBe(0)
+ expect(mockWindow.listeners.get("focus")?.size ?? 0).toBe(0)
+ intervalSpy.mockRestore()
+ })
+
it("retires a CONNECTING socket hidden transition and ignores its late open", async () => {
setupTokenFetch()
const onConnectionStateChange = vi.fn()
@@ -689,6 +1007,34 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(2)
})
+ it("keeps an OPEN pre-auth event storm inside the original auth deadline", async () => {
+ setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ const fetchCount = mockFetch.mock.calls.length
+
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS - 1)
+ dispatchWindowFocus()
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ mockWindow.dispatch("online")
+ mockDocument.dispatch("visibilitychange")
+ await flushPromises()
+
+ expect(first.closed).toBe(false)
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ expect(MockWebSocket.instances).toEqual([first])
+
+ await vi.advanceTimersByTimeAsync(1)
+ expect(first.closed).toBe(true)
+
+ await vi.advanceTimersByTimeAsync(2_000)
+ await flushPromises()
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount + 1)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
it("coalesces foreground signals into one exact-nonce validation on the retained socket", async () => {
setupTokenFetch()
const onConnectionStateChange = vi.fn()
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 8abafca9c..b1b74d5a2 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -11,7 +11,12 @@ import {
} from "@alook/shared"
import {
trackCommunityWsFrameDropped,
+ trackCommunityWsLifecycleRecovery,
type CommunityWsFrameDropReason,
+ type CommunityWsLifecycleRecoveryStrategy,
+ type CommunityWsLifecycleRecoveryTrigger,
+ type CommunityWsSocketReadyState,
+ type CommunityWsSuspensionDurationBucket,
} from "@/lib/analytics"
import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"
import { websocketUrl } from "@/lib/websocket-url"
@@ -21,6 +26,8 @@ const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS)
const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
const WS_TOKEN_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_TOKEN_TIMEOUT_MS) || 10_000
export const WS_CONNECTION_VALIDATION_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_CONNECT_TIMEOUT_MS) || 10_000
+export const WS_FOREGROUND_SENTINEL_INTERVAL_MS = 10_000
+export const WS_FOREGROUND_SUSPENSION_GAP_MS = 30_000
type PendingConnectionValidation = {
ws: WebSocket
@@ -33,6 +40,31 @@ function isPageHidden(): boolean {
return typeof document !== "undefined" && document.visibilityState === "hidden"
}
+function socketReadyState(ws: WebSocket | null): CommunityWsSocketReadyState {
+ if (!ws) return "none"
+ switch (ws.readyState) {
+ case WebSocket.CONNECTING:
+ return "connecting"
+ case WebSocket.OPEN:
+ return "open"
+ case WebSocket.CLOSING:
+ return "closing"
+ default:
+ return "closed"
+ }
+}
+
+function suspensionDurationBucket(
+ suspendedAt: number | null,
+ now: number,
+): CommunityWsSuspensionDurationBucket {
+ if (suspendedAt === null) return "unknown"
+ const durationMs = Math.max(0, now - suspendedAt)
+ if (durationMs < 30_000) return "under-30s"
+ if (durationMs < 120_000) return "30s-2m"
+ return "over-2m"
+}
+
/**
* Incoming WS message shape delivered to the `onMessage` handler.
*
@@ -114,6 +146,10 @@ export function useUserWs(
const connectionGenerationRef = useRef(0)
const connectionValidationRef = useRef<PendingConnectionValidation | null>(null)
const connectionValidationNeededRef = useRef(isPageHidden())
+ const frozenRef = useRef(false)
+ const suspendedAtRef = useRef<number | null>(null)
+ const sentinelIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
+ const lastSentinelTickAtRef = useRef(0)
useEffect(() => {
onMessageRef.current = onMessage
@@ -152,6 +188,15 @@ export function useUserWs(
if (pending) clearTimeout(pending.timeout)
}, [])
+ const abortPendingToken = useCallback(() => {
+ tokenAbortRef.current?.abort()
+ tokenAbortRef.current = null
+ if (tokenTimeoutRef.current !== null) {
+ clearTimeout(tokenTimeoutRef.current)
+ tokenTimeoutRef.current = null
+ }
+ }, [])
+
const stopHeartbeat = useCallback(() => {
if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
@@ -161,6 +206,7 @@ export function useUserWs(
stopHeartbeat()
if (
isPageHidden()
+ || frozenRef.current
|| ws !== wsRef.current
|| generation !== connectionGenerationRef.current
|| authenticatedGenerationRef.current !== generation
@@ -205,8 +251,9 @@ export function useUserWs(
) return
clearConnectionValidation()
retireSocket()
- publishConnectionPhase(isPageHidden() ? "suspended" : "reconnecting")
- if (!isPageHidden()) void connectRef.current?.()
+ const suspended = isPageHidden() || frozenRef.current
+ publishConnectionPhase(suspended ? "suspended" : "reconnecting")
+ if (!suspended) void connectRef.current?.()
}, [clearConnectionValidation, publishConnectionPhase, retireSocket])
const validateCurrentConnection = useCallback((ws: WebSocket, generation: number) => {
@@ -238,7 +285,7 @@ export function useUserWs(
const scheduleReconnect = useCallback((generation: number) => {
if (generation !== connectionGenerationRef.current) return
- if (isPageHidden()) return
+ if (isPageHidden() || frozenRef.current) return
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
@@ -252,7 +299,7 @@ export function useUserWs(
}, [])
const connect = useCallback(async () => {
- if (isPageHidden()) {
+ if (isPageHidden() || frozenRef.current) {
publishConnectionPhase("suspended")
return
}
@@ -443,7 +490,7 @@ export function useUserWs(
}
stopHeartbeat()
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
- publishConnectionPhase(isPageHidden() ? "suspended" : "reconnecting")
+ publishConnectionPhase(isPageHidden() || frozenRef.current ? "suspended" : "reconnecting")
scheduleReconnect(generation)
}
}, [clearConnectionValidation, failConnectionValidation, publishConnectionPhase, retireSocket, scheduleReconnect, startHeartbeat, stopHeartbeat])
@@ -452,93 +499,170 @@ export function useUserWs(
connectRef.current = connect
}, [connect])
+ const suspendConnection = useCallback((retireAuthenticatedSocket: boolean) => {
+ connectionValidationNeededRef.current = true
+ suspendedAtRef.current ??= Date.now()
+ clearConnectionValidation()
+ stopHeartbeat()
+ publishConnectionPhase("suspended")
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current)
+ reconnectTimerRef.current = null
+ }
+
+ const generation = connectionGenerationRef.current
+ const authenticated = authenticatedGenerationRef.current === generation
+ if (!retireAuthenticatedSocket && authenticated) return
+
+ connectionGenerationRef.current += 1
+ abortPendingToken()
+ retireSocket(retireAuthenticatedSocket)
+ }, [abortPendingToken, clearConnectionValidation, publishConnectionPhase, retireSocket, stopHeartbeat])
+
+ const trackLifecycleRecovery = useCallback((
+ trigger: CommunityWsLifecycleRecoveryTrigger,
+ strategy: CommunityWsLifecycleRecoveryStrategy,
+ readyState: CommunityWsSocketReadyState,
+ now: number,
+ ) => {
+ if (isPageHidden() || frozenRef.current) return
+ trackCommunityWsLifecycleRecovery({
+ trigger,
+ strategy,
+ socketReadyState: readyState,
+ suspensionDuration: suspensionDurationBucket(suspendedAtRef.current, now),
+ })
+ suspendedAtRef.current = null
+ }, [])
+
+ const requestForegroundRecovery = useCallback((
+ trigger: CommunityWsLifecycleRecoveryTrigger,
+ forceValidation: boolean,
+ ) => {
+ if (isPageHidden()) {
+ suspendConnection(false)
+ return
+ }
+
+ frozenRef.current = false
+ const recoveryNeeded = forceValidation || connectionValidationNeededRef.current
+ if (!recoveryNeeded) return
+
+ reconnectDelay.current = WS_RECONNECT_INIT
+ if (tokenAbortRef.current) return
+
+ const ws = wsRef.current
+ const generation = connectionGenerationRef.current
+ const authenticated = authenticatedGenerationRef.current === generation
+ const awaitingAuthentication = (
+ ws?.readyState === WebSocket.CONNECTING
+ || ws?.readyState === WebSocket.OPEN
+ )
+ && !authenticated
+ && Date.now() - connectStartedAtRef.current <= WS_CONNECTION_VALIDATION_TIMEOUT_MS
+ if (authenticated && ws?.readyState === WebSocket.OPEN) {
+ connectionValidationNeededRef.current = false
+ if (connectionValidationRef.current?.ws === ws) return
+ trackLifecycleRecovery(trigger, "validate", socketReadyState(ws), Date.now())
+ validateCurrentConnection(ws, generation)
+ return
+ }
+ if (awaitingAuthentication) return
+
+ connectionValidationNeededRef.current = false
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current)
+ reconnectTimerRef.current = null
+ }
+ const readyState = socketReadyState(ws)
+ retireSocket()
+ trackLifecycleRecovery(trigger, "replace", readyState, Date.now())
+ void connectRef.current?.()
+ }, [retireSocket, suspendConnection, trackLifecycleRecovery, validateCurrentConnection])
+
useEffect(() => {
+ const mountedAt = Date.now()
+ if (isPageHidden()) suspendedAtRef.current = mountedAt
+ lastSentinelTickAtRef.current = mountedAt
void connect()
- const resumeConnection = () => {
+ const onVisibilityChange = () => {
if (isPageHidden()) {
- connectionValidationNeededRef.current = true
- const generation = connectionGenerationRef.current
- const authenticated = authenticatedGenerationRef.current === generation
- clearConnectionValidation()
- stopHeartbeat()
- publishConnectionPhase("suspended")
- if (reconnectTimerRef.current !== null) {
- clearTimeout(reconnectTimerRef.current)
- reconnectTimerRef.current = null
- }
- if (!authenticated) {
- connectionGenerationRef.current += 1
- tokenAbortRef.current?.abort()
- tokenAbortRef.current = null
- if (tokenTimeoutRef.current !== null) {
- clearTimeout(tokenTimeoutRef.current)
- tokenTimeoutRef.current = null
- }
- retireSocket(false)
- }
+ suspendConnection(false)
return
}
-
- reconnectDelay.current = WS_RECONNECT_INIT
- if (tokenAbortRef.current) return
-
- const ws = wsRef.current
- const generation = connectionGenerationRef.current
- const authenticated = authenticatedGenerationRef.current === generation
- const connecting = ws?.readyState === WebSocket.CONNECTING
- && Date.now() - connectStartedAtRef.current <= WS_CONNECTION_VALIDATION_TIMEOUT_MS
- if (authenticated && ws?.readyState === WebSocket.OPEN) {
- if (!connectionValidationNeededRef.current) return
- connectionValidationNeededRef.current = false
- validateCurrentConnection(ws, generation)
- return
- }
- if (connecting) return
-
- connectionValidationNeededRef.current = false
- connectionGenerationRef.current += 1
- if (reconnectTimerRef.current !== null) {
- clearTimeout(reconnectTimerRef.current)
- reconnectTimerRef.current = null
- }
- retireSocket()
- void connectRef.current?.()
+ requestForegroundRecovery("visibility", false)
+ }
+ const onFreeze = () => {
+ frozenRef.current = true
+ suspendConnection(true)
}
- const onVisibilityChange = () => resumeConnection()
- const onPageShow = () => resumeConnection()
- const onOnline = () => resumeConnection()
+ const onResume = () => requestForegroundRecovery("resume", true)
+ const onPageShow = (event: PageTransitionEvent) => {
+ requestForegroundRecovery("pageshow", event.persisted)
+ }
+ const onWindowFocus = (event: FocusEvent) => {
+ if (event.target !== window) return
+ requestForegroundRecovery("focus", true)
+ }
+ const onOnline = () => requestForegroundRecovery("online", false)
const onOffline = () => { connectionValidationNeededRef.current = true }
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", onVisibilityChange)
+ document.addEventListener("freeze", onFreeze)
+ document.addEventListener("resume", onResume)
}
if (typeof window !== "undefined") {
window.addEventListener("pageshow", onPageShow)
+ window.addEventListener("focus", onWindowFocus)
window.addEventListener("online", onOnline)
window.addEventListener("offline", onOffline)
}
+ sentinelIntervalRef.current = setInterval(() => {
+ const now = Date.now()
+ const elapsedMs = Math.max(0, now - lastSentinelTickAtRef.current)
+ lastSentinelTickAtRef.current = now
+ if (
+ isPageHidden()
+ || elapsedMs < WS_FOREGROUND_SUSPENSION_GAP_MS
+ ) return
+ requestForegroundRecovery("sentinel", true)
+ }, WS_FOREGROUND_SENTINEL_INTERVAL_MS)
return () => {
if (typeof document !== "undefined") {
document.removeEventListener("visibilitychange", onVisibilityChange)
+ document.removeEventListener("freeze", onFreeze)
+ document.removeEventListener("resume", onResume)
}
if (typeof window !== "undefined") {
window.removeEventListener("pageshow", onPageShow)
+ window.removeEventListener("focus", onWindowFocus)
window.removeEventListener("online", onOnline)
window.removeEventListener("offline", onOffline)
}
+ if (sentinelIntervalRef.current !== null) {
+ clearInterval(sentinelIntervalRef.current)
+ sentinelIntervalRef.current = null
+ }
connectionGenerationRef.current += 1
clearConnectionValidation()
- tokenAbortRef.current?.abort()
- tokenAbortRef.current = null
+ abortPendingToken()
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
- if (tokenTimeoutRef.current !== null) { clearTimeout(tokenTimeoutRef.current); tokenTimeoutRef.current = null }
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
stopHeartbeat()
retireSocket(false)
}
- }, [clearConnectionValidation, connect, publishConnectionPhase, retireSocket, stopHeartbeat, validateCurrentConnection])
+ }, [
+ abortPendingToken,
+ clearConnectionValidation,
+ connect,
+ requestForegroundRecovery,
+ retireSocket,
+ stopHeartbeat,
+ suspendConnection,
+ ])
const send = useCallback((msg: object) => {
const ws = wsRef.current
@@ -553,21 +677,16 @@ export function useUserWs(
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
- tokenAbortRef.current?.abort()
- tokenAbortRef.current = null
- if (tokenTimeoutRef.current !== null) {
- clearTimeout(tokenTimeoutRef.current)
- tokenTimeoutRef.current = null
- }
+ abortPendingToken()
reconnectDelay.current = WS_RECONNECT_INIT
retireSocket()
- if (isPageHidden()) {
+ if (isPageHidden() || frozenRef.current) {
connectionGenerationRef.current += 1
publishConnectionPhase("suspended")
return
}
void connectRef.current?.()
- }, [clearConnectionValidation, publishConnectionPhase, retireSocket])
+ }, [abortPendingToken, clearConnectionValidation, publishConnectionPhase, retireSocket])
return { send, reconnectNow }
}
diff --git a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
index af6178504..042b79ba1 100644
--- a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
@@ -3,7 +3,11 @@ import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/
import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
-import { WS_CONNECTION_VALIDATION_TIMEOUT_MS } from "../../lib/use-user-ws"
+import {
+ WS_CONNECTION_VALIDATION_TIMEOUT_MS,
+ WS_FOREGROUND_SENTINEL_INTERVAL_MS,
+ WS_FOREGROUND_SUSPENSION_GAP_MS,
+} from "../../lib/use-user-ws"
test("mobile foreground proof is exact, bounded, and recovers through one current generation", async ({ asUser }, testInfo) => {
test.setTimeout(240_000)
@@ -14,6 +18,30 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
const alice = await asUser("alice")
const bob = await asUser("bob")
+ await alice.page.addInitScript(() => {
+ const nativeSetInterval = window.setInterval.bind(window)
+ const nativeClearInterval = window.clearInterval.bind(window)
+ const intervals = new Map<number, { delay: number; run: () => void }>()
+ window.setInterval = ((handler: TimerHandler, delay?: number, ...args: unknown[]) => {
+ const id = nativeSetInterval(handler, delay, ...args)
+ if (typeof handler === "function") {
+ intervals.set(id, { delay: delay ?? 0, run: () => handler(...args) })
+ }
+ return id
+ }) as typeof window.setInterval
+ window.clearInterval = ((id?: number) => {
+ if (id !== undefined) intervals.delete(id)
+ nativeClearInterval(id)
+ }) as typeof window.clearInterval
+ Object.defineProperty(window, "__alookQaRunIntervals", {
+ configurable: true,
+ value: (delay: number) => {
+ const matching = [...intervals.values()].filter((entry) => entry.delay === delay)
+ for (const entry of matching) entry.run()
+ return matching.length
+ },
+ })
+ })
let dropValidationPong = false
let holdReplacementAuth = false
const proxy = await proxyCommunityWebSockets(alice.context, {
@@ -33,9 +61,16 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
},
})
let tokenRequests = 0
+ let successfulTokenResponses = 0
alice.page.on("request", (request) => {
if (new URL(request.url()).pathname === "/api/ws/token") tokenRequests += 1
})
+ alice.page.on("response", (response) => {
+ if (
+ new URL(response.url()).pathname === "/api/ws/token"
+ && response.ok()
+ ) successfulTokenResponses += 1
+ })
await alice.page.setViewportSize({ width: 390, height: 844 })
await bob.page.setViewportSize({ width: 390, height: 844 })
@@ -52,30 +87,71 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
})
Object.defineProperty(window, "__alookQaSetVisibility", {
configurable: true,
- value: (next: DocumentVisibilityState) => {
+ value: (next: DocumentVisibilityState, dispatch = true) => {
qaVisibility = next
- document.dispatchEvent(new Event("visibilitychange"))
+ if (dispatch) document.dispatchEvent(new Event("visibilitychange"))
+ },
+ })
+ const originalDateNow = Date.now.bind(Date)
+ Object.defineProperty(window, "__alookQaAdvanceWallClock", {
+ configurable: true,
+ value: (offsetMs: number) => {
+ Date.now = () => originalDateNow() + offsetMs
+ },
+ })
+ Object.defineProperty(window, "__alookQaRestoreWallClock", {
+ configurable: true,
+ value: () => {
+ Date.now = originalDateNow
},
})
})
- const setVisibility = async (state: "hidden" | "visible") => {
- await alice.page.evaluate((next) => {
+ const setVisibility = async (state: "hidden" | "visible", dispatch = true) => {
+ await alice.page.evaluate(({ next, shouldDispatch }) => {
const setter = (window as Window & {
- __alookQaSetVisibility?: (value: DocumentVisibilityState) => void
+ __alookQaSetVisibility?: (
+ value: DocumentVisibilityState,
+ dispatch?: boolean,
+ ) => void
}).__alookQaSetVisibility
if (!setter) throw new Error("QA visibility setter missing")
- setter(next)
- }, state)
+ setter(next, shouldDispatch)
+ }, { next: state, shouldDispatch: dispatch })
await expect.poll(() => alice.page.evaluate(() => document.visibilityState)).toBe(state)
}
- const dispatchDuplicateResumeSignals = async () => {
- await alice.page.evaluate(() => {
- window.dispatchEvent(new Event("pageshow"))
+ const dispatchDuplicateResumeSignals = async (persisted = true) => {
+ await alice.page.evaluate((isPersisted) => {
+ document.dispatchEvent(new Event("resume"))
+ document.dispatchEvent(new Event("visibilitychange"))
+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: isPersisted }))
+ window.dispatchEvent(new FocusEvent("focus"))
window.dispatchEvent(new Event("online"))
- })
+ }, persisted)
}
+ const runSentinelIntervals = async () => alice.page.evaluate((delay) => {
+ const run = (window as Window & {
+ __alookQaRunIntervals?: (intervalDelay: number) => number
+ }).__alookQaRunIntervals
+ if (!run) throw new Error("QA interval runner missing")
+ return run(delay)
+ }, WS_FOREGROUND_SENTINEL_INTERVAL_MS)
const wsOverlay = alice.page.getByTestId(tid.wsReconnectOverlay)
+ const initialPageShowFrameCount = proxy.connectionFrames.length
+ const initialPageShowConnectionCount = proxy.connectionCount()
+ const initialPageShowTokenRequests = tokenRequests
+ await composerEditable(alice.page).focus()
+ await alice.page.evaluate(() => {
+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: false }))
+ })
+ await alice.page.waitForTimeout(250)
+ expect(proxy.connectionCount()).toBe(initialPageShowConnectionCount)
+ expect(tokenRequests).toBe(initialPageShowTokenRequests)
+ expect(proxy.connectionFrames.slice(initialPageShowFrameCount).filter((frame) =>
+ frame.direction === "client-to-server"
+ && frame.type === "connection.ping",
+ )).toEqual([])
+
const initialConnectionCount = proxy.connectionCount()
const initialTokenRequests = tokenRequests
const hiddenFrameStart = proxy.connectionFrames.length
@@ -90,7 +166,7 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await expect(wsOverlay).toHaveCount(0)
const healthyStart = proxy.connectionFrames.length
- await setVisibility("visible")
+ await setVisibility("visible", false)
await dispatchDuplicateResumeSignals()
await expect.poll(() => proxy.connectionFrames.slice(healthyStart).filter((frame) =>
frame.direction === "client-to-server" && frame.type === "connection.ping",
@@ -110,12 +186,45 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await expect(composerEditable(alice.page)).toBeVisible()
await setVisibility("hidden")
+ const freezeFrameStart = proxy.connectionFrames.length
+ const freezeConnectionBaseline = proxy.connectionCount()
+ const freezeTokenBaseline = tokenRequests
+ await alice.page.evaluate(() => document.dispatchEvent(new Event("freeze")))
+ await alice.page.waitForTimeout(WS_FOREGROUND_SENTINEL_INTERVAL_MS + 500)
+ await alice.page.evaluate(() => document.dispatchEvent(new Event("resume")))
+ await alice.page.waitForTimeout(250)
+ expect(proxy.connectionCount()).toBe(freezeConnectionBaseline)
+ expect(tokenRequests).toBe(freezeTokenBaseline)
+ expect(proxy.connectionFrames.slice(freezeFrameStart).filter((frame) =>
+ frame.direction === "client-to-server"
+ && (
+ frame.type === "raw.ping"
+ || frame.type === "connection.ping"
+ || frame.type === "auth"
+ ),
+ )).toEqual([])
+
+ await setVisibility("visible", false)
+ await dispatchDuplicateResumeSignals()
+ await expect.poll(() => proxy.connectionCount()).toBe(freezeConnectionBaseline + 1)
+ await expect.poll(() => tokenRequests).toBe(freezeTokenBaseline + 1)
+ await expect.poll(() => proxy.connectionFrames.filter((frame) =>
+ frame.direction === "server-to-client"
+ && frame.type === "auth.ok"
+ && frame.connectionId === freezeConnectionBaseline + 1,
+ ).length).toBe(1)
+ expect(proxy.connectionFrames.slice(freezeFrameStart).filter((frame) =>
+ frame.direction === "client-to-server"
+ && frame.type === "connection.ping",
+ )).toEqual([])
+ await expect(wsOverlay).toHaveCount(0, { timeout: 10_000 })
+
dropValidationPong = true
holdReplacementAuth = true
const failedStart = proxy.connectionFrames.length
const failedConnectionBaseline = proxy.connectionCount()
const failedTokenBaseline = tokenRequests
- await setVisibility("visible")
+ await alice.page.evaluate(() => window.dispatchEvent(new FocusEvent("focus")))
await dispatchDuplicateResumeSignals()
await expect.poll(() => proxy.connectionFrames.slice(failedStart).filter((frame) =>
frame.direction === "client-to-server" && frame.type === "connection.ping",
@@ -132,6 +241,11 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await expect.poll(() => proxy.connectionCount()).toBe(failedConnectionBaseline + 1)
await expect.poll(() => tokenRequests).toBe(failedTokenBaseline + 1)
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
+ await dispatchDuplicateResumeSignals()
+ await alice.page.waitForTimeout(250)
+ expect(proxy.connectionCount()).toBe(failedConnectionBaseline + 1)
+ expect(tokenRequests).toBe(failedTokenBaseline + 1)
+ expect(proxy.heldConnectionCount()).toBe(1)
expect(proxy.connectionFrames.filter((frame) =>
frame.direction === "client-to-server"
&& frame.type === "auth"
@@ -146,6 +260,66 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await expect(wsOverlay).toHaveCount(0, { timeout: 10_000 })
await expect(composerEditable(alice.page)).toBeVisible()
+ await alice.page.bringToFront()
+ await alice.page.waitForTimeout(500)
+ const sentinelOrdinaryStart = proxy.connectionFrames.length
+ const sentinelConnectionBaseline = proxy.connectionCount()
+ const sentinelTokenBaseline = tokenRequests
+ expect(await runSentinelIntervals()).toBeGreaterThanOrEqual(1)
+ await alice.page.waitForTimeout(250)
+ expect(proxy.connectionCount()).toBe(sentinelConnectionBaseline)
+ expect(tokenRequests).toBe(sentinelTokenBaseline)
+ expect(proxy.connectionFrames.slice(sentinelOrdinaryStart).filter((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ )).toEqual([])
+
+ dropValidationPong = true
+ holdReplacementAuth = true
+ const sentinelRecoveryStart = proxy.connectionFrames.length
+ const observedClockShift = await alice.page.evaluate((offsetMs) => {
+ const before = Date.now()
+ const advance = (window as Window & {
+ __alookQaAdvanceWallClock?: (offset: number) => void
+ }).__alookQaAdvanceWallClock
+ if (!advance) throw new Error("QA wall-clock advancer missing")
+ advance(offsetMs)
+ return Date.now() - before
+ }, WS_FOREGROUND_SUSPENSION_GAP_MS + 5_000)
+ expect(observedClockShift).toBeGreaterThanOrEqual(WS_FOREGROUND_SUSPENSION_GAP_MS)
+ expect(await runSentinelIntervals()).toBeGreaterThanOrEqual(1)
+ await expect.poll(() => proxy.connectionFrames.slice(sentinelRecoveryStart).filter((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ ).length).toBe(1)
+ await alice.page.evaluate(() => {
+ const restore = (window as Window & {
+ __alookQaRestoreWallClock?: () => void
+ }).__alookQaRestoreWallClock
+ if (!restore) throw new Error("QA wall-clock restorer missing")
+ restore()
+ })
+ await dispatchDuplicateResumeSignals()
+ proxy.sendConnectionFrame({ type: "connection.pong", nonce: "sentinel_stale_nonce" })
+
+ await expect(wsOverlay).toHaveAttribute(
+ "data-ws-status",
+ "reconnecting",
+ { timeout: WS_CONNECTION_VALIDATION_TIMEOUT_MS + 5_000 },
+ )
+ await expect.poll(() => proxy.connectionCount()).toBe(sentinelConnectionBaseline + 1)
+ await expect.poll(() => tokenRequests).toBe(sentinelTokenBaseline + 1)
+ await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
+ expect(proxy.connectionFrames.slice(sentinelRecoveryStart).filter((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ )).toHaveLength(1)
+
+ dropValidationPong = false
+ holdReplacementAuth = false
+ expect(proxy.releaseHeldConnections((frame) =>
+ frame.type === "auth.ok" && frame.connectionId === sentinelConnectionBaseline + 1,
+ )).toBe(1)
+ await expect(wsOverlay).toHaveCount(0, { timeout: 10_000 })
+ await expect(composerEditable(alice.page)).toBeVisible()
+
try {
await alice.context.setOffline(true)
await proxy.disconnect()
@@ -165,6 +339,28 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await alice.page.getByTestId(tid.wsRetry).click()
await expect(wsOverlay).toHaveCount(0, { timeout: 20_000 })
+
+ const reloadFrameStart = proxy.connectionFrames.length
+ const reloadConnectionBaseline = proxy.connectionCount()
+ const reloadSuccessfulTokenBaseline = successfulTokenResponses
+ await alice.page.reload({ waitUntil: "commit" })
+ await expect(composerEditable(alice.page)).toBeVisible({ timeout: 20_000 })
+ await expect.poll(() => proxy.connectionCount()).toBe(reloadConnectionBaseline + 1)
+ await expect.poll(() => successfulTokenResponses).toBe(reloadSuccessfulTokenBaseline + 1)
+ await expect.poll(() => proxy.connectionFrames.slice(reloadFrameStart).filter((frame) =>
+ frame.direction === "server-to-client"
+ && frame.type === "auth.ok"
+ && frame.connectionId === reloadConnectionBaseline + 1,
+ ).length).toBe(1)
+ await alice.page.waitForTimeout(500)
+ expect(proxy.connectionCount()).toBe(reloadConnectionBaseline + 1)
+ expect(successfulTokenResponses).toBe(reloadSuccessfulTokenBaseline + 1)
+ expect(proxy.connectionFrames.slice(reloadFrameStart).filter((frame) =>
+ frame.direction === "client-to-server"
+ && frame.connectionId === reloadConnectionBaseline + 1
+ && frame.type === "connection.ping",
+ )).toEqual([])
+
const body = `foreground recovery ${stamp}`
await sendMessage(bob.page, body)
await expect(alice.page.getByText(body, { exact: true })).toBeVisible({ timeout: 20_000 })
@@ -173,8 +369,22 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await testInfo.attach("foreground-validation-frames.json", {
body: Buffer.from(JSON.stringify({
tokenRequests,
+ successfulTokenResponses,
connectionCount: proxy.connectionCount(),
frames: proxy.connectionFrames,
+ simulatedLifecycleCoverage: [
+ "initial-pageshow",
+ "element-focus",
+ "hidden-network-silence",
+ "healthy-retained-validation",
+ "freeze-resume",
+ "focus-only-zombie-open",
+ "foreground-event-storm",
+ "wall-clock-sentinel",
+ "offline-online",
+ "discarded-document-reload",
+ "post-recovery-delivery",
+ ],
physicalDeviceCoverage: "not run; approved residual risk",
stagingCoverage: "not run; approved residual risk",
}, null, 2)),
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
index 3e89a2e48..c121b92a0 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
@@ -120,7 +120,7 @@ export async function proxyCommunityWebSockets(
let activeClient: WebSocketRoute | undefined
let activeConnectionId: number | undefined
let connectionCount = 0
- await context.routeWebSocket(/.*/, (client: WebSocketRoute) => {
+ await context.routeWebSocket(/\/api\/ws\/user(?:\?|$)/, (client: WebSocketRoute) => {
connectionCount += 1
const connectionId = connectionCount
activeClient = client