Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(ws/sync): websocket recconection and heartbeat issues (#3908)
teoc636807afe40
diff --git a/js/app/packages/core/collab/engine.ts b/js/app/packages/core/collab/engine.tsindex 6e4d1c5478..32beadf465 100644--- a/js/app/packages/core/collab/engine.ts+++ b/js/app/packages/core/collab/engine.ts@@ -68,10 +68,12 @@ export function createSyncEngine<await source.pushUpdate(update, peerId).mapErr((err) => {logger.error('failed to push local update to remote', {scope: 'sync_engine',- resolution: 'try to reconnect',+ resolution: 'reconnect if the socket is down',err: err,documentId: source.documentId,});+ // The source only force-reconnects when the socket is not open;+ // liveness of open connections is handled by the heartbeat.source.reconnect();return;});diff --git a/js/app/packages/service-clients/service-sync/source.ts b/js/app/packages/service-clients/service-sync/source.tsindex 394fcf6400..a542c6d466 100644--- a/js/app/packages/service-clients/service-sync/source.ts+++ b/js/app/packages/service-clients/service-sync/source.ts@@ -15,8 +15,9 @@ import { storageServiceClient } from '@service-storage/client';import { createEventBus } from '@solid-primitives/event-bus';import { raceTimeout, until } from '@solid-primitives/promise';import {+ ArrayQueue,BebopSerializer,- ConstantBackoff,+ ExponentialBackoff,type UrlResolver,untilMessage,WebsocketBuilder,@@ -28,7 +29,7 @@ import {} from '@websocket/solid/socket-effect';import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import { encodeFrontiers, type Frontiers } from 'loro-crdt';-import { okAsync, type Result, ResultAsync } from 'neverthrow';+import { errAsync, okAsync, type Result, ResultAsync } from 'neverthrow';import { createStore } from 'solid-js/store';import {FromPeer,@@ -83,28 +84,56 @@ function createSyncServiceSocket(documentId: string, initialToken: string) {return refreshedUrl;};- return new WebsocketBuilder(getUrl)- .withSerializer(new BebopSerializer(FromPeer, FromRemote))- .withBackoff(new ConstantBackoff(500))- .withMaxRetries(20)- .withHeartbeat({- interval: 10_000,- timeout: 5_000,- pingMessage: 'ping',- pongMessage: 'pong',- maxMissedHeartbeats: 2,- autoStart: false, // Start heartbeat manually after initial sync completes- })- .build();+ return (+ new WebsocketBuilder(getUrl)+ .withSerializer(new BebopSerializer(FromPeer, FromRemote))+ // Capped exponential backoff. The scheduler calls next() before the first+ // retry, so the delays are 250*2^1 = 500ms doubling to a 250*2^5 = 8s+ // cap; 20 retries ≈ 2 minutes of automatic attempts, after which+ // something is very wrong and we stop hammering. A given-up socket is+ // revived by 'online' / 'visibilitychange' signals or by the user editing+ // (see pushUpdate) — unlike before, exhausting the budget no longer+ // strands the socket permanently.+ .withBackoff(new ExponentialBackoff(250, 5))+ .withMaxRetries(20)+ // Queue messages sent while disconnected; they are flushed in order once+ // the connection is re-established, so edits made during a reconnect+ // aren't dropped. Unbounded on purpose: dropping the oldest updates would+ // leave dependency gaps the server can never fill, and CRDT updates are+ // tiny relative to a session's lifetime.+ .withBuffer(new ArrayQueue())+ .withHeartbeat({+ interval: 10_000,+ timeout: 5_000,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 2,+ autoStart: false, // Start heartbeat manually after initial sync completes+ })+ .build()+ );}const TIMEOUTS = {INITIAL_SYNC: 10_000,- ACK: 3_000,+ // The server only acks after durably storing the update, and its internal+ // budget for a storage operation is 4.5s — so a busy-but-healthy server can+ // legitimately ack late. Waiting 5s keeps "server is busy" from being+ // misread as "update was lost".+ ACK: 5_000,SNAPSHOT: 10_000,REQUEST_UPDATES_SINCE: 10_000,} as const;+/**+ * Times an un-acked update is re-sent before pushUpdate reports missing_ack.+ * The ACK timeout above covers the busy-server case; the single resend covers+ * a genuinely lost message (sent into a dying socket, or the server handler+ * aborted before acking). Updates are idempotent CRDT ops, so a duplicate+ * delivery is harmless.+ */+const ACK_RESENDS = 1;+type WithCleanup<T> = T & { cleanup: () => void };export const createSyncServiceSource = (@@ -245,6 +274,14 @@ export const createSyncServiceSource = (ws.send(message);};+ /**+ * True once the automatic retry budget is used up (mirrors the scheduling+ * condition in the websocket's retry logic: a retry is only scheduled while+ * retries <= maxRetries). The counter resets on every successful open.+ */+ const retriesExhausted = () =>+ ws.maxRetries !== undefined && (ws.backoff?.retries ?? 0) > ws.maxRetries;+const pushUpdate = (update: RawUpdate): ResultAsync<void, MissingAckError> => {@@ -255,28 +292,67 @@ export const createSyncServiceSource = (}const message = FromPeer.fromPeerUpdate({ update });- ws.send(message);-const ack = () => awaitingAckStore[rawUpdateToString(update)];- return ResultAsync.fromPromise(- raceTimeout(- until(ack),- TIMEOUTS.ACK,- /** make sure until throws **/- true- ),- () =>- ({- type: 'missing_ack',- update: update,- }) as const- ).map(() => {- stopAwaitingAck(update);- });+ const attempt = (+ resendsLeft: number+ ): ResultAsync<void, MissingAckError> => {+ const sent = ws.send(message);+ if (!sent) {+ // Not connected: the update sits in the websocket's send buffer and is+ // flushed (and acked) once the connection is re-established, so don't+ // report a missing ack while the transport is down.+ //+ // If automatic retries gave up (maxRetries exhausted, so no retry is+ // scheduled anymore), this edit is the revival signal. The exhausted+ // check means this never preempts a pending backoff timer, and+ // reconnectIfDisconnected() is additionally a no-op while a+ // connection is open or being established.+ if (retriesExhausted()) {+ ws.reconnectIfDisconnected();+ }+ return okAsync(undefined);+ }++ return ResultAsync.fromPromise(+ raceTimeout(+ until(ack),+ TIMEOUTS.ACK,+ /** make sure until throws **/+ true+ ),+ () =>+ ({+ type: 'missing_ack',+ update: update,+ }) as const+ )+ .map(() => {+ stopAwaitingAck(update);+ })+ .orElse((err) => {+ // Updates are idempotent CRDT ops, so re-sending is safe. Retry+ // before reporting missing_ack: a late ack (slow storage write on+ // the server) shouldn't tear anything down.+ if (resendsLeft > 0) {+ return attempt(resendsLeft - 1);+ }+ return errAsync(err);+ });+ };++ return attempt(ACK_RESENDS);};const pushAwareness = (awareness: RawUpdate) => {+ // Awareness is ephemeral (cursor positions with a short server-side TTL),+ // so never let it sit in the send buffer: replaying a backlog of stale+ // cursor moves after a reconnect would flood the room for no benefit.+ // Drop it unless the socket is open right now — the next local cursor+ // move re-publishes fresh state anyway.+ if (ws.underlyingWebsocket?.readyState !== WebSocket.OPEN) {+ return;+ }const message = FromPeer.fromPeerAwareness({ awareness });ws.send(message);};@@ -306,10 +382,33 @@ export const createSyncServiceSource = (};const reconnect = () => {- ws.reconnect();+ // Only force a new connection when the socket is actually down. Tearing+ // down an OPEN socket (e.g. on a missed ack) caused reconnect storms, and+ // tearing down a CONNECTING one aborts an attempt that may be about to+ // succeed. Liveness of open sockets is owned by the heartbeat.+ ws.reconnectIfDisconnected();};+ // When the browser regains connectivity or the tab becomes visible again,+ // kick the connection immediately instead of waiting out the current+ // backoff timer (which may also have been throttled in background tabs).+ const handleOnline = reconnect;+ const handleVisibilityChange = () => {+ if (document.visibilityState === 'visible') {+ reconnect();+ }+ };++ if (typeof window !== 'undefined') {+ window.addEventListener('online', handleOnline);+ document.addEventListener('visibilitychange', handleVisibilityChange);+ }+const cleanup = () => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('online', handleOnline);+ document.removeEventListener('visibilitychange', handleVisibilityChange);+ }ws.close();};diff --git a/js/app/packages/websocket/core/websocket.ts b/js/app/packages/websocket/core/websocket.tsindex bcfba1eb4e..f54c610a1a 100644--- a/js/app/packages/websocket/core/websocket.ts+++ b/js/app/packages/websocket/core/websocket.ts@@ -42,6 +42,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {private _closedByUser: boolean = false; // whether the websocket was closed by the userprivate _lastConnection?: Date; // timestamp of the last connectionprivate _underlyingWebsocket: WebSocket; // the underlying websocket, e.g. native browser websocket+ private connectPending: boolean = false; // whether tryConnect is resolving its url / creating a socketprivate retryTimeout?: ReturnType<typeof globalThis.setTimeout>; // timeout for the next retry, if anyprivate heartbeatInterval?: ReturnType<typeof setInterval> | undefined; // interval for the heartbeat@@ -284,7 +285,10 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {public close(code?: number, reason?: string): void {this.cancelScheduledConnectionRetry(); // cancel any scheduled retriesthis._closedByUser = true; // mark websocket as closed by user- this._underlyingWebsocket.close(code, reason); // close underlying websocket with provided code and reason+ // The underlying websocket is unassigned while the first connect attempt+ // is still resolving its url; tryConnect observes _closedByUser and+ // won't open a socket after this point.+ (this._underlyingWebsocket as WebSocket | undefined)?.close(code, reason);this.stopHeartbeat();}@@ -330,52 +334,65 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {/*** Creates a new browser-native websocket and connects it to the given URL with the given protocols* and adds all event listeners to the browser-native websocket.- *- * @return the created browser-native websocket which is also stored in the '_underlyingWebsocket' property.*/- private async tryConnect(): Promise<WebSocket> {- const url = await resolveUrl(this._urlResolver);- this._url = url;- const event = new CustomEvent<UrlResolvedEventDetail>(- WebsocketEvent.UrlResolved,- {- detail: {- url: this._url,- },+ private async tryConnect(): Promise<void> {+ this.connectPending = true;+ try {+ const url = await resolveUrl(this._urlResolver);++ // The websocket may have been closed by the user while the url was+ // resolving (e.g. a token fetch); don't open a connection nobody owns.+ if (this._closedByUser) {+ return;}- );- this.dispatchEvent(WebsocketEvent.UrlResolved, event);- const factory = this._options.factory ?? platformWebSocketFactory;- const newSocket = factory(this.url, this.protocols); // create new browser-native websocket and add all event listeners- this._underlyingWebsocket = newSocket;- this._underlyingWebsocket.addEventListener(- WebsocketEvent.Open,- this.handleOpenEvent- );- this._underlyingWebsocket.addEventListener(- WebsocketEvent.Close,- this.handleCloseEvent- );- this._underlyingWebsocket.addEventListener(- WebsocketEvent.Error,- this.handleErrorEvent- );- this._underlyingWebsocket.addEventListener(- WebsocketEvent.Message,- this.handleMessageEvent- );- if (this.binaryType !== undefined) {- this._underlyingWebsocket.binaryType = this.binaryType;- }+ this._url = url;+ const event = new CustomEvent<UrlResolvedEventDetail>(+ WebsocketEvent.UrlResolved,+ {+ detail: {+ url: this._url,+ },+ }+ );+ this.dispatchEvent(WebsocketEvent.UrlResolved, event);+ const factory = this._options.factory ?? platformWebSocketFactory;+ const newSocket = factory(this.url, this.protocols); // create new browser-native websocket and add all event listeners+ this._underlyingWebsocket = newSocket;+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Open,+ this.handleOpenEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Close,+ this.handleCloseEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Error,+ this.handleErrorEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Message,+ this.handleMessageEvent+ );- return this._underlyingWebsocket;+ if (this.binaryType !== undefined) {+ this._underlyingWebsocket.binaryType = this.binaryType;+ }+ } finally {+ this.connectPending = false;+ }}/*** Removes all event listeners from the browser-native websocket and closes it.*/private clearWebsocket() {+ // Nothing to clear while the first connection attempt is still resolving+ // its url (the underlying websocket is only assigned in tryConnect).+ if (!this._underlyingWebsocket) {+ return;+ }this._underlyingWebsocket.removeEventListener(WebsocketEvent.Open,this.handleOpenEvent@@ -396,10 +413,14 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {// Only close if the connection is OPEN or CLOSING// The ws library throws an error when closing a CONNECTING WebSocketconst readyState = this._underlyingWebsocket.readyState;- if (- readyState !== WebSocket.CONNECTING &&- readyState !== WebSocket.CLOSED- ) {+ if (readyState === WebSocket.CONNECTING) {+ // Close the abandoned attempt once it opens so it doesn't linger+ // half-connected on the server.+ const abandoned = this._underlyingWebsocket;+ abandoned.addEventListener(WebsocketEvent.Open, () => abandoned.close(), {+ once: true,+ });+ } else if (readyState !== WebSocket.CLOSED) {this._underlyingWebsocket.close();}}@@ -431,6 +452,10 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {this.heartbeatTimeout = undefined;}+ // A pong proves the connection is alive; only consecutive misses should+ // count towards maxMissedHeartbeats.+ this.missedHeartbeats = 0;+const receivedHeartbeatEvent = new CustomEvent<HeartbeatEventDetail>(WebsocketEvent.HeartbeatReceived,{@@ -529,9 +554,13 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {{ detail });this.dispatchEvent(WebsocketEvent.Reconnect, reconnectEvent);- this.backoff.reset();}+ // Reset on every successful open (not only on reconnects), otherwise+ // retries spent establishing the first connection permanently eat+ // into the maxRetries budget.+ this.backoff?.reset();+if (this._options.heartbeat &&this._options.heartbeat.autoStart !== false@@ -779,8 +808,50 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {}, this._options.heartbeat.interval);}+ /**+ * Tears down the current underlying websocket and connects a fresh one.+ *+ * Unlike close(), this does NOT mark the websocket as closed by the user:+ * send(), heartbeats and automatic retries keep working on the new+ * connection.+ */reconnect() {- this.close();+ // An explicit reconnect always overrides a prior user close — clear the+ // flag before the pending check so a close() that landed while a connect+ // attempt was resolving its url doesn't strand the instance (tryConnect+ // bails on _closedByUser after the url resolves).+ this._closedByUser = false;+ if (this.connectPending) {+ // A fresh connection is already being established (e.g. 'online' and+ // 'visibilitychange' firing together on wake) — starting a second+ // tryConnect would orphan the first socket. With _closedByUser cleared+ // above, the in-flight attempt is adopted as this reconnect.+ return;+ }+ this.cancelScheduledConnectionRetry();+ this.stopHeartbeat();+ this.clearWebsocket(); // detach listeners from (and close) the old socket+ this.connectionState = WebsocketConnectionState.Reconnecting;this.tryConnect();}++ /**+ * Reconnects only if there is no usable connection: a no-op while the+ * underlying websocket is OPEN, still CONNECTING, or a connect attempt is+ * resolving its url, and a no-op after the user closed the websocket+ * (only an explicit reconnect() may override a user close). Safe to call+ * from connectivity signals like 'online' or 'visibilitychange' without+ * disturbing a healthy connection.+ */+ reconnectIfDisconnected() {+ if (this.connectPending || this._closedByUser) {+ return;+ }+ const readyState = (this._underlyingWebsocket as WebSocket | undefined)+ ?.readyState;+ if (readyState === WebSocket.OPEN || readyState === WebSocket.CONNECTING) {+ return;+ }+ this.reconnect();+ }}diff --git a/js/app/packages/websocket/tests/websocket-heartbeat-repro.test.ts b/js/app/packages/websocket/tests/websocket-heartbeat-repro.test.tsnew file mode 100644index 0000000000..5305f69531--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-heartbeat-repro.test.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import {+ ConstantBackoff,+ type Websocket,+ WebsocketBuilder,+ WebsocketEvent,+} from '../';+import {+ startServerWithHeartbeat,+ stopClient,+ stopServer,+ type WebsocketServerWithHeartbeat,+} from './websocket-test-utils';++/**+ * Regression test for intermittent disconnects on long-lived, otherwise+ * healthy connections.+ *+ * `missedHeartbeats` used to be incremented in handleHeartbeatTimeout() but+ * never reset when a pong WAS received, so the counter accumulated over the+ * lifetime of a connection: with maxMissedHeartbeats = 2 (the sync-service+ * config), the 3rd missed pong — even with hours of healthy ping/pong in+ * between — force-closed a healthy connection ("No heartbeat received").+ * Only consecutive misses should close the connection.+ */+describe('missed heartbeats should reset on received pong', () => {+ let client: Websocket | undefined;+ let server: WebsocketServerWithHeartbeat | undefined;+ let url: string;++ beforeEach(async () => {+ server = await startServerWithHeartbeat(0, 5000);+ const address = server.address();+ const port =+ typeof address === 'object' && address !== null ? address.port : 0;+ url = `ws://localhost:${port}`;+ });++ afterEach(async () => {+ await stopClient(client, 5000);+ await stopServer(server, 5000);+ client = undefined;+ server = undefined;+ });++ test('non-consecutive misses, each recovered, do not close the connection', async () => {+ const missed: number[] = [];+ let closed = false;++ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(60_000)) // don't reconnect during test+ .withHeartbeat({+ interval: 150,+ timeout: 80,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 2,+ })+ .build();++ client.addEventListener(WebsocketEvent.HeartbeatMissed, (_w, e) => {+ missed.push((e as CustomEvent).detail.missedHeartbeats);+ });+ client.addEventListener(WebsocketEvent.Close, () => {+ closed = true;+ });++ await new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Open, () => resolve(), {+ once: true,+ })+ );++ const missOne = async () => {+ server!.setRespondToPings(false);+ const target = missed.length + 1;+ while (missed.length < target) {+ await new Promise((r) => setTimeout(r, 20));+ }+ server!.setRespondToPings(true);+ // several healthy ping/pong cycles — these pongs should reset the+ // missed-heartbeat counter+ await new Promise((r) => setTimeout(r, 500));+ };++ await missOne(); // isolated miss #1, recovered+ expect(closed).toBe(false);+ await missOne(); // isolated miss #2, recovered+ expect(closed).toBe(false);+ await missOne(); // isolated miss #3, recovered+ await new Promise((r) => setTimeout(r, 300));++ // Each miss was followed by healthy pongs, so the counter reset and the+ // connection stays open. Without the reset the counter accumulated+ // 1, 2, 3 and the third isolated miss closed the connection.+ expect(closed).toBe(false);+ // Every recorded miss is an isolated first miss, never a streak.+ expect(missed.every((m) => m === 1)).toBe(true);+ }, 20_000);+});diff --git a/js/app/packages/websocket/tests/websocket-reconnect-if-disconnected.test.ts b/js/app/packages/websocket/tests/websocket-reconnect-if-disconnected.test.tsnew file mode 100644index 0000000000..96e9262516--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-reconnect-if-disconnected.test.ts@@ -0,0 +1,167 @@+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import type { WebSocketServer } from 'ws';+import type { Websocket } from '../';+import { ConstantBackoff, WebsocketBuilder, WebsocketEvent } from '../';+import { startServer, stopClient, stopServer } from './websocket-test-utils';++/**+ * Guarantees for reconnectIfDisconnected(), which connectivity signals+ * ('online', 'visibilitychange') and user-activity revival call into:+ *+ * 1. It is a strict no-op while a connection is OPEN or being established —+ * it must never disturb a healthy connection.+ * 2. It revives a connection whose automatic retries have given up.+ * 3. Multiple signals firing together (e.g. 'online' + 'visibilitychange' on+ * laptop wake) produce exactly one new connection, never two.+ */+describe('reconnectIfDisconnected()', () => {+ let url: string;+ let server: WebSocketServer | undefined;+ let client: Websocket | undefined;+ let serverConnections = 0;++ beforeEach(async () => {+ serverConnections = 0;+ server = await startServer(0, 5000);+ const address = server.address();+ const port =+ typeof address === 'object' && address !== null ? address.port : 0;+ url = `ws://localhost:${port}`;+ server.on('connection', () => serverConnections++);+ });++ afterEach(async () => {+ await stopClient(client, 5000);+ await stopServer(server, 5000);+ client = undefined;+ server = undefined;+ });++ const untilOpen = (ws: Websocket) =>+ new Promise<void>((resolve) =>+ ws.addEventListener(WebsocketEvent.Open, () => resolve(), { once: true })+ );++ test('is a no-op on a live connection', async () => {+ let reconnectEvents = 0;+ let retryEvents = 0;++ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(100))+ .build();+ client.addEventListener(WebsocketEvent.Reconnect, () => reconnectEvents++);+ client.addEventListener(WebsocketEvent.retry, () => retryEvents++);++ await untilOpen(client);+ const socketBefore = client.underlyingWebsocket;++ client.reconnectIfDisconnected();+ client.reconnectIfDisconnected();+ await new Promise((r) => setTimeout(r, 300));++ // Same underlying socket, still open, no churn, and the server never saw+ // a second connection.+ expect(client.underlyingWebsocket).toBe(socketBefore);+ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.OPEN);+ expect(reconnectEvents).toBe(0);+ expect(retryEvents).toBe(0);+ expect(serverConnections).toBe(1);+ expect(client.send('still-works')).toBe(true);+ });++ test('revives a connection whose retry budget is exhausted', async () => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(50))+ .withMaxRetries(0) // first close exhausts the budget immediately+ .build();++ await untilOpen(client);++ // Kill the connection server-side; with maxRetries 0 no retry is scheduled.+ const closed = new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Close, () => resolve(), {+ once: true,+ })+ );+ for (const ws of server!.clients) ws.terminate();+ await closed;+ await new Promise((r) => setTimeout(r, 200));+ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.CLOSED);++ // A revival signal brings it back.+ const reopened = untilOpen(client);+ client.reconnectIfDisconnected();+ await reopened;++ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.OPEN);+ expect(client.send('after-revival')).toBe(true);+ expect(serverConnections).toBe(2);+ });++ test('never revives a websocket the user closed', async () => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(50))+ .withMaxRetries(0)+ .build();++ await untilOpen(client);++ const closed = new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Close, () => resolve(), {+ once: true,+ })+ );+ client.close();+ await closed;++ // Late revival signals (a pending pushUpdate resend, an 'online' event+ // racing component cleanup) must not resurrect a deliberately closed+ // socket — that would leak a connection nobody owns.+ client.reconnectIfDisconnected();+ client.reconnectIfDisconnected();+ await new Promise((r) => setTimeout(r, 300));++ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.CLOSED);+ expect(client.closedByUser).toBe(true);+ expect(serverConnections).toBe(1);+ });++ test('simultaneous revival signals create exactly one new connection', async () => {+ // Delay url resolution so the window where a second signal could start a+ // competing connect attempt is wide open.+ const slowResolver = async () => {+ await new Promise((r) => setTimeout(r, 150));+ return url;+ };++ let openEvents = 0;+ client = new WebsocketBuilder(slowResolver)+ .withBackoff(new ConstantBackoff(60_000)) // no auto-retry during the test+ .build();+ client.addEventListener(WebsocketEvent.Open, () => openEvents++);++ await untilOpen(client);++ const closed = new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Close, () => resolve(), {+ once: true,+ })+ );+ for (const ws of server!.clients) ws.terminate();+ await closed;++ // 'online' and 'visibilitychange' firing together on wake, plus a direct+ // reconnect() for good measure — all while the first revival is still+ // resolving its url.+ client.reconnectIfDisconnected();+ client.reconnectIfDisconnected();+ client.reconnect();++ await new Promise((r) => setTimeout(r, 600));++ expect(openEvents).toBe(2); // initial + exactly one revival+ expect(serverConnections).toBe(2);+ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.OPEN);+ expect(client.send('single-connection')).toBe(true);+ }, 10_000);+});diff --git a/js/app/packages/websocket/tests/websocket-reconnect-repro.test.ts b/js/app/packages/websocket/tests/websocket-reconnect-repro.test.tsnew file mode 100644index 0000000000..76c1fa72af--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-reconnect-repro.test.ts@@ -0,0 +1,119 @@+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import type { WebSocketServer } from 'ws';+import type { Websocket } from '../';+import { ConstantBackoff, WebsocketBuilder, WebsocketEvent } from '../';+import { startServer, stopClient, stopServer } from './websocket-test-utils';++/**+ * Regression test for the "connected but messages don't send" bug.+ *+ * `Websocket.reconnect()` used to call `close()`, which set+ * `_closedByUser = true` permanently: the new underlying socket opened fine+ * (UI showed connected), but `send()` short-circuited on `closedByUser` and+ * silently dropped every message. The sync engine calls `reconnect()` when an+ * update ack times out, so one missed ack zombified the connection and every+ * subsequent edit triggered another missed ack -> reconnect -> loop.+ */+describe('reconnect() should produce a usable connection', () => {+ let url: string;+ let server: WebSocketServer | undefined;+ let client: Websocket | undefined;++ beforeEach(async () => {+ server = await startServer(0, 5000);+ const address = server.address();+ const port =+ typeof address === 'object' && address !== null ? address.port : 0;+ url = `ws://localhost:${port}`;+ });++ afterEach(async () => {+ await stopClient(client, 5000);+ await stopServer(server, 5000);+ client = undefined;+ server = undefined;+ });++ test('explicit reconnect() revives a close() that landed during url resolution', async () => {+ const received: string[] = [];+ let connections = 0;+ server!.on('connection', (ws) => {+ connections++;+ ws.on('message', (data) => received.push(data.toString()));+ });++ // Slow url resolution keeps connectPending true long enough for both+ // calls below to land inside the same in-flight connect attempt.+ const slowResolver = async () => {+ await new Promise((r) => setTimeout(r, 150));+ return url;+ };++ client = new WebsocketBuilder(slowResolver)+ .withBackoff(new ConstantBackoff(100))+ .build();++ // close() while the first connect attempt is still resolving its url,+ // then an explicit reconnect() in the same window. The reconnect must+ // override the close by adopting the in-flight attempt — not be+ // silently swallowed by the connect-pending guard.+ client.close();+ client.reconnect();++ await Promise.race([+ new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Open, () => resolve(), {+ once: true,+ })+ ),+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error('socket was never revived')), 3000)+ ),+ ]);++ expect(client.closedByUser).toBe(false);+ expect(client.send('revived')).toBe(true);+ await new Promise((r) => setTimeout(r, 250));+ expect(received).toContain('revived');+ // The pending attempt was adopted, not duplicated.+ expect(connections).toBe(1);+ }, 10_000);++ test('send() works again after a manual reconnect()', async () => {+ const received: string[] = [];+ server!.on('connection', (ws) => {+ ws.on('message', (data) => received.push(data.toString()));+ });++ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(100))+ .build();++ await new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Open, () => resolve(), {+ once: true,+ })+ );++ expect(client.send('before-reconnect')).toBe(true);++ // what engine.ts does on a missed ack+ client.reconnect();++ await new Promise<void>((resolve) =>+ client!.addEventListener(WebsocketEvent.Open, () => resolve(), {+ once: true,+ })+ );++ expect(client.underlyingWebsocket.readyState).toBe(WebSocket.OPEN);++ // A reconnected socket must be able to send.+ const sent = client.send('after-reconnect');+ await new Promise((r) => setTimeout(r, 250));++ expect(sent).toBe(true);+ expect(received).toContain('after-reconnect');+ expect(client.closedByUser).toBe(false);+ }, 10_000);+});diff --git a/rust/sync-service/src/durable_object.rs b/rust/sync-service/src/durable_object.rsindex 155a10b407..57f649a67a 100644--- a/rust/sync-service/src/durable_object.rs+++ b/rust/sync-service/src/durable_object.rs@@ -904,25 +904,15 @@ impl DurableObject for DocumentSyncSession {state.mark_exported();}- let sockets = self.state.get_websockets();-- // on a schedule we should broadcast the current snapshot of the document- // to all connected clients- if !sockets.is_empty() {+ // Re-arm the alarm while clients are connected so the in-memory state+ // stays warm and pending updates keep getting persisted. Updates reach+ // peers when they happen (PeerUpdate broadcast); pushing a full+ // snapshot to every client on every alarm tick only burned bandwidth+ // and stalled clients on large documents.+ if !self.state.get_websockets().is_empty() {bump_alarm(&self.state).await.context("failed to keep document alive")?;-- let snapshot = state- .export_shallow_snapshot()- .context("failed to export snapshot")?;-- websocket::broadcast_snapshot(- sockets.as_slice(),- snapshot.as_slice(),- self.msg_buffer.clone(),- )- .context("failed to broadcast snapshot")?;} else {info!("durable object has reached 0 connections")}diff --git a/rust/sync-service/src/websocket.rs b/rust/sync-service/src/websocket.rsindex 706b43d814..dbf63957b8 100644--- a/rust/sync-service/src/websocket.rs+++ b/rust/sync-service/src/websocket.rs@@ -43,25 +43,6 @@ pub fn send_initial_sync(Ok(())}-// Broadcasts a shallow snapshot of the document state to all connected clients-pub fn broadcast_snapshot(- sockets: &[WebSocket],- snapshot: &[u8],- buf: Arc<Mutex<Vec<u8>>>,-) -> Result<()> {- let message = FromRemote::RemoteSnapshot {- snapshot: SliceWrapper::Raw(snapshot),- };-- let mut buf = buf.lock("serialize RemoteSnapshot in broadcast_snapshot");- let serialized = serialize(message, &mut buf).context("Failed serializing snapshot")?;- for ws in sockets {- ws.send_with_bytes(serialized)- .context("failed to send update message")?;- }- Ok(())-}-pub fn broadcast_awareness(from_socket: &WebSocket,sockets: &[WebSocket],@@ -73,10 +54,13 @@ pub fn broadcast_awareness(};let mut buf = buf.lock("serialize RemoteAwareness in broadcast_awareness");- let serialized = serialize(message, &mut buf).context("TODO")?;+ let serialized = serialize(message, &mut buf).context("failed serializing RemoteAwareness")?;for w in sockets.iter().filter(|w| w != &from_socket) {- w.send_with_bytes(serialized).context("failed to send")?;+ // A dead peer socket must not abort delivery to the remaining peers.+ if let Err(e) = w.send_with_bytes(serialized) {+ tracing::warn!(error = ?e, "failed to send awareness to a peer; continuing");+ }}Ok(())@@ -147,28 +131,40 @@ pub async fn process_message(.await?;{- // send update to peers- let message = FromRemote::RemoteUpdate {+ // ACK the sender first: the update is durably stored at this+ // point, and a failed send to some *other* peer must not block+ // the ack, or the sender tears down a healthy connection. The+ // reverse holds too — if the sender's socket is broken the+ // peers below must still receive the update (the sender will+ // re-send it after reconnecting, which is a harmless+ // duplicate), so a failed ack is logged rather than returned.+ let message = FromRemote::RemoteUpdateAck {update: SliceWrapper::Raw(&update),};-- let mut buf = buf.lock("serialize RemoteUpdate in PeerUpdate handler");+ let mut buf = buf.lock("serialize RemoteUpdateAck in PeerUpdate handler");let serialized =serialize(message, &mut buf).context("Failed serializing update")?;- for w in dss.get_websockets().iter().filter(|w| w != &ws) {- w.send_with_bytes(serialized).context("failed to send")?;+ if let Err(e) = ws.send_with_bytes(serialized) {+ tracing::warn!(error = ?e, "failed to send ack to the update's sender");}}{- // send ACK- let message = FromRemote::RemoteUpdateAck {+ // send update to peers+ let message = FromRemote::RemoteUpdate {update: SliceWrapper::Raw(&update),};- let mut buf = buf.lock("serialize RemoteUpdateAck in PeerUpdate handler");++ let mut buf = buf.lock("serialize RemoteUpdate in PeerUpdate handler");let serialized =serialize(message, &mut buf).context("Failed serializing update")?;- ws.send_with_bytes(serialized).context("failed to send")?;+ for w in dss.get_websockets().iter().filter(|w| w != &ws) {+ // A dead peer socket must not abort delivery to the+ // remaining peers.+ if let Err(e) = w.send_with_bytes(serialized) {+ tracing::warn!(error = ?e, "failed to send update to a peer; continuing");+ }+ }}}// Handle an incoming awareness update from a peer@@ -176,7 +172,10 @@ pub async fn process_message(FromPeer::PeerAwareness {awareness: awareness_update,} => {- awareness.apply(*awareness_update);+ if let Err(e) = awareness.apply(*awareness_update) {+ tracing::warn!(error = ?e, "failed to apply awareness update; ignoring it");+ return Ok(());+ }let encodede = awareness.encode_all();broadcast_awareness(ws, &dss.get_websockets(), &encodede, buf).context("failed to broadcast awareness")?;