Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): validate resumed WebSocket connections (#565)

Gener594cd26e90ef
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 79e510657..8951eeac5 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -40,6 +40,7 @@ export const SPEC_SECONDS = {
"29-multi-device-read-state.spec.ts": 45,
"30-bot-profile-audit-preview.spec.ts": 35,
"31-mention-candidate-pagination.spec.ts": 10,
+ "32-mobile-ws-foreground-validation.spec.ts": 80,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 8ce624d6f..dc5d3c816 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([220, 220, 220, 224, 224])
+ expect(totals.sort((left, right) => left - right)).toEqual([234, 238, 238, 239, 239])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 44cbb45a6..43df445bb 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -71,6 +71,13 @@ export type {
// daemon, and the D1 query layer).
export * from "./diagnostics-contract";
export { compareAsciiSqliteBinary } from "./lib/sqlite-binary";
+export {
+ isUserWsConnectionPing,
+ isUserWsConnectionPong,
+ USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH,
+ type UserWsConnectionPing,
+ type UserWsConnectionPong,
+} from "./user-ws-validation";
// Constants
export {
diff --git a/src/shared/src/user-ws-validation.test.ts b/src/shared/src/user-ws-validation.test.ts
new file mode 100644
index 000000000..2cc88f239
--- /dev/null
+++ b/src/shared/src/user-ws-validation.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import {
+ isUserWsConnectionPing,
+ isUserWsConnectionPong,
+ USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH,
+} from "./user-ws-validation";
+
+describe("user WebSocket connection validation", () => {
+ it("accepts exact bounded ping and pong frames", () => {
+ const nonce = `resume_${"a".repeat(USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH - 7)}`;
+
+ expect(isUserWsConnectionPing({ type: "connection.ping", nonce })).toBe(true);
+ expect(isUserWsConnectionPong({ type: "connection.pong", nonce })).toBe(true);
+ });
+
+ it.each([
+ null,
+ [],
+ { type: "connection.ping" },
+ { type: "connection.ping", nonce: "" },
+ { type: "connection.ping", nonce: "contains spaces" },
+ { type: "connection.ping", nonce: "a".repeat(USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH + 1) },
+ { type: "connection.ping", nonce: "valid", extra: true },
+ { type: "connection.pong", nonce: 42 },
+ ])("rejects malformed or non-exact frames %#", (frame) => {
+ expect(isUserWsConnectionPing(frame)).toBe(false);
+ expect(isUserWsConnectionPong(frame)).toBe(false);
+ });
+});
diff --git a/src/shared/src/user-ws-validation.ts b/src/shared/src/user-ws-validation.ts
new file mode 100644
index 000000000..1d3dc6671
--- /dev/null
+++ b/src/shared/src/user-ws-validation.ts
@@ -0,0 +1,33 @@
+export const USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH = 64;
+
+export type UserWsConnectionPing = {
+ type: "connection.ping";
+ nonce: string;
+};
+
+export type UserWsConnectionPong = {
+ type: "connection.pong";
+ nonce: string;
+};
+
+function isConnectionValidationFrame(
+ value: unknown,
+ type: UserWsConnectionPing["type"] | UserWsConnectionPong["type"],
+): value is UserWsConnectionPing | UserWsConnectionPong {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
+ const frame = value as Record<string, unknown>;
+ return Object.keys(frame).length === 2
+ && frame.type === type
+ && typeof frame.nonce === "string"
+ && frame.nonce.length > 0
+ && frame.nonce.length <= USER_WS_CONNECTION_VALIDATION_NONCE_MAX_LENGTH
+ && /^[A-Za-z0-9_-]+$/.test(frame.nonce);
+}
+
+export function isUserWsConnectionPing(value: unknown): value is UserWsConnectionPing {
+ return isConnectionValidationFrame(value, "connection.ping");
+}
+
+export function isUserWsConnectionPong(value: unknown): value is UserWsConnectionPong {
+ return isConnectionValidationFrame(value, "connection.pong");
+}
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.test.ts b/src/web/src/components/community/messages/composer-accessory-rail.test.ts
index 46dc9d24e..1f76e382b 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.test.ts
+++ b/src/web/src/components/community/messages/composer-accessory-rail.test.ts
@@ -236,6 +236,32 @@ describe("ComposerAccessoryRail", () => {
expect(reconnectNow).toHaveBeenCalledOnce()
})
+ it("stays absent during validation, then replaces outage controls and removes them on recovery", () => {
+ const renderer = render({ scrollCount: 0, typingNames: [] })
+ expect(renderer.root.findAllByProps({ "data-testid": tid.composerAccessoryRail })).toHaveLength(0)
+
+ act(() => useCommunityWsStore.getState().setConnectionStatus("reconnecting"))
+ const status = renderer.root.findByProps({ "data-testid": tid.wsStatus })
+ expect(status.props).toMatchObject({
+ "data-ws-status": "reconnecting",
+ "aria-label": "WebSocket reconnecting",
+ })
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsRetry })).toHaveLength(0)
+
+ act(() => useCommunityWsStore.getState().setConnectionStatus("failed"))
+ const retry = renderer.root.findByProps({ "data-testid": tid.wsRetry })
+ expect(retry.props).toMatchObject({
+ "data-ws-status": "failed",
+ "aria-label": "WebSocket connection failed. Retry now",
+ })
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsStatus })).toHaveLength(0)
+
+ act(() => useCommunityWsStore.getState().setConnectionStatus("connected"))
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsStatus })).toHaveLength(0)
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsRetry })).toHaveLength(0)
+ expect(renderer.root.findAllByProps({ "data-testid": tid.composerAccessoryRail })).toHaveLength(0)
+ })
+
it("replaces scroll with selection controls and preserves desktop typing", () => {
const renderer = render({ selectMode: true, selectedCount: 3 })
const rail = renderer.root.findByProps({ "data-testid": tid.composerAccessoryRail })
diff --git a/src/web/src/hooks/community/community-ws/connection-status.test.ts b/src/web/src/hooks/community/community-ws/connection-status.test.ts
index cc967dbe4..df2f60e24 100644
--- a/src/web/src/hooks/community/community-ws/connection-status.test.ts
+++ b/src/web/src/hooks/community/community-ws/connection-status.test.ts
@@ -59,6 +59,32 @@ describe("community websocket connection status", () => {
expect(publish).toHaveBeenLastCalledWith("failed")
})
+ it("keeps hidden validation quiet and starts the outage clock only on failure", () => {
+ const { controller, publish } = setup()
+ controller.handlePhase("reconnecting")
+ controller.handlePhase("authenticated")
+ controller.handlePhase("suspended")
+ publish.mockClear()
+
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS + 1)
+ expect(publish).not.toHaveBeenCalled()
+
+ controller.handlePhase("authenticated")
+ expect(publish).toHaveBeenLastCalledWith("connected")
+ publish.mockClear()
+
+ controller.handlePhase("reconnecting")
+ expect(publish).toHaveBeenCalledOnce()
+ expect(publish).toHaveBeenLastCalledWith("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - 1)
+ expect(publish).not.toHaveBeenCalledWith("failed")
+ vi.advanceTimersByTime(1)
+ expect(publish).toHaveBeenLastCalledWith("failed")
+
+ controller.handlePhase("authenticated")
+ expect(publish).toHaveBeenLastCalledWith("connected")
+ })
+
it("suspends hidden outages and starts fresh thresholds when visible again", () => {
const { controller, publish } = setup()
controller.handlePhase("reconnecting")
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 27edfc2ec..0a379cd62 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -125,6 +125,32 @@ describe("useCommunityWs — connection status publication", () => {
vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
})
+
+ it("keeps resume validation quiet until transport failure and clears recovery once", async () => {
+ vi.useFakeTimers()
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ await mountHook()
+ flushEffects()
+
+ capturedConnectionStateChange!("reconnecting")
+ capturedConnectionStateChange!("authenticated")
+ capturedConnectionStateChange!("suspended")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS + 1)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+
+ capturedConnectionStateChange!("authenticated")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+
+ capturedConnectionStateChange!("reconnecting")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("failed")
+
+ capturedConnectionStateChange!("authenticated")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+ })
})
describe("useCommunityWs — double-mount detection", () => {
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 166c65680..93ba1d2fa 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -32,6 +32,7 @@ class MockWebSocket {
simulateOpen() { this.readyState = MockWebSocket.OPEN; this.onopen?.() }
simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }
simulateRawMessage(data: string) { this.onmessage?.({ data }) }
+ simulateError() { this.onerror?.() }
simulateClose() { this.readyState = MockWebSocket.CLOSED; this.onclose?.() }
}
@@ -146,6 +147,26 @@ function setupTokenFetch() {
})
}
+function connectionPings(ws: MockWebSocket): Array<{ type: "connection.ping"; nonce: string }> {
+ return ws.sent.flatMap((value) => {
+ try {
+ const parsed = JSON.parse(value) as { type?: string; nonce?: string }
+ return parsed.type === "connection.ping" && typeof parsed.nonce === "string"
+ ? [{ type: "connection.ping" as const, nonce: parsed.nonce }]
+ : []
+ } catch {
+ return []
+ }
+ })
+}
+
+function dispatchHiddenToVisible() {
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+}
+
function resetMockState() {
MockWebSocket.instances = []
mockFetch.mockReset()
@@ -266,12 +287,16 @@ describe("useUserWs", () => {
it("opens the access gate only after auth.ok", async () => {
setupTokenFetch()
+ const onMessage = vi.fn()
const onAuthenticated = vi.fn()
- await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ await mountHook(onMessage, { onAuthenticated, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
+ ws.simulateMessage({ type: "connection.pong", nonce: "preauth_nonce" })
+ ws.simulateMessage({ type: "task.updated", taskId: "preauth" })
expect(onAuthenticated).not.toHaveBeenCalled()
+ expect(onMessage).not.toHaveBeenCalled()
ws.simulateMessage({ type: "auth.ok" })
expect(onAuthenticated).toHaveBeenCalledTimes(1)
@@ -577,14 +602,107 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(2)
})
- it("keeps a fresh authenticated socket across pageshow and online", async () => {
+ it("parks an authenticated hidden socket without heartbeat or reconnect work", async () => {
setupTokenFetch()
- await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ await vi.advanceTimersByTimeAsync(25_000)
+ expect(ws.sent.filter(frame => frame === "ping")).toHaveLength(1)
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ const hiddenFrameCount = ws.sent.length
+ const hiddenFetchCount = mockFetch.mock.calls.length
+ await vi.advanceTimersByTimeAsync(120_000)
+
+ expect(ws.sent).toHaveLength(hiddenFrameCount)
+ expect(mockFetch).toHaveBeenCalledTimes(hiddenFetchCount)
+ expect(MockWebSocket.instances).toEqual([ws])
+ expect(ws.closed).toBe(false)
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ mockWindow.dispatch("pageshow")
+ mockWindow.dispatch("online")
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(onConnectionStateChange).not.toHaveBeenLastCalledWith("reconnecting")
+ })
+
+ it("retires a CONNECTING socket hidden transition and ignores its late open", async () => {
+ setupTokenFetch()
+ const onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ expect(first.closed).toBe(true)
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+
+ first.simulateOpen()
+ expect(first.sent).toEqual([])
+
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ mockWindow.dispatch("pageshow")
+ mockWindow.dispatch("online")
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("retires an OPEN pre-auth socket hidden transition and ignores late auth.ok", async () => {
+ setupTokenFetch()
+ const onAuthenticated = vi.fn()
+ await mountHook(vi.fn(), {
+ onAuthenticated,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123" }))
+
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ expect(first.closed).toBe(true)
+
+ first.simulateMessage({ type: "auth.ok" })
+ expect(onAuthenticated).not.toHaveBeenCalled()
+
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ mockWindow.dispatch("pageshow")
+ await flushPromises()
+
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("coalesces foreground signals into one exact-nonce validation on the retained socket", async () => {
+ setupTokenFetch()
+ const onConnectionStateChange = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok" })
const fetchCount = mockFetch.mock.calls.length
+ onConnectionStateChange.mockClear()
+ dispatchHiddenToVisible()
mockWindow.dispatch("pageshow")
mockWindow.dispatch("online")
await flushPromises()
@@ -592,23 +710,185 @@ describe("useUserWs", () => {
expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
expect(MockWebSocket.instances).toEqual([ws])
expect(ws.closed).toBe(false)
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(onConnectionStateChange).not.toHaveBeenCalledWith("reconnecting")
+
+ const [{ nonce }] = connectionPings(ws)
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("authenticated")
+
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS + 1)
+ expect(MockWebSocket.instances).toEqual([ws])
+ expect(ws.closed).toBe(false)
+ })
+
+ it("coalesces an offline-online signal pair while foreground validation is pending", async () => {
+ setupTokenFetch()
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ dispatchHiddenToVisible()
+ expect(connectionPings(ws)).toHaveLength(1)
+
+ mockWindow.dispatch("offline")
+ mockWindow.dispatch("online")
+
+ expect(connectionPings(ws)).toHaveLength(1)
+ })
+
+ it("keeps a cleared foreground validation timer inert", async () => {
+ setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ const timerSpy = vi.spyOn(globalThis, "setTimeout")
+
+ dispatchHiddenToVisible()
+ const [{ nonce }] = connectionPings(ws)
+ const timeout = timerSpy.mock.calls.find(([, delay]) =>
+ delay === mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)?.[0]
+ expect(timeout).toBeTypeOf("function")
+
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ ;(timeout as () => void)()
+
+ expect(ws.closed).toBe(false)
+ expect(MockWebSocket.instances).toEqual([ws])
+ timerSpy.mockRestore()
+ })
+
+ it("does not restart an old heartbeat after a reentrant validation lifecycle reconnect", async () => {
+ setupTokenFetch()
+ let reconnectOnValidation = false
+ const onConnectionStateChange = vi.fn((phase: string) => {
+ if (reconnectOnValidation && phase === "authenticated") {
+ latestHookResult?.reconnectNow()
+ }
+ })
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ dispatchHiddenToVisible()
+ const [{ nonce }] = connectionPings(ws)
+ reconnectOnValidation = true
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ await flushPromises()
+
+ expect(ws.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ await vi.advanceTimersByTimeAsync(25_000)
+ expect(ws.sent).not.toContain("ping")
})
- it("keeps cached UI ownership but replaces a stale authenticated socket on foreground", async () => {
+ it("fails foreground validation once when its control-frame send throws", async () => {
setupTokenFetch()
const onDisconnect = vi.fn()
- await mountHook(vi.fn(), { onDisconnect, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), {
+ onDisconnect,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ const send = ws.send.bind(ws)
+ ws.send = vi.fn((data: string) => {
+ if (data.includes('"type":"connection.ping"')) throw new Error("socket send failed")
+ send(data)
+ })
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ dispatchHiddenToVisible()
+ await flushPromises()
+
+ expect(onDisconnect).toHaveBeenCalledOnce()
+ expect(ws.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("does not accept raw, mismatched, or queued previous validation pong as foreground proof", async () => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn()
+ const onConnectionStateChange = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ onDisconnect,
+ requestDaemonStatusOnAuth: false,
+ })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
first.simulateMessage({ type: "auth.ok" })
+ onConnectionStateChange.mockClear()
- vi.setSystemTime(Date.now() + 31_000)
+ dispatchHiddenToVisible()
+ const [{ nonce }] = connectionPings(first)
+ first.simulateRawMessage("pong")
+ first.simulateMessage({ type: "connection.pong", nonce: "previous_nonce" })
+ first.simulateMessage({ type: "connection.pong", nonce: `${nonce}_wrong` })
+
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS - 1)
+ expect(onDisconnect).not.toHaveBeenCalled()
+ expect(onConnectionStateChange).not.toHaveBeenCalledWith("reconnecting")
+ expect(first.closed).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(1)
mockWindow.dispatch("pageshow")
await flushPromises()
expect(onDisconnect).toHaveBeenCalledTimes(1)
expect(first.closed).toBe(true)
expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(onConnectionStateChange).toHaveBeenCalledWith("reconnecting")
+ expect(onConnectionStateChange.mock.calls.filter(([phase]) => phase === "reconnecting"))
+ .toHaveLength(1)
+
+ first.simulateMessage({ type: "connection.pong", nonce })
+ first.simulateMessage({ type: "auth.ok" })
+ expect(onDisconnect).toHaveBeenCalledTimes(1)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("requires a new nonce after hidden and ignores the queued pre-hide response", async () => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onDisconnect,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ dispatchHiddenToVisible()
+ const firstNonce = connectionPings(ws).at(-1)!.nonce
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ mockWindow.dispatch("pageshow")
+ mockWindow.dispatch("online")
+ const pings = connectionPings(ws)
+ expect(pings).toHaveLength(2)
+ const secondNonce = pings.at(-1)!.nonce
+ expect(secondNonce).not.toBe(firstNonce)
+
+ ws.simulateMessage({ type: "connection.pong", nonce: firstNonce })
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS - 1)
+ expect(onDisconnect).not.toHaveBeenCalled()
+
+ ws.simulateMessage({ type: "connection.pong", nonce: secondNonce })
+ await vi.advanceTimersByTimeAsync(2)
+ expect(onDisconnect).not.toHaveBeenCalled()
+ expect(ws.closed).toBe(false)
+ expect(MockWebSocket.instances).toEqual([ws])
})
it("coalesces visible, pageshow, and online while one replacement token request is pending", async () => {
@@ -638,6 +918,85 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(2)
})
+ it("lets an exact response queued first at the deadline win without a reconnect", async () => {
+ setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ dispatchHiddenToVisible()
+ const [{ nonce }] = connectionPings(ws)
+
+ vi.setSystemTime(Date.now() + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ await vi.runOnlyPendingTimersAsync()
+
+ expect(ws.closed).toBe(false)
+ expect(MockWebSocket.instances).toEqual([ws])
+ expect(mockFetch).toHaveBeenCalledOnce()
+ })
+
+ it("lets the deadline queued first retire once and makes the exact late response inert", async () => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn()
+ const mod = await mountHook(vi.fn(), {
+ onDisconnect,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ dispatchHiddenToVisible()
+ const [{ nonce }] = connectionPings(ws)
+
+ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ await flushPromises()
+ expect(ws.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ ws.simulateClose()
+ ws.simulateError()
+ await vi.advanceTimersByTimeAsync(5_000)
+
+ expect(onDisconnect).toHaveBeenCalledOnce()
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("treats error as non-authoritative and lets current close start one validation failure chain", async () => {
+ setupTokenFetch()
+ const onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ onConnectionStateChange.mockClear()
+ dispatchHiddenToVisible()
+
+ ws.simulateError()
+ ws.simulateError()
+ expect(MockWebSocket.instances).toEqual([ws])
+ expect(onConnectionStateChange).not.toHaveBeenCalledWith("reconnecting")
+
+ ws.simulateClose()
+ await flushPromises()
+ expect(ws.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ expect(onConnectionStateChange.mock.calls.filter(([phase]) => phase === "reconnecting"))
+ .toHaveLength(1)
+
+ ws.simulateClose()
+ ws.simulateError()
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
it("failed connect (fetch rejects) retries with backoff and cleanup prevents further reconnects", async () => {
// All connects will fail
mockFetch.mockRejectedValue(new Error("network error"))
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index e9dc5f8b9..8abafca9c 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -6,6 +6,7 @@ import {
isCommunityBrowserEventBatchCandidate,
isCommunityEventCandidate,
isCommunityEventType,
+ isUserWsConnectionPong,
type WsMessage,
} from "@alook/shared"
import {
@@ -19,8 +20,14 @@ const isLocal = isLocalMode()
const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
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
-const WS_CONNECT_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_CONNECT_TIMEOUT_MS) || 10_000
-const WS_STALE_AFTER_MS = 30_000
+export const WS_CONNECTION_VALIDATION_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_CONNECT_TIMEOUT_MS) || 10_000
+
+type PendingConnectionValidation = {
+ ws: WebSocket
+ generation: number
+ nonce: string
+ timeout: ReturnType<typeof setTimeout>
+}
function isPageHidden(): boolean {
return typeof document !== "undefined" && document.visibilityState === "hidden"
@@ -91,6 +98,7 @@ export function useUserWs(
const onDisconnectRef = useRef(options?.onDisconnect)
const onAuthenticatedRef = useRef(options?.onAuthenticated)
const onConnectionStateChangeRef = useRef(options?.onConnectionStateChange)
+ const lastConnectionPhaseRef = useRef<UserWsConnectionPhase | null>(null)
const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const tokenAbortRef = useRef<AbortController | null>(null)
@@ -104,6 +112,8 @@ export function useUserWs(
const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const livenessIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const connectionGenerationRef = useRef(0)
+ const connectionValidationRef = useRef<PendingConnectionValidation | null>(null)
+ const connectionValidationNeededRef = useRef(isPageHidden())
useEffect(() => {
onMessageRef.current = onMessage
@@ -129,19 +139,102 @@ export function useUserWs(
const connectRef = useRef<(() => Promise<void>) | null>(null)
+ const publishConnectionPhase = useCallback((phase: UserWsConnectionPhase) => {
+ if (lastConnectionPhaseRef.current === phase) return
+ lastConnectionPhaseRef.current = phase
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.(phase))
+ }, [])
+
+ const clearConnectionValidation = useCallback(() => {
+ const pending = connectionValidationRef.current
+ connectionValidationRef.current = null
+ if (pending) clearTimeout(pending.timeout)
+ }, [])
+
+ const stopHeartbeat = useCallback(() => {
+ if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
+ if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
+ }, [])
+
+ const startHeartbeat = useCallback((ws: WebSocket, generation: number) => {
+ stopHeartbeat()
+ if (
+ isPageHidden()
+ || ws !== wsRef.current
+ || generation !== connectionGenerationRef.current
+ || authenticatedGenerationRef.current !== generation
+ || ws.readyState !== WebSocket.OPEN
+ ) return
+ lastMessageAtRef.current = Date.now()
+ pingIntervalRef.current = setInterval(() => {
+ if (ws.readyState === WebSocket.OPEN) ws.send("ping")
+ }, 25_000)
+ livenessIntervalRef.current = setInterval(() => {
+ if (Date.now() - lastMessageAtRef.current > 30_000) ws.close()
+ }, 5_000)
+ }, [stopHeartbeat])
+
const retireSocket = useCallback((reportDisconnect = true) => {
const ws = wsRef.current
wsRef.current = null
+ clearConnectionValidation()
if (reportDisconnect && authenticatedGenerationRef.current !== null) {
authenticatedGenerationRef.current = null
disconnectedAtRef.current ??= Date.now()
runLifecycleCallback("disconnect", onDisconnectRef.current)
}
- if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
- if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
+ stopHeartbeat()
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
ws?.close()
- }, [])
+ }, [clearConnectionValidation, stopHeartbeat])
+
+ const failConnectionValidation = useCallback((
+ ws: WebSocket,
+ generation: number,
+ nonce: string,
+ ) => {
+ const pending = connectionValidationRef.current
+ if (
+ !pending
+ || pending.ws !== ws
+ || pending.generation !== generation
+ || pending.nonce !== nonce
+ || ws !== wsRef.current
+ || generation !== connectionGenerationRef.current
+ ) return
+ clearConnectionValidation()
+ retireSocket()
+ publishConnectionPhase(isPageHidden() ? "suspended" : "reconnecting")
+ if (!isPageHidden()) void connectRef.current?.()
+ }, [clearConnectionValidation, publishConnectionPhase, retireSocket])
+
+ const validateCurrentConnection = useCallback((ws: WebSocket, generation: number) => {
+ const current = connectionValidationRef.current
+ if (
+ current?.ws === ws
+ && current.generation === generation
+ && ws === wsRef.current
+ && generation === connectionGenerationRef.current
+ ) return
+ clearConnectionValidation()
+ stopHeartbeat()
+ const nonce = crypto.randomUUID()
+ const pending: PendingConnectionValidation = {
+ ws,
+ generation,
+ nonce,
+ timeout: setTimeout(() => {
+ failConnectionValidation(ws, generation, nonce)
+ }, WS_CONNECTION_VALIDATION_TIMEOUT_MS),
+ }
+ connectionValidationRef.current = pending
+ try {
+ ws.send(JSON.stringify({ type: "connection.ping", nonce }))
+ } catch {
+ failConnectionValidation(ws, generation, nonce)
+ }
+ }, [clearConnectionValidation, failConnectionValidation, stopHeartbeat])
const scheduleReconnect = useCallback((generation: number) => {
if (generation !== connectionGenerationRef.current) return
@@ -160,12 +253,10 @@ export function useUserWs(
const connect = useCallback(async () => {
if (isPageHidden()) {
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.("suspended"))
+ publishConnectionPhase("suspended")
return
}
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.("reconnecting"))
+ publishConnectionPhase("reconnecting")
const generation = connectionGenerationRef.current + 1
connectionGenerationRef.current = generation
if (reconnectTimerRef.current !== null) {
@@ -233,24 +324,12 @@ export function useUserWs(
connectTimeoutRef.current = setTimeout(() => {
if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return
ws.close()
- }, WS_CONNECT_TIMEOUT_MS)
+ }, WS_CONNECTION_VALIDATION_TIMEOUT_MS)
ws.onopen = () => {
if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return
reconnectDelay.current = WS_RECONNECT_INIT
ws.send(JSON.stringify({ type: "auth", token: authToken }))
-
- lastMessageAtRef.current = Date.now()
- pingIntervalRef.current = setInterval(() => {
- if (ws.readyState === WebSocket.OPEN) {
- ws.send("ping")
- }
- }, 25_000)
- livenessIntervalRef.current = setInterval(() => {
- if (Date.now() - lastMessageAtRef.current > 30_000) {
- ws.close()
- }
- }, 5_000)
}
ws.onmessage = (e) => {
@@ -277,6 +356,21 @@ export function useUserWs(
reportDroppedFrame("missing-type", msg)
return
}
+ if (msg.type === "connection.pong") {
+ const pending = connectionValidationRef.current
+ if (
+ isUserWsConnectionPong(msg)
+ && pending?.ws === ws
+ && pending.generation === generation
+ && pending.nonce === msg.nonce
+ && authenticatedGenerationRef.current === generation
+ ) {
+ clearConnectionValidation()
+ publishConnectionPhase("authenticated")
+ startHeartbeat(ws, generation)
+ }
+ return
+ }
if (msg.type === "auth.ok") {
if (authenticatedGenerationRef.current === generation) {
reportDroppedFrame("duplicate-auth-ok", msg)
@@ -293,8 +387,7 @@ export function useUserWs(
? 0
: Math.max(0, Date.now() - disconnectedAtRef.current)
disconnectedAtRef.current = null
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.("authenticated"))
+ publishConnectionPhase("authenticated")
runLifecycleCallback("authenticated", onAuthenticatedRef.current)
if (isReconnect) {
runLifecycleCallback("reconnect", () =>
@@ -303,6 +396,7 @@ export function useUserWs(
if (requestDaemonStatusOnAuthRef.current) {
ws.send(JSON.stringify({ type: "check_daemon_status" }))
}
+ startHeartbeat(ws, generation)
return
}
if (authenticatedGenerationRef.current !== generation) {
@@ -333,20 +427,26 @@ export function useUserWs(
ws.onclose = () => {
if (ws !== wsRef.current) return
+ const validation = connectionValidationRef.current
+ if (
+ validation?.ws === ws
+ && validation.generation === generation
+ ) {
+ failConnectionValidation(ws, generation, validation.nonce)
+ return
+ }
const wasAuthenticated = authenticatedGenerationRef.current === generation
if (wasAuthenticated) {
authenticatedGenerationRef.current = null
disconnectedAtRef.current ??= Date.now()
runLifecycleCallback("disconnect", onDisconnectRef.current)
}
- if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
- if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
+ stopHeartbeat()
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.(isPageHidden() ? "suspended" : "reconnecting"))
+ publishConnectionPhase(isPageHidden() ? "suspended" : "reconnecting")
scheduleReconnect(generation)
}
- }, [retireSocket, scheduleReconnect])
+ }, [clearConnectionValidation, failConnectionValidation, publishConnectionPhase, retireSocket, scheduleReconnect, startHeartbeat, stopHeartbeat])
useEffect(() => {
connectRef.current = connect
@@ -356,23 +456,25 @@ export function useUserWs(
void connect()
const resumeConnection = () => {
if (isPageHidden()) {
+ connectionValidationNeededRef.current = true
const generation = connectionGenerationRef.current
- if (authenticatedGenerationRef.current !== generation) {
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.("suspended"))
- }
+ const authenticated = authenticatedGenerationRef.current === generation
+ clearConnectionValidation()
+ stopHeartbeat()
+ publishConnectionPhase("suspended")
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
- if (tokenAbortRef.current) {
+ if (!authenticated) {
connectionGenerationRef.current += 1
- tokenAbortRef.current.abort()
+ tokenAbortRef.current?.abort()
tokenAbortRef.current = null
if (tokenTimeoutRef.current !== null) {
clearTimeout(tokenTimeoutRef.current)
tokenTimeoutRef.current = null
}
+ retireSocket(false)
}
return
}
@@ -383,13 +485,17 @@ export function useUserWs(
const ws = wsRef.current
const generation = connectionGenerationRef.current
const authenticated = authenticatedGenerationRef.current === generation
- const fresh = authenticated
- && ws?.readyState === WebSocket.OPEN
- && Date.now() - lastMessageAtRef.current <= WS_STALE_AFTER_MS
const connecting = ws?.readyState === WebSocket.CONNECTING
- && Date.now() - connectStartedAtRef.current <= WS_CONNECT_TIMEOUT_MS
- if (fresh || connecting) return
+ && 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)
@@ -401,12 +507,14 @@ export function useUserWs(
const onVisibilityChange = () => resumeConnection()
const onPageShow = () => resumeConnection()
const onOnline = () => resumeConnection()
+ const onOffline = () => { connectionValidationNeededRef.current = true }
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", onVisibilityChange)
}
if (typeof window !== "undefined") {
window.addEventListener("pageshow", onPageShow)
window.addEventListener("online", onOnline)
+ window.addEventListener("offline", onOffline)
}
return () => {
if (typeof document !== "undefined") {
@@ -415,8 +523,10 @@ export function useUserWs(
if (typeof window !== "undefined") {
window.removeEventListener("pageshow", onPageShow)
window.removeEventListener("online", onOnline)
+ window.removeEventListener("offline", onOffline)
}
connectionGenerationRef.current += 1
+ clearConnectionValidation()
tokenAbortRef.current?.abort()
tokenAbortRef.current = null
if (reconnectTimerRef.current !== null) {
@@ -425,11 +535,10 @@ export function useUserWs(
}
if (tokenTimeoutRef.current !== null) { clearTimeout(tokenTimeoutRef.current); tokenTimeoutRef.current = null }
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
- if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
- if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
+ stopHeartbeat()
retireSocket(false)
}
- }, [connect, retireSocket])
+ }, [clearConnectionValidation, connect, publishConnectionPhase, retireSocket, stopHeartbeat, validateCurrentConnection])
const send = useCallback((msg: object) => {
const ws = wsRef.current
@@ -439,6 +548,7 @@ export function useUserWs(
}, [])
const reconnectNow = useCallback(() => {
+ clearConnectionValidation()
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
@@ -453,12 +563,11 @@ export function useUserWs(
retireSocket()
if (isPageHidden()) {
connectionGenerationRef.current += 1
- runLifecycleCallback("connection-state", () =>
- onConnectionStateChangeRef.current?.("suspended"))
+ publishConnectionPhase("suspended")
return
}
void connectRef.current?.()
- }, [retireSocket])
+ }, [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
new file mode 100644
index 000000000..cc3893fef
--- /dev/null
+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
@@ -0,0 +1,189 @@
+import { test, expect } from "./_fixtures/community-fixture"
+import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
+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"
+
+test("mobile foreground proof is exact, bounded, and recovers through one current generation", async ({ asUser }, testInfo) => {
+ test.setTimeout(240_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Foreground validation ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `foreground-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+
+ const alice = await asUser("alice")
+ const bob = await asUser("bob")
+ let dropValidationPong = false
+ let holdReplacementAuth = false
+ const proxy = await proxyCommunityWebSockets(alice.context, {
+ decideConnectionFrame: (frame) => {
+ if (
+ dropValidationPong
+ && frame.direction === "server-to-client"
+ && frame.type === "connection.pong"
+ ) return "drop"
+ if (
+ holdReplacementAuth
+ && frame.direction === "server-to-client"
+ && frame.type === "auth.ok"
+ && frame.connectionId > 1
+ ) return "hold"
+ return "forward"
+ },
+ })
+ let tokenRequests = 0
+ alice.page.on("request", (request) => {
+ if (new URL(request.url()).pathname === "/api/ws/token") tokenRequests += 1
+ })
+
+ await alice.page.setViewportSize({ width: 390, height: 844 })
+ await bob.page.setViewportSize({ width: 390, height: 844 })
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(alice.page, route)
+ await gotoAfterUserWsAuth(bob.page, route)
+ await expect(composerEditable(alice.page)).toBeVisible()
+ await expect(composerEditable(bob.page)).toBeVisible()
+ await alice.page.evaluate(() => {
+ let qaVisibility: DocumentVisibilityState = "visible"
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => qaVisibility,
+ })
+ Object.defineProperty(window, "__alookQaSetVisibility", {
+ configurable: true,
+ value: (next: DocumentVisibilityState) => {
+ qaVisibility = next
+ document.dispatchEvent(new Event("visibilitychange"))
+ },
+ })
+ })
+ const setVisibility = async (state: "hidden" | "visible") => {
+ await alice.page.evaluate((next) => {
+ const setter = (window as Window & {
+ __alookQaSetVisibility?: (value: DocumentVisibilityState) => void
+ }).__alookQaSetVisibility
+ if (!setter) throw new Error("QA visibility setter missing")
+ setter(next)
+ }, state)
+ await expect.poll(() => alice.page.evaluate(() => document.visibilityState)).toBe(state)
+ }
+ const dispatchDuplicateResumeSignals = async () => {
+ await alice.page.evaluate(() => {
+ window.dispatchEvent(new Event("pageshow"))
+ window.dispatchEvent(new Event("online"))
+ })
+ }
+ const wsControls = alice.page.locator(
+ `[data-testid='${tid.wsStatus}'], [data-testid='${tid.wsRetry}']`,
+ )
+
+ const initialConnectionCount = proxy.connectionCount()
+ const initialTokenRequests = tokenRequests
+ const hiddenFrameStart = proxy.connectionFrames.length
+ await setVisibility("hidden")
+ await alice.page.waitForTimeout(26_000)
+ expect(proxy.connectionCount()).toBe(initialConnectionCount)
+ expect(tokenRequests).toBe(initialTokenRequests)
+ expect(proxy.connectionFrames.slice(hiddenFrameStart).filter((frame) =>
+ frame.direction === "client-to-server"
+ && (frame.type === "raw.ping" || frame.type === "connection.ping"),
+ )).toEqual([])
+ await expect(wsControls).toHaveCount(0)
+
+ const healthyStart = proxy.connectionFrames.length
+ await setVisibility("visible")
+ await dispatchDuplicateResumeSignals()
+ await expect.poll(() => proxy.connectionFrames.slice(healthyStart).filter((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ ).length).toBe(1)
+ const healthyPing = proxy.connectionFrames.slice(healthyStart).find((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ )!
+ await expect.poll(() => proxy.connectionFrames.slice(healthyStart).filter((frame) =>
+ frame.direction === "server-to-client"
+ && frame.type === "connection.pong"
+ && frame.connectionId === healthyPing.connectionId
+ && frame.nonce === healthyPing.nonce,
+ ).length).toBe(1)
+ expect(proxy.connectionCount()).toBe(initialConnectionCount)
+ expect(tokenRequests).toBe(initialTokenRequests)
+ await expect(wsControls).toHaveCount(0)
+ await expect(composerEditable(alice.page)).toBeVisible()
+
+ await setVisibility("hidden")
+ dropValidationPong = true
+ holdReplacementAuth = true
+ const failedStart = proxy.connectionFrames.length
+ const failedConnectionBaseline = proxy.connectionCount()
+ const failedTokenBaseline = tokenRequests
+ await setVisibility("visible")
+ await dispatchDuplicateResumeSignals()
+ await expect.poll(() => proxy.connectionFrames.slice(failedStart).filter((frame) =>
+ frame.direction === "client-to-server" && frame.type === "connection.ping",
+ ).length).toBe(1)
+ proxy.sendConnectionFrame({ type: "connection.pong", nonce: "queued_stale_nonce" })
+ await alice.page.waitForTimeout(WS_CONNECTION_VALIDATION_TIMEOUT_MS - 1_000)
+ await expect(wsControls).toHaveCount(0)
+
+ await expect(alice.page.getByTestId(tid.wsStatus)).toHaveAttribute(
+ "data-ws-status",
+ "reconnecting",
+ { timeout: 5_000 },
+ )
+ await expect.poll(() => proxy.connectionCount()).toBe(failedConnectionBaseline + 1)
+ await expect.poll(() => tokenRequests).toBe(failedTokenBaseline + 1)
+ await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
+ expect(proxy.connectionFrames.filter((frame) =>
+ frame.direction === "client-to-server"
+ && frame.type === "auth"
+ && frame.connectionId === failedConnectionBaseline + 1,
+ )).toHaveLength(1)
+
+ dropValidationPong = false
+ holdReplacementAuth = false
+ expect(proxy.releaseHeldConnections((frame) =>
+ frame.type === "auth.ok" && frame.connectionId === failedConnectionBaseline + 1,
+ )).toBe(1)
+ await expect(wsControls).toHaveCount(0, { timeout: 10_000 })
+ await expect(composerEditable(alice.page)).toBeVisible()
+
+ try {
+ await alice.context.setOffline(true)
+ await proxy.disconnect()
+ await expect(alice.page.getByTestId(tid.wsStatus)).toHaveAttribute(
+ "data-ws-status",
+ "reconnecting",
+ { timeout: 10_000 },
+ )
+ await expect(alice.page.getByTestId(tid.wsRetry)).toHaveAttribute(
+ "data-ws-status",
+ "failed",
+ { timeout: 40_000 },
+ )
+ } finally {
+ await alice.context.setOffline(false)
+ }
+
+ await alice.page.getByTestId(tid.wsRetry).click()
+ await expect(wsControls).toHaveCount(0, { timeout: 20_000 })
+ const body = `foreground recovery ${stamp}`
+ await sendMessage(bob.page, body)
+ await expect(alice.page.getByText(body, { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect(composerEditable(alice.page)).toBeVisible()
+
+ await testInfo.attach("foreground-validation-frames.json", {
+ body: Buffer.from(JSON.stringify({
+ tokenRequests,
+ connectionCount: proxy.connectionCount(),
+ frames: proxy.connectionFrames,
+ physicalDeviceCoverage: "not run; approved residual risk",
+ stagingCoverage: "not run; approved residual risk",
+ }, null, 2)),
+ contentType: "application/json",
+ })
+ await testInfo.attach("foreground-validation-final.png", {
+ body: await alice.page.screenshot(),
+ contentType: "image/png",
+ })
+})
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 af0070e54..3e89a2e48 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
@@ -16,22 +16,46 @@ type FrameDecision = (
frame: CapturedCommunityFrame,
) => "drop" | "duplicate" | "forward" | "hold"
+export type CapturedConnectionFrame = {
+ connectionId: number
+ direction: "client-to-server" | "server-to-client"
+ type: "auth" | "auth.ok" | "connection.ping" | "connection.pong" | "raw.ping" | "raw.pong"
+ nonce?: string
+ at: number
+}
+
+type ConnectionFrameDecision = (
+ frame: CapturedConnectionFrame,
+) => "drop" | "forward" | "hold"
+
type HeldCommunityFrame = {
client: WebSocketRoute
frame: CapturedCommunityFrame
message: string | Buffer
}
+type HeldConnectionFrame = {
+ client: WebSocketRoute
+ frame: CapturedConnectionFrame
+ message: string | Buffer
+}
+
export type CommunityWsProxy = {
frames: CapturedCommunityFrame[]
+ connectionFrames: CapturedConnectionFrame[]
+ connectionCount: () => number
heldCount: () => number
+ heldConnectionCount: () => number
releaseHeld: (predicate?: (frame: CapturedCommunityFrame) => boolean) => number
+ releaseHeldConnections: (predicate?: (frame: CapturedConnectionFrame) => boolean) => number
replay: (frame: CapturedCommunityFrame) => void
+ sendConnectionFrame: (frame: { type: "connection.pong" | "auth.ok"; nonce?: string }) => void
disconnect: () => Promise<void>
}
export type CommunityWsProxyOptions = {
decide?: FrameDecision
+ decideConnectionFrame?: ConnectionFrameDecision
}
function parseCommunityFrame(message: string | Buffer): CapturedCommunityFrame | null {
@@ -50,18 +74,74 @@ function parseCommunityFrame(message: string | Buffer): CapturedCommunityFrame |
}
}
+function parseConnectionFrame(
+ message: string | Buffer,
+ direction: CapturedConnectionFrame["direction"],
+ connectionId: number,
+): CapturedConnectionFrame | null {
+ const raw = message.toString()
+ if (raw === "ping" || raw === "pong") {
+ return {
+ connectionId,
+ direction,
+ type: raw === "ping" ? "raw.ping" : "raw.pong",
+ at: Date.now(),
+ }
+ }
+ try {
+ const value = JSON.parse(raw) as { type?: unknown; nonce?: unknown }
+ if (
+ value.type !== "auth"
+ && value.type !== "auth.ok"
+ && value.type !== "connection.ping"
+ && value.type !== "connection.pong"
+ ) return null
+ return {
+ connectionId,
+ direction,
+ type: value.type,
+ ...(typeof value.nonce === "string" ? { nonce: value.nonce } : {}),
+ at: Date.now(),
+ }
+ } catch {
+ return null
+ }
+}
+
export async function proxyCommunityWebSockets(
context: BrowserContext,
options: CommunityWsProxyOptions = {},
): Promise<CommunityWsProxy> {
const frames: CapturedCommunityFrame[] = []
const held: HeldCommunityFrame[] = []
+ const connectionFrames: CapturedConnectionFrame[] = []
+ const heldConnectionFrames: HeldConnectionFrame[] = []
const payloads = new WeakMap<CapturedCommunityFrame, string | Buffer>()
let activeClient: WebSocketRoute | undefined
+ let activeConnectionId: number | undefined
+ let connectionCount = 0
await context.routeWebSocket(/.*/, (client: WebSocketRoute) => {
+ connectionCount += 1
+ const connectionId = connectionCount
activeClient = client
+ activeConnectionId = connectionId
const server = client.connectToServer()
+ client.onMessage((message) => {
+ const connectionFrame = parseConnectionFrame(message, "client-to-server", connectionId)
+ if (connectionFrame) connectionFrames.push(connectionFrame)
+ server.send(message)
+ })
server.onMessage((message) => {
+ const connectionFrame = parseConnectionFrame(message, "server-to-client", connectionId)
+ if (connectionFrame) {
+ connectionFrames.push(connectionFrame)
+ const decision = options.decideConnectionFrame?.(connectionFrame) ?? "forward"
+ if (decision === "drop") return
+ if (decision === "hold") {
+ heldConnectionFrames.push({ client, frame: connectionFrame, message })
+ return
+ }
+ }
const frame = parseCommunityFrame(message)
if (frame) {
frames.push(frame)
@@ -81,7 +161,10 @@ export async function proxyCommunityWebSockets(
})
return {
frames,
+ connectionFrames,
+ connectionCount: () => connectionCount,
heldCount: () => held.length,
+ heldConnectionCount: () => heldConnectionFrames.length,
releaseHeld: (predicate = () => true) => {
let released = 0
for (let index = 0; index < held.length;) {
@@ -96,11 +179,38 @@ export async function proxyCommunityWebSockets(
}
return released
},
+ releaseHeldConnections: (predicate = () => true) => {
+ let released = 0
+ for (let index = 0; index < heldConnectionFrames.length;) {
+ const item = heldConnectionFrames[index]!
+ if (!predicate(item.frame)) {
+ index += 1
+ continue
+ }
+ heldConnectionFrames.splice(index, 1)
+ item.client.send(item.message)
+ released += 1
+ }
+ return released
+ },
replay: (frame) => {
const message = payloads.get(frame)
if (!message || !activeClient) throw new Error("community frame is not replayable")
activeClient.send(message)
},
+ sendConnectionFrame: (frame) => {
+ if (!activeClient || activeConnectionId === undefined) {
+ throw new Error("connection frame target missing")
+ }
+ connectionFrames.push({
+ connectionId: activeConnectionId,
+ direction: "server-to-client",
+ type: frame.type,
+ ...(typeof frame.nonce === "string" ? { nonce: frame.nonce } : {}),
+ at: Date.now(),
+ })
+ activeClient.send(JSON.stringify(frame))
+ },
/* istanbul ignore next -- retained offline/reconnect Chromium journey */
disconnect: async () => {
/* istanbul ignore next -- retained offline/reconnect Chromium journey */
@@ -109,6 +219,7 @@ export async function proxyCommunityWebSockets(
const client = activeClient
/* istanbul ignore next -- retained offline/reconnect Chromium journey */
activeClient = undefined
+ activeConnectionId = undefined
/* istanbul ignore next -- retained offline/reconnect Chromium journey */
await client.close({ code: 1012, reason: "test transport offline" })
},
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
index 18bcd3f7d..d4c33a4ec 100644
--- a/src/ws-do/src/ws-durable/user-auth.test.ts
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -521,6 +521,106 @@ describe("WebSocketDurableObject", () => {
describe("webSocketMessage — auth flow", () => {
+ it("echoes an exact connection nonce only for an authenticated user", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "user",
+ userId: "user-42",
+ targetUserId: "user-42",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "connection.ping", nonce: "resume_123" }),
+ )
+
+ expect(ws.send).toHaveBeenCalledOnce()
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({
+ type: "connection.pong",
+ nonce: "resume_123",
+ }))
+ expect(ws.close).not.toHaveBeenCalled()
+ })
+
+ it("closes a pre-authenticated connection validation request", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "user",
+ userId: "",
+ targetUserId: "user-42",
+ authenticated: false,
+ })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "connection.ping", nonce: "resume_123" }),
+ )
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Not authenticated")
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ { type: "connection.ping", nonce: "" },
+ { type: "connection.ping", nonce: "resume_123", extra: true },
+ { type: "connection.ping", nonce: "a".repeat(65) },
+ { type: "connection.pong", nonce: "resume_123" },
+ ])("consumes invalid or client-response control frame %#", async (frame) => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "user",
+ userId: "user-42",
+ targetUserId: "user-42",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify(frame))
+
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ })
+
+ it("ignores array frames without treating them as connection controls", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "user",
+ userId: "user-42",
+ targetUserId: "user-42",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify([]))
+
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ })
+
+ it("consumes connection validation frames from authenticated non-user sockets", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "daemon",
+ daemonId: "daemon-1",
+ userId: "user-42",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "connection.ping", nonce: "resume_123" }),
+ )
+
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.close).not.toHaveBeenCalled()
+ })
+
it("authenticates with valid token and sends auth.ok", async () => {
const { durable } = createDO()
mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
index 51b5da4e2..8ad923680 100644
--- a/src/ws-do/src/ws-durable/user-auth.ts
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -1,6 +1,7 @@
import {
createDb,
encodePreparedCommunityBrowserEventBatch,
+ isUserWsConnectionPing,
isValidCommunityUserTarget,
queries,
readOrStale,
@@ -180,6 +181,20 @@ export async function handleWebSocketMessage(
const state = ws.deserializeAttachment() as ConnectionState
+ const controlType = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>).type
+ : undefined
+ if (controlType === "connection.ping" || controlType === "connection.pong") {
+ if (!state?.authenticated) {
+ ws.close(1008, "Not authenticated")
+ return
+ }
+ if (state.type === "user" && isUserWsConnectionPing(parsed)) {
+ ws.send(JSON.stringify({ type: "connection.pong", nonce: parsed.nonce }))
+ }
+ return
+ }
+
if (state?.type === "community-machine") {
await handleCommunityMachineMessage(parsed)
return