Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(core): add exponential backoff with jitter to WSClient reconnect (#5036)

MeloMei67cd1e645ac9
diff --git a/packages/core/api/ws-client.test.ts b/packages/core/api/ws-client.test.ts
index 2817cb47ba..25e2e82bf0 100644
--- a/packages/core/api/ws-client.test.ts
+++ b/packages/core/api/ws-client.test.ts
@@ -204,4 +204,259 @@ describe("WSClient", () => {
"user",
);
});
+
+ // ── Reconnect backoff tests ────────────────────────────────────────
+
+ describe("reconnect backoff", () => {
+ let setTimeoutSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ });
+
+ afterEach(() => {
+ setTimeoutSpy.mockRestore();
+ vi.useRealTimers();
+ });
+
+ /** Return the delay (ms) passed to the most recent setTimeout call. */
+ function lastTimerDelay(): number {
+ const calls = setTimeoutSpy.mock.calls;
+ return calls[calls.length - 1]?.[1] as number;
+ }
+
+ function simulateDisconnect() {
+ FakeWebSocket.lastInstance!.onclose?.();
+ }
+
+ /** Simulate the server acknowledging the auth token. In token mode the
+ * client sends `{type:"auth"}` on open, and the server replies with
+ * `{type:"auth_ack"}`. Only then does `onAuthenticated()` fire and
+ * reset the reconnect counter. */
+ function simulateAuthAck() {
+ FakeWebSocket.lastInstance!.onmessage?.({
+ data: JSON.stringify({ type: "auth_ack" }),
+ });
+ }
+
+ it("uses ~1000ms base delay for the first reconnect attempt", () => {
+ // Pin Math.random so jitter is deterministic: random()=0.5 → jitter=0.
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+ ws.connect();
+ simulateDisconnect();
+
+ expect(lastTimerDelay()).toBe(1000);
+ });
+
+ it("doubles the base delay on consecutive failures (exponential)", () => {
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+ ws.connect();
+
+ // Attempt 1: base = 1000 * 2^0 = 1000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(1000);
+
+ // Fire the timer → connect() → new FakeWebSocket → simulate disconnect
+ vi.advanceTimersByTime(1000);
+ // Attempt 2: base = 1000 * 2^1 = 2000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(2000);
+
+ vi.advanceTimersByTime(2000);
+ // Attempt 3: base = 1000 * 2^2 = 4000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(4000);
+
+ vi.advanceTimersByTime(4000);
+ // Attempt 4: base = 1000 * 2^3 = 8000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(8000);
+ });
+
+ it("caps the delay at 30s even after many failures", () => {
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+ ws.connect();
+
+ // Drive through enough failures to exceed the cap:
+ // 2^5 = 32000 > 30000, so attempt 6 should be capped.
+ const delays = [1000, 2000, 4000, 8000, 16000];
+ for (const d of delays) {
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(d);
+ vi.advanceTimersByTime(d);
+ }
+
+ // Attempt 6: 1000 * 2^5 = 32000 → capped to 30000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(30000);
+ });
+
+ it("applies jitter so delays vary with Math.random", () => {
+ // Stub Math.random to alternate between 0 (jitter = -20%) and
+ // 1 (jitter = +20%), producing deterministic min/max delays.
+ let callCount = 0;
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => (callCount++ % 2 === 0 ? 0 : 1);
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+
+ // First disconnect: random()=0 → jitter = 1000 * 0.2 * (0*2-1) = -200 → 800ms
+ ws.connect();
+ simulateDisconnect();
+ const delay1 = lastTimerDelay();
+
+ // Second disconnect: random()=1 → jitter = 1000 * 0.2 * (1*2-1) = +200 → 1200ms
+ vi.clearAllTimers();
+ ws.disconnect();
+ ws.connect();
+ simulateDisconnect();
+ const delay2 = lastTimerDelay();
+
+ // The two delays must differ and fall within [800, 1200].
+ expect(delay1).toBe(800);
+ expect(delay2).toBe(1200);
+ });
+
+ it("resets the attempt counter on successful authentication", () => {
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+ ws.setAuth("tok", "acme");
+ ws.connect();
+
+ // Two failures: delays 1000, 2000
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(1000);
+ vi.advanceTimersByTime(1000);
+
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(2000);
+ vi.advanceTimersByTime(2000);
+
+ // Successful connection resets the counter.
+ simulateAuthAck();
+
+ // Next failure should be back to the base delay.
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(1000);
+ });
+
+ it("keeps retrying indefinitely with capped delay", () => {
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const logger = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ const ws = new WSClient("ws://example.test/ws", { logger });
+ ws.connect();
+
+ // Drive past the old 20-attempt limit — all should schedule a reconnect.
+ for (let i = 0; i < 25; i++) {
+ simulateDisconnect();
+ const delay = lastTimerDelay();
+ // Once past attempt 5 (base > 30000), delay should be capped at 30s.
+ if (i >= 5) {
+ expect(delay).toBe(30000);
+ }
+ vi.advanceTimersByTime(delay);
+ }
+
+ // The 26th disconnect should STILL schedule a reconnect (no give-up).
+ const timerCountBefore = setTimeoutSpy.mock.calls.length;
+ simulateDisconnect();
+ expect(setTimeoutSpy.mock.calls.length).toBe(timerCountBefore + 1);
+ expect(lastTimerDelay()).toBe(30000);
+ // No "giving up" error should have been logged.
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+
+ it("disconnect() cancels a pending reconnect and resets the counter", () => {
+ vi.stubGlobal(
+ "Math",
+ new Proxy(Math, {
+ get(target, prop) {
+ if (prop === "random") return () => 0.5;
+ return (target as any)[prop];
+ },
+ }),
+ );
+
+ const ws = new WSClient("ws://example.test/ws");
+ ws.connect();
+
+ // Two failures to bump the counter.
+ simulateDisconnect();
+ vi.advanceTimersByTime(1000);
+ simulateDisconnect();
+ // A reconnect timer is now pending.
+
+ // Explicit disconnect should cancel the pending timer.
+ ws.disconnect();
+ vi.advanceTimersByTime(10_000);
+ // No new WebSocket should have been created after the disconnect.
+ // The last URL should still be from the second connect() call.
+
+ // A fresh connect() after disconnect should start from attempt 0.
+ ws.connect();
+ simulateDisconnect();
+ expect(lastTimerDelay()).toBe(1000);
+ });
+ });
});
diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.ts
index 447df46b12..f4fb086c5b 100644
--- a/packages/core/api/ws-client.ts
+++ b/packages/core/api/ws-client.ts
@@ -8,6 +8,14 @@ type EventHandler = (payload: unknown, actorId?: string, actorType?: string) =>
// be a console / IPC bridge whose buffers we don't want to blow.
const UNPARSEABLE_LOG_MAX_CHARS = 200;
+// Reconnect backoff parameters. A flat delay causes a thundering herd when many
+// clients reconnect after a server restart; exponential backoff with jitter
+// spreads the reconnection attempts over time. The client retries indefinitely
+// (capped at RECONNECT_MAX_DELAY_MS) because the web/desktop UI does not yet
+// expose a visible disconnected state or manual retry action.
+const RECONNECT_BASE_DELAY_MS = 1_000;
+const RECONNECT_MAX_DELAY_MS = 30_000;
+
function summarizeUnparseable(data: unknown): string {
const text = typeof data === "string" ? data : String(data);
if (text.length <= UNPARSEABLE_LOG_MAX_CHARS) return text;
@@ -33,6 +41,7 @@ export class WSClient {
private identity: WSClientIdentity | undefined;
private handlers = new Map<WSEventType, Set<EventHandler>>();
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private reconnectAttempt = 0;
private hasConnectedBefore = false;
// One-shot per connection. A non-conforming frame can repeat hundreds of
// times per session, so we log the first drop and suppress the rest. Reset
@@ -137,8 +146,7 @@ export class WSClient {
};
this.ws.onclose = () => {
- this.logger.warn("disconnected, reconnecting in 3s");
- this.reconnectTimer = setTimeout(() => this.connect(), 3000);
+ this.scheduleReconnect();
};
this.ws.onerror = () => {
@@ -147,8 +155,33 @@ export class WSClient {
};
}
+ /**
+ * Schedule a reconnection attempt with exponential backoff and jitter.
+ * Retries indefinitely with a capped delay because the web/desktop UI
+ * does not yet expose a visible disconnected state or manual retry action.
+ */
+ private scheduleReconnect() {
+ const base = Math.min(
+ RECONNECT_BASE_DELAY_MS * 2 ** this.reconnectAttempt,
+ RECONNECT_MAX_DELAY_MS,
+ );
+ // ±20 % jitter so clients that disconnected at the same time don't
+ // reconnect in lockstep.
+ const jitter = base * 0.2 * (Math.random() * 2 - 1);
+ const delay = Math.round(
+ Math.min(base + jitter, RECONNECT_MAX_DELAY_MS),
+ );
+
+ this.reconnectAttempt++;
+ this.logger.warn(
+ `ws: disconnected, reconnecting in ${delay}ms (attempt ${this.reconnectAttempt})`,
+ );
+ this.reconnectTimer = setTimeout(() => this.connect(), delay);
+ }
+
private onAuthenticated() {
this.logger.info("connected");
+ this.reconnectAttempt = 0;
if (this.hasConnectedBefore) {
for (const cb of this.onReconnectCallbacks) {
try {
@@ -174,6 +207,7 @@ export class WSClient {
this.ws = null;
}
this.hasConnectedBefore = false;
+ this.reconnectAttempt = 0;
this.handlers.clear();
this.anyHandlers.clear();
this.onReconnectCallbacks.clear();