import { describe, expect, it, vi } from "vitest"; import { createChatRealtimeClient, type ChatClientDiagnostic, type ChatClientScheduler, type ChatClientStatus, type ChatLocalEcho, type ChatRealtimeClientOptions, type ChatRemotePresence, type ChatRemoteTyping, type ChatSubscriptionSnapshot, type ChatWebSocketLike, } from "./chat-client.js"; import { CHAT_EVENT_NAMES, type ChatMessageCreatedEvent, type ChatServerEvent } from "./chat-events.js"; import { CHAT_CLIENT_FRAME_TYPES, CHAT_MAX_ACTIVE_SUBSCRIPTIONS, CHAT_SERVER_FRAME_TYPES, parseChatClientFrameJson, serializeChatServerFrame, type ChatClientFrame, type ChatServerFrame, } from "./chat-wire.js"; class FakeScheduler implements ChatClientScheduler { private nextHandle = 1; private currentTime = 1_000; readonly timers = new Map void; dueAt: number }>(); now(): number { return this.currentTime; } setTimeout(callback: () => void, delayMs: number): number { const handle = this.nextHandle; this.nextHandle += 1; this.timers.set(handle, { callback, dueAt: this.currentTime + delayMs }); return handle; } clearTimeout(handle: unknown): void { if (typeof handle === "number") this.timers.delete(handle); } advanceBy(delayMs: number): void { const target = this.currentTime + delayMs; while (true) { const next = [...this.timers.entries()] .filter(([, timer]) => timer.dueAt <= target) .sort((left, right) => left[1].dueAt - right[1].dueAt || left[0] - right[0])[0]; if (!next) break; const [handle, timer] = next; this.currentTime = timer.dueAt; this.timers.delete(handle); timer.callback(); } this.currentTime = target; } } class FakeWebSocket implements ChatWebSocketLike { readyState = 0; bufferedAmount = 0; onopen: (() => void) | null = null; onmessage: ((event: { data: unknown }) => void) | null = null; onerror: ((event: unknown) => void) | null = null; onclose: ((event: { code: number }) => void) | null = null; readonly sent: string[] = []; constructor(readonly url: string) {} open(): void { this.readyState = 1; this.onopen?.(); } send(data: string): void { if (this.readyState !== 1) throw new Error("Socket is not open"); this.sent.push(data); } close(code = 1_000): void { if (this.readyState >= 2) return; this.readyState = 3; this.onclose?.({ code }); } fail(code = 1_006): void { this.close(code); } emitError(): void { this.onerror?.({}); } receive(frame: ChatServerFrame): void { this.onmessage?.({ data: serializeChatServerFrame(frame) }); } receiveRaw(data: unknown): void { this.onmessage?.({ data }); } frames(): ChatClientFrame[] { return this.sent.map((raw) => parseChatClientFrameJson(raw)); } } type Harness = { client: ReturnType; scheduler: FakeScheduler; sockets: FakeWebSocket[]; tokenProvider: ReturnType; statuses: Array<{ status: ChatClientStatus; reconnectAttempt: number; retryAtMs: number | null }>; diagnostics: ChatClientDiagnostic[]; events: Array<{ event: ChatServerEvent; source: "gap" | "live"; reconciledClientMessageId: string | null }>; echoes: Array<{ echo: ChatLocalEcho; reason: string }>; typing: Array<{ chatId: string; entries: readonly ChatRemoteTyping[] }>; presence: Array<{ chatId: string; entries: readonly ChatRemotePresence[] }>; resets: Array<{ chatId: string; currentStreamId: string | null }>; subscriptionChanges: Array<{ chatId: string; subscription: ChatSubscriptionSnapshot | null }>; }; function createHarness(overrides: Partial = {}): Harness { const scheduler = new FakeScheduler(); const sockets: FakeWebSocket[] = []; const statuses: Harness["statuses"] = []; const diagnostics: ChatClientDiagnostic[] = []; const events: Harness["events"] = []; const echoes: Harness["echoes"] = []; const typing: Harness["typing"] = []; const presence: Harness["presence"] = []; const resets: Harness["resets"] = []; const subscriptionChanges: Harness["subscriptionChanges"] = []; const tokenProvider = vi.fn(async () => `token_${tokenProvider.mock.calls.length}`); let requestSequence = 0; let messageSequence = 0; const client = createChatRealtimeClient({ url: "wss://api.example.test/ws/chat", tokenProvider, WebSocket: (url) => { const socket = new FakeWebSocket(url); sockets.push(socket); return socket; }, scheduler, generateId: (kind) => (kind === "request" ? `request_${++requestSequence}` : `client_${++messageSequence}`), random: () => 0.5, reconnect: { baseDelayMs: 100, maxDelayMs: 800, maxAttempts: 3, jitterRatio: 0.2 }, sending: { acknowledgmentTimeoutMs: 200, baseRetryDelayMs: 50, maxRetryDelayMs: 200, maxAttempts: 3, jitterRatio: 0 }, typingTtlMs: 500, presenceTtlMs: 1_000, ...overrides, onStatus: (status, detail) => { statuses.push({ status, ...detail }); overrides.onStatus?.(status, detail); }, onDiagnostic: (diagnostic) => { diagnostics.push(diagnostic); overrides.onDiagnostic?.(diagnostic); }, onEvent: (event, context) => { events.push({ event, ...context }); overrides.onEvent?.(event, context); }, onLocalEcho: (echo, reason) => { echoes.push({ echo, reason }); overrides.onLocalEcho?.(echo, reason); }, onSubscriptionChange: (change) => { subscriptionChanges.push(change); overrides.onSubscriptionChange?.(change); }, onTyping: (chatId, entries) => { typing.push({ chatId, entries }); overrides.onTyping?.(chatId, entries); }, onPresence: (chatId, entries) => { presence.push({ chatId, entries }); overrides.onPresence?.(chatId, entries); }, onResetRequired: (input) => { resets.push(input); overrides.onResetRequired?.(input); }, }); return { client, scheduler, sockets, tokenProvider, statuses, diagnostics, events, echoes, typing, presence, resets, subscriptionChanges }; } async function flushAsync(): Promise { await Promise.resolve(); await Promise.resolve(); } function deferred(): { promise: Promise; resolve: (value: Value) => void } { let resolvePromise: ((value: Value) => void) | undefined; const promise = new Promise((resolve) => { resolvePromise = resolve; }); return { promise, resolve: (value) => { if (!resolvePromise) throw new Error("Deferred promise is unavailable"); resolvePromise(value); }, }; } async function openConnection(harness: Harness): Promise { harness.client.connect(); await flushAsync(); const socket = harness.sockets.at(-1); if (!socket) throw new Error("Expected a chat socket"); socket.open(); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: `connection_${harness.sockets.length}` }); return socket; } async function activateChat(harness: Harness, chatId = "chat_1", cursor = "0"): Promise { harness.client.subscribe(chatId, cursor); const socket = await openConnection(harness); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId, result: { status: "ok", events: [], nextCursor: cursor, hasMore: false }, }); return socket; } function messageCreatedEvent( sequence: number, clientMessageId = `remote_client_${sequence}`, chatId = "chat_1", requestId = `event_request_${sequence}` ): ChatMessageCreatedEvent { const timestamp = `2026-07-15T12:00:0${sequence}.000Z`; return { event: CHAT_EVENT_NAMES.messageCreated, cursor: `stream_1:${sequence}`, requestId, tenantId: "tenant_1", chatId, occurredAt: timestamp, data: { message: { id: `message_${sequence}`, clientMessageId, authorUserId: "user_1", body: `Message ${sequence}`, bodyFormat: "markdown", parentMessageId: null, mentions: [], attachmentIds: [], linkPreviews: [], createdAt: timestamp, updatedAt: timestamp, editedAt: null, deletedAt: null, }, }, }; } function eventFrame(event: ChatServerEvent): ChatServerFrame { return { type: CHAT_SERVER_FRAME_TYPES.event, event }; } describe("chat realtime client", () => { it("serializes subscriptions added after authenticate but before ready on the same socket generation", async () => { const harness = createHarness(); harness.client.connect(); await flushAsync(); const socket = harness.sockets[0]; socket.open(); expect(socket.frames()).toEqual([{ type: CHAT_CLIENT_FRAME_TYPES.authenticate, token: "token_1", resumeCursors: [] }]); harness.client.subscribe("chat_1", "0"); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.subscribe, chatId: "chat_1", afterCursor: "0" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: "connection_1" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "0", hasMore: false }, }); expect(harness.client.status).toBe("online"); expect(harness.client.getSubscriptions()).toEqual([{ chatId: "chat_1", cursor: "0", status: "synchronized" }]); }); it("safely ignores in-flight auth events after unsubscribe-before-ready", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "0"); harness.client.connect(); await flushAsync(); const socket = harness.sockets[0]; socket.open(); harness.client.unsubscribe("chat_1"); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.unsubscribe, chatId: "chat_1" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: "connection_1" }); socket.receive(eventFrame(messageCreatedEvent(1))); expect(harness.client.status).toBe("online"); expect(harness.client.getSubscriptions()).toEqual([]); expect(harness.events).toEqual([]); }); it("authenticates with resume cursors and becomes online only after ordered gap synchronization", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "stream_1:2"); const socket = await openConnection(harness); expect(socket.url).toBe("wss://api.example.test/ws/chat"); expect(socket.frames()[0]).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.authenticate, token: "token_1", resumeCursors: [{ chatId: "chat_1", afterCursor: "stream_1:2" }], }); expect(harness.client.status).toBe("connecting"); socket.receive(eventFrame(messageCreatedEvent(3))); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_1:3", hasMore: false }, }); expect(harness.events).toEqual([{ event: messageCreatedEvent(3), source: "gap", reconciledClientMessageId: null }]); expect(harness.client.getSubscriptions()).toEqual([{ chatId: "chat_1", cursor: "stream_1:3", status: "synchronized" }]); expect(harness.client.status).toBe("online"); expect(harness.statuses.map((entry) => entry.status)).toEqual(["connecting", "online"]); }); it("continues paged gap frames and supports live subscribe and unsubscribe commands", async () => { const harness = createHarness(); const socket = await openConnection(harness); expect(harness.client.status).toBe("online"); harness.client.subscribe("chat_1", "0"); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.subscribe, chatId: "chat_1", afterCursor: "0" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [messageCreatedEvent(1)], nextCursor: "stream_1:1", hasMore: true }, }); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.subscribe, chatId: "chat_1", afterCursor: "stream_1:1", }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_1:1", hasMore: false }, }); harness.client.unsubscribe("chat_1"); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.unsubscribe, chatId: "chat_1" }); expect(harness.client.getSubscriptions()).toEqual([]); expect(harness.events[0]?.source).toBe("gap"); }); it("reconnects with exponential jitter, fresh tokens, and the last confirmed cursor", async () => { const harness = createHarness(); const firstSocket = await activateChat(harness); firstSocket.receive(eventFrame(messageCreatedEvent(1))); firstSocket.fail(); expect(harness.client.status).toBe("reconnecting"); expect(harness.statuses.at(-1)).toEqual({ status: "reconnecting", reconnectAttempt: 1, retryAtMs: 1_090 }); harness.scheduler.advanceBy(89); expect(harness.sockets).toHaveLength(1); harness.scheduler.advanceBy(1); await flushAsync(); const secondSocket = harness.sockets[1]; secondSocket.open(); expect(secondSocket.frames()[0]).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.authenticate, token: "token_2", resumeCursors: [{ chatId: "chat_1", afterCursor: "stream_1:1" }], }); secondSocket.fail(); expect(harness.statuses.at(-1)).toEqual({ status: "reconnecting", reconnectAttempt: 2, retryAtMs: 1_270 }); expect(harness.tokenProvider).toHaveBeenCalledTimes(2); }); it("moves terminal authorization failures to blocked and permits an explicit fresh retry", async () => { const harness = createHarness(); const firstSocket = await openConnection(harness); firstSocket.fail(4_401); expect(harness.client.status).toBe("blocked"); expect(harness.scheduler.timers.size).toBe(0); harness.client.retryNow(); await flushAsync(); expect(harness.sockets).toHaveLength(2); expect(harness.client.status).toBe("connecting"); expect(harness.tokenProvider).toHaveBeenCalledTimes(2); expect(harness.scheduler.timers.size).toBe(1); }); it("blocks invalid token-provider output without opening a socket or retry loop", async () => { const harness = createHarness({ tokenProvider: async () => " invalid-token " }); harness.client.connect(); await flushAsync(); expect(harness.client.status).toBe("blocked"); expect(harness.sockets).toEqual([]); expect(harness.scheduler.timers.size).toBe(0); expect(harness.diagnostics.at(-1)).toEqual({ phase: "token", message: "Chat gateway token provider returned an invalid token.", }); }); it("reconnects on retryable uncorrelated gateway errors", async () => { const harness = createHarness(); const socket = await openConnection(harness); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.error, i18nKey: "chat.errors.realtimeUnavailable", retryable: true, }); expect(harness.client.status).toBe("reconnecting"); expect(harness.diagnostics).toContainEqual( expect.objectContaining({ phase: "validation", message: "Chat gateway returned an uncorrelated operation error." }) ); }); it("times out stale token loads generation-safely and uses the configured watchdog", async () => { const firstToken = deferred(); let calls = 0; const harness = createHarness({ tokenProvider: async () => { calls += 1; return calls === 1 ? firstToken.promise : "token_2"; }, connectionTimeouts: { tokenMs: 20, openMs: 30, readyMs: 40 }, reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 2, jitterRatio: 0 }, }); harness.client.connect(); harness.scheduler.advanceBy(20); expect(harness.client.status).toBe("reconnecting"); expect(harness.sockets).toHaveLength(0); firstToken.resolve("stale_token"); await flushAsync(); expect(harness.sockets).toHaveLength(0); harness.scheduler.advanceBy(10); await flushAsync(); expect(harness.sockets).toHaveLength(1); expect(calls).toBe(2); expect(harness.diagnostics).toContainEqual(expect.objectContaining({ phase: "token", message: "Chat gateway token loading timed out." })); }); it("times out socket-open and ready phases without letting stale generations mutate state", async () => { const openHarness = createHarness({ connectionTimeouts: { tokenMs: 50, openMs: 20, readyMs: 30 }, reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 2, jitterRatio: 0 }, }); openHarness.client.connect(); await flushAsync(); const staleSocket = openHarness.sockets[0]; openHarness.scheduler.advanceBy(20); expect(openHarness.client.status).toBe("reconnecting"); staleSocket.open(); expect(staleSocket.frames()).toEqual([]); const readyHarness = createHarness({ connectionTimeouts: { tokenMs: 50, openMs: 30, readyMs: 20 }, reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 2, jitterRatio: 0 }, }); readyHarness.client.connect(); await flushAsync(); const unreadySocket = readyHarness.sockets[0]; unreadySocket.open(); readyHarness.scheduler.advanceBy(20); expect(readyHarness.client.status).toBe("reconnecting"); expect(readyHarness.diagnostics).toContainEqual(expect.objectContaining({ phase: "socket", message: "Chat gateway ready frame timed out." })); readyHarness.scheduler.advanceBy(10); await flushAsync(); const healthySocket = readyHarness.sockets[1]; healthySocket.open(); healthySocket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: "connection_2" }); expect(readyHarness.client.status).toBe("online"); expect(readyHarness.scheduler.timers.size).toBe(0); }); it("reconnects when initial subscriptions never finish after ready", async () => { const harness = createHarness({ connectionTimeouts: { tokenMs: 50, openMs: 50, readyMs: 50, syncMs: 20 }, reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 2, jitterRatio: 0 }, }); harness.client.subscribe("chat_1", "0"); harness.client.connect(); await flushAsync(); const socket = harness.sockets[0]; socket.open(); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: "connection_1" }); expect(harness.client.status).toBe("connecting"); harness.scheduler.advanceBy(20); expect(harness.client.status).toBe("reconnecting"); expect(harness.diagnostics).toContainEqual(expect.objectContaining({ phase: "socket", message: "Chat subscription synchronization timed out." })); }); it("reconnects when a dynamic subscription receives no acknowledgement", async () => { const harness = createHarness({ connectionTimeouts: { tokenMs: 50, openMs: 50, readyMs: 50, syncMs: 20 }, reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 2, jitterRatio: 0 }, }); await openConnection(harness); expect(harness.client.status).toBe("online"); harness.client.subscribe("chat_1", "0"); harness.scheduler.advanceBy(20); expect(harness.client.status).toBe("reconnecting"); expect(harness.client.getSubscriptions()[0]?.status).toBe("pending"); }); it("stops after the configured reconnect limit and reports offline", async () => { const harness = createHarness({ reconnect: { baseDelayMs: 10, maxDelayMs: 10, maxAttempts: 1, jitterRatio: 0 } }); const firstSocket = await openConnection(harness); firstSocket.fail(); harness.scheduler.advanceBy(10); await flushAsync(); const secondSocket = harness.sockets[1]; secondSocket.open(); secondSocket.fail(); expect(harness.client.status).toBe("offline"); expect(harness.scheduler.timers.size).toBe(0); }); it("reconciles a Local Echo exactly once when its canonical event arrives", async () => { const harness = createHarness(); const socket = await activateChat(harness); const echo = harness.client.sendMessage({ chatId: "chat_1", body: "Hallo Team" }); const sentFrame = socket.frames().at(-1); expect(echo.status).toBe("sending"); expect(sentFrame).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.sendMessage, chatId: "chat_1", requestId: "request_1", clientMessageId: "client_1", body: "Hallo Team", mentions: [], }); const canonical = messageCreatedEvent(1, "client_1", "chat_1", "request_1"); socket.receive(eventFrame(canonical)); socket.receive(eventFrame(canonical)); expect(harness.client.getLocalEchoes()).toEqual([ expect.objectContaining({ requestId: "request_1", clientMessageId: "client_1", status: "sent", failureI18nKey: null, canonicalMessage: canonical.data.message, }), ]); expect(harness.events).toHaveLength(1); expect(harness.events[0]?.reconciledClientMessageId).toBe("client_1"); expect(harness.echoes.filter((entry) => entry.echo.status === "sent")).toHaveLength(1); }); it("reuses a persisted client message id without duplicating an active local echo", async () => { const harness = createHarness(); const socket = await activateChat(harness); const first = harness.client.sendMessage({ chatId: "chat_1", body: "Navigation retry", clientMessageId: "persisted_client_1" }); const duplicate = harness.client.sendMessage({ chatId: "chat_1", body: "Navigation retry", clientMessageId: "persisted_client_1" }); expect(first.clientMessageId).toBe("persisted_client_1"); expect(duplicate).toBe(first); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toEqual([ expect.objectContaining({ clientMessageId: "persisted_client_1", body: "Navigation retry" }), ]); }); it("reuses persisted correlation ids so an idempotent navigation retry settles", async () => { const harness = createHarness(); const socket = await activateChat(harness); const echo = harness.client.sendMessage({ chatId: "chat_1", body: "Navigation retry", clientMessageId: "persisted_client_1", requestId: "persisted_request_1", }); expect(echo).toMatchObject({ clientMessageId: "persisted_client_1", requestId: "persisted_request_1", status: "sending" }); expect(socket.frames().at(-1)).toMatchObject({ type: CHAT_CLIENT_FRAME_TYPES.sendMessage, clientMessageId: "persisted_client_1", requestId: "persisted_request_1", }); socket.receive(eventFrame(messageCreatedEvent(1, "persisted_client_1", "chat_1", "persisted_request_1"))); expect(harness.client.getLocalEchoes()).toEqual([ expect.objectContaining({ clientMessageId: "persisted_client_1", requestId: "persisted_request_1", status: "sent" }), ]); }); it("settles an idempotent replay behind the cursor without redelivering it", async () => { const harness = createHarness(); const socket = await activateChat(harness, "chat_1", "stream_1:2"); harness.client.sendMessage({ chatId: "chat_1", body: "Navigation retry", clientMessageId: "persisted_client_1", requestId: "persisted_request_1", }); socket.receive(eventFrame(messageCreatedEvent(1, "persisted_client_1", "chat_1", "persisted_request_1"))); expect(harness.client.getLocalEchoes()).toEqual([ expect.objectContaining({ clientMessageId: "persisted_client_1", status: "sent", canonicalMessage: expect.any(Object) }), ]); expect(harness.events).toHaveLength(0); expect(harness.client.getSubscriptions()).toEqual([{ chatId: "chat_1", cursor: "stream_1:2", status: "synchronized" }]); }); it("restores an observed failure without dispatching until an explicit retry", async () => { const harness = createHarness(); const socket = await activateChat(harness); const sendCount = socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage).length; const restored = harness.client.restoreFailedMessage({ chatId: "chat_1", body: "Bewusst fehlgeschlagen", clientMessageId: "persisted_client_1", requestId: "persisted_request_1", failureI18nKey: "chat.errors.realtimeUnavailable", retryable: true, createdAtMs: 500, }); expect(restored).toMatchObject({ clientMessageId: "persisted_client_1", requestId: "persisted_request_1", status: "failed", retryable: true, createdAtMs: 500, }); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(sendCount); expect(harness.client.retryMessage("persisted_client_1")).toMatchObject({ status: "sending" }); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(sendCount + 1); expect(socket.frames().at(-1)).toMatchObject({ type: CHAT_CLIENT_FRAME_TYPES.sendMessage, clientMessageId: "persisted_client_1", requestId: "persisted_request_1", }); }); it("retains every active send while evicting settled echoes first", async () => { const harness = createHarness({ sending: { maxRetainedEchoes: 2 } }); const socket = await activateChat(harness); harness.client.sendMessage({ chatId: "chat_1", body: "One" }); harness.client.sendMessage({ chatId: "chat_1", body: "Two" }); harness.client.sendMessage({ chatId: "chat_1", body: "Three" }); expect(harness.client.getLocalEchoes()).toHaveLength(3); expect(harness.client.getLocalEchoes().every((echo) => echo.status === "sending")).toBe(true); socket.receive(eventFrame(messageCreatedEvent(1, "client_1", "chat_1", "request_1"))); expect(harness.client.getLocalEchoes().map((echo) => echo.clientMessageId)).toEqual(["client_2", "client_3"]); expect(harness.echoes.at(-1)).toEqual({ echo: expect.objectContaining({ clientMessageId: "client_1", status: "sent" }), reason: "evicted" }); }); it("reports subscription cursor, synchronization, and removal changes", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "0"); const socket = await openConnection(harness); socket.receive(eventFrame(messageCreatedEvent(1))); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_1:1", hasMore: false }, }); harness.client.unsubscribe("chat_1"); expect(harness.subscriptionChanges).toEqual([ { chatId: "chat_1", subscription: { chatId: "chat_1", cursor: "0", status: "pending" } }, { chatId: "chat_1", subscription: { chatId: "chat_1", cursor: "stream_1:1", status: "pending" } }, { chatId: "chat_1", subscription: { chatId: "chat_1", cursor: "stream_1:1", status: "synchronized" } }, { chatId: "chat_1", subscription: null }, ]); }); it("ignores equal or older loader cursors and resynchronizes only when the loader advances", async () => { const harness = createHarness(); const socket = await activateChat(harness, "chat_1", "stream_1:3"); const framesBefore = socket.frames().length; harness.client.subscribe("chat_1", "stream_1:3"); harness.client.subscribe("chat_1", "stream_1:2"); expect(socket.frames()).toHaveLength(framesBefore); expect(harness.client.status).toBe("online"); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_1:3", status: "synchronized" }); harness.client.subscribe("chat_1", "stream_1:4"); expect(socket.frames().at(-1)).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.subscribe, chatId: "chat_1", afterCursor: "stream_1:4" }); expect(harness.client.status).toBe("reconnecting"); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_1:4", status: "pending" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_1:4", hasMore: false }, }); expect(harness.client.status).toBe("online"); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_1:4", status: "synchronized" }); }); it("rejects no-progress and backwards gap pages without regressing the confirmed cursor", async () => { const noProgress = createHarness(); const noProgressSocket = await activateChat(noProgress, "chat_1", "stream_1:1"); noProgress.client.subscribe("chat_1", "stream_1:2"); noProgressSocket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [messageCreatedEvent(2)], nextCursor: "stream_1:2", hasMore: true }, }); expect(noProgress.client.status).toBe("reconnecting"); expect(noProgress.client.getSubscriptions()[0]?.cursor).toBe("stream_1:2"); expect(noProgress.diagnostics).toContainEqual(expect.objectContaining({ phase: "validation", message: "Chat gap page made no cursor progress." })); const backwards = createHarness(); const backwardsSocket = await activateChat(backwards, "chat_1", "stream_1:2"); backwards.client.subscribe("chat_1", "stream_1:3"); backwardsSocket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_1:1", hasMore: false }, }); expect(backwards.client.status).toBe("reconnecting"); expect(backwards.client.getSubscriptions()[0]?.cursor).toBe("stream_1:3"); }); it("enforces the shared 64-channel active subscription limit", () => { const harness = createHarness(); for (let index = 0; index < CHAT_MAX_ACTIVE_SUBSCRIPTIONS; index += 1) { harness.client.subscribe(`chat_${index}`, "0"); } expect(harness.client.getSubscriptions()).toHaveLength(64); expect(() => harness.client.subscribe("chat_overflow", "0")).toThrow(/maximum of 64/); }); it("requires cursor, request id, and successful consumption before reconciling a Local Echo", async () => { const harness = createHarness(); const socket = await activateChat(harness, "chat_1", "stream_1:2"); harness.client.sendMessage({ chatId: "chat_1", body: "Correlate me" }); socket.receive(eventFrame(messageCreatedEvent(1, "client_1", "chat_1", "wrong_old_request"))); expect(harness.client.getLocalEchoes()[0]).toEqual(expect.objectContaining({ status: "sending", canonicalMessage: null })); socket.receive(eventFrame(messageCreatedEvent(3, "client_1", "chat_1", "wrong_request"))); expect(harness.events.at(-1)?.reconciledClientMessageId).toBeNull(); expect(harness.client.getLocalEchoes()[0]).toEqual(expect.objectContaining({ status: "sending", canonicalMessage: null })); socket.receive(eventFrame(messageCreatedEvent(4, "client_1", "chat_1", "request_1"))); expect(harness.events.at(-1)?.reconciledClientMessageId).toBe("client_1"); expect(harness.client.getLocalEchoes()[0]).toEqual(expect.objectContaining({ status: "sent", canonicalMessage: expect.any(Object) })); }); it("does not reconcile a Local Echo when the consumer rejects the canonical event", async () => { const harness = createHarness({ onEvent: () => { throw new Error("consumer failed"); }, }); const socket = await activateChat(harness); harness.client.sendMessage({ chatId: "chat_1", body: "Consumer must accept" }); socket.receive(eventFrame(messageCreatedEvent(1, "client_1", "chat_1", "request_1"))); expect(harness.client.getSubscriptions()[0]?.cursor).toBe("0"); expect(harness.client.getLocalEchoes()[0]).toEqual(expect.objectContaining({ canonicalMessage: null, status: "failed" })); }); it("fails Local Echo immediately when an online socket is no longer OPEN", async () => { const harness = createHarness(); const socket = await activateChat(harness); socket.readyState = 2; const sentCount = socket.frames().length; const echo = harness.client.sendMessage({ chatId: "chat_1", body: "Closing socket" }); expect(echo).toEqual(expect.objectContaining({ status: "failed", attempts: 0, retryable: true })); expect(socket.frames()).toHaveLength(sentCount); }); it("automatically retries timeouts with stable ids and fails after bounded attempts", async () => { const harness = createHarness(); const socket = await activateChat(harness); harness.client.sendMessage({ chatId: "chat_1", body: "Bitte prüfen" }); harness.scheduler.advanceBy(200); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(1); harness.scheduler.advanceBy(50); harness.scheduler.advanceBy(200); harness.scheduler.advanceBy(100); harness.scheduler.advanceBy(200); const sendFrames = socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage); expect(sendFrames).toHaveLength(3); expect(new Set(sendFrames.map((frame) => frame.type === "send_message" && frame.requestId))).toEqual(new Set(["request_1"])); expect(new Set(sendFrames.map((frame) => frame.type === "send_message" && frame.clientMessageId))).toEqual(new Set(["client_1"])); expect(harness.client.getLocalEchoes()[0]).toEqual( expect.objectContaining({ status: "failed", retryable: true, attempts: 3, failureI18nKey: "chat.errors.realtimeUnavailable" }) ); }); it("retries correlated retryable server errors and preserves non-retryable failures", async () => { const harness = createHarness(); const socket = await activateChat(harness); harness.client.sendMessage({ chatId: "chat_1", body: "Retry me" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.error, i18nKey: "chat.errors.realtimeUnavailable", retryable: true, requestId: "request_1", clientMessageId: "client_1", }); harness.scheduler.advanceBy(50); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(2); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.error, i18nKey: "chat.errors.invalidInput", retryable: false, requestId: "request_1", clientMessageId: "client_1", }); expect(harness.client.getLocalEchoes()[0]).toEqual( expect.objectContaining({ status: "failed", retryable: false, failureI18nKey: "chat.errors.invalidInput" }) ); expect(harness.client.retryMessage("client_1")).toBeNull(); }); it("does not create an offline outbox and only resends failed messages after manual retry", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "0"); const offlineEcho = harness.client.sendMessage({ chatId: "chat_1", body: "Offline" }); expect(offlineEcho).toEqual(expect.objectContaining({ status: "failed", attempts: 0, retryable: true })); const firstSocket = await openConnection(harness); firstSocket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "0", hasMore: false }, }); expect(firstSocket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(0); const retried = harness.client.retryMessage("client_1"); expect(retried).toEqual(expect.objectContaining({ requestId: "request_1", clientMessageId: "client_1", status: "sending" })); expect(firstSocket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(1); firstSocket.fail(); expect(harness.client.getLocalEchoes()[0]).toEqual(expect.objectContaining({ status: "failed", retryable: true })); harness.scheduler.advanceBy(90); await flushAsync(); const secondSocket = harness.sockets[1]; secondSocket.open(); secondSocket.receive({ type: CHAT_SERVER_FRAME_TYPES.ready, connectionId: "connection_2", }); secondSocket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "0", hasMore: false }, }); expect(secondSocket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(0); }); it("sends read, typing, presence, and ping operations only while synchronized", async () => { const harness = createHarness(); expect(harness.client.markRead("chat_1", "message_1", "read_1")).toEqual({ requestId: "read_1", sent: false }); expect(harness.client.setTyping("chat_1", "started")).toBe(false); expect(harness.client.setPresence("away")).toBe(false); const socket = await activateChat(harness); expect(harness.client.markRead("chat_1", "message_1", "read_1")).toEqual({ requestId: "read_1", sent: true }); expect(harness.client.setTyping("chat_1", "started")).toBe(true); expect(harness.client.setTyping("chat_1", "stopped")).toBe(true); expect(harness.client.setPresence("away")).toBe(true); expect(harness.client.ping()).toBe(true); expect(socket.frames().slice(-5)).toEqual([ { type: CHAT_CLIENT_FRAME_TYPES.markRead, chatId: "chat_1", messageId: "message_1", requestId: "read_1" }, { type: CHAT_CLIENT_FRAME_TYPES.typing, chatId: "chat_1", status: "started" }, { type: CHAT_CLIENT_FRAME_TYPES.typing, chatId: "chat_1", status: "stopped" }, { type: CHAT_CLIENT_FRAME_TYPES.presence, status: "away" }, { type: CHAT_CLIENT_FRAME_TYPES.ping }, ]); }); it("expires received typing and presence locally and handles explicit stop/offline events", async () => { const harness = createHarness(); const socket = await activateChat(harness); const base = { cursor: null, requestId: "ephemeral_1", tenantId: "tenant_1", chatId: "chat_1", occurredAt: "2026-07-15T12:00:00.000Z", } as const; socket.receive(eventFrame({ ...base, event: CHAT_EVENT_NAMES.typingStarted, data: { userId: "user_2" } })); socket.receive(eventFrame({ ...base, requestId: "ephemeral_2", event: CHAT_EVENT_NAMES.presenceOnline, data: { userId: "user_2", presence: "online" } })); expect(harness.client.getTyping("chat_1")).toEqual([{ chatId: "chat_1", userId: "user_2", expiresAtMs: 1_500 }]); expect(harness.client.getPresence("chat_1")).toEqual([{ chatId: "chat_1", userId: "user_2", status: "online", expiresAtMs: 2_000 }]); harness.scheduler.advanceBy(500); expect(harness.client.getTyping("chat_1")).toEqual([]); expect(harness.client.getPresence("chat_1")).toHaveLength(1); harness.scheduler.advanceBy(500); expect(harness.client.getPresence("chat_1")).toEqual([]); socket.receive(eventFrame({ ...base, requestId: "ephemeral_3", event: CHAT_EVENT_NAMES.typingStarted, data: { userId: "user_2" } })); socket.receive(eventFrame({ ...base, requestId: "ephemeral_4", event: CHAT_EVENT_NAMES.typingStopped, data: { userId: "user_2" } })); socket.receive(eventFrame({ ...base, requestId: "ephemeral_5", event: CHAT_EVENT_NAMES.presenceAway, data: { userId: "user_2", presence: "away" } })); socket.receive(eventFrame({ ...base, requestId: "ephemeral_6", event: CHAT_EVENT_NAMES.presenceOffline, data: { userId: "user_2", presence: "offline" } })); expect(harness.client.getTyping("chat_1")).toEqual([]); expect(harness.client.getPresence("chat_1")).toEqual([]); expect(harness.typing.at(-1)).toEqual({ chatId: "chat_1", entries: [] }); expect(harness.presence.at(-1)).toEqual({ chatId: "chat_1", entries: [] }); }); it("bounds bufferedAmount, drops ephemeral writes, and retries durable Local Echoes", async () => { const harness = createHarness({ maxBufferedBytes: 200 }); const socket = await activateChat(harness); socket.bufferedAmount = 190; expect(harness.client.setTyping("chat_1", "started")).toBe(false); expect(harness.client.setPresence("online")).toBe(false); harness.client.sendMessage({ chatId: "chat_1", body: "Buffered" }); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(0); expect(harness.diagnostics).toContainEqual(expect.objectContaining({ phase: "backpressure", clientMessageId: "client_1", requestId: "request_1" })); socket.bufferedAmount = 0; harness.scheduler.advanceBy(50); expect(socket.frames().filter((frame) => frame.type === CHAT_CLIENT_FRAME_TYPES.sendMessage)).toHaveLength(1); }); it("ignores a stale subscription reset before processing the current cursor response", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "stream_1:1"); const socket = await openConnection(harness); harness.client.subscribe("chat_1", "stream_2:5"); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "reset_required", currentStreamId: "stream_stale" }, }); expect(harness.resets).toEqual([]); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_2:5", status: "pending" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_2:5", hasMore: false }, }); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_2:5", status: "synchronized" }); }); it("does not deliver events from a stale subscription revision", async () => { const harness = createHarness(); harness.client.subscribe("chat_1", "stream_1:1"); const socket = await openConnection(harness); harness.client.subscribe("chat_1", "stream_2:5"); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [messageCreatedEvent(2)], nextCursor: "stream_1:2", hasMore: false }, }); expect(harness.events).toEqual([]); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_2:5", status: "pending" }); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "ok", events: [], nextCursor: "stream_2:5", hasMore: false }, }); expect(harness.client.getSubscriptions()[0]).toMatchObject({ cursor: "stream_2:5", status: "synchronized" }); }); it("surfaces stream resets and blocks malformed or out-of-scope server frames", async () => { const harness = createHarness(); const socket = await activateChat(harness); harness.client.subscribe("chat_1", "stream_1:1"); socket.receive({ type: CHAT_SERVER_FRAME_TYPES.subscribed, chatId: "chat_1", result: { status: "reset_required", currentStreamId: "stream_2" }, }); expect(harness.resets).toEqual([{ chatId: "chat_1", currentStreamId: "stream_2" }]); expect(harness.client.getSubscriptions()[0]?.status).toBe("reset_required"); expect(harness.client.status).toBe("reconnecting"); socket.receiveRaw("{not-json"); expect(harness.client.status).toBe("blocked"); expect(harness.diagnostics.at(-1)).toEqual({ phase: "validation", message: "Chat gateway returned an invalid frame." }); }); it("does not advance a cursor when the consumer rejects an event", async () => { const onEvent = vi.fn(() => { throw new Error("consumer failed"); }); const harness = createHarness({ onEvent }); const socket = await activateChat(harness); socket.receive(eventFrame(messageCreatedEvent(1))); expect(harness.client.getSubscriptions()[0]?.cursor).toBe("0"); expect(harness.client.status).toBe("reconnecting"); expect(harness.diagnostics).toContainEqual(expect.objectContaining({ phase: "callback", message: "Chat event callback failed.", chatId: "chat_1" })); }); it("discards Local Echoes without leaking timers", async () => { const harness = createHarness(); await activateChat(harness); harness.client.sendMessage({ chatId: "chat_1", body: "Discard me" }); expect(harness.client.discardMessage("client_1")).toBe(true); expect(harness.client.discardMessage("client_1")).toBe(false); expect(harness.client.getLocalEchoes()).toEqual([]); expect(harness.echoes.at(-1)).toEqual({ echo: expect.objectContaining({ clientMessageId: "client_1" }), reason: "discarded" }); expect(harness.scheduler.timers.size).toBe(0); }); });