From 541f74f8384c606c7e662a38bf749584487093c7 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 5 Nov 2026 12:09:34 -0500 Subject: [PATCH 01/29] fix(socket-mode): observe reconnect failures and stop connecting after disconnect() delayReconnectAttempt chained the reconnect with .then(res) only, and the close handler dropped the returned promise, so a failed reconnect became an unhandled rejection that crashes Node by default. - Propagate the reconnect result (resolve and reject) and log failures from the close-triggered reconnect. - When disconnect() wins the race, reject with the new SMDisconnectedWhileConnectingError, which the close handler swallows, and check for it in start() right after apps.connections.open returns, so no WebSocket is opened after the user disconnected. Fixes #2656. Supersedes #2657. Co-authored-by: w3lld1 <42353747+w3lld1@users.noreply.github.com> Co-authored-by: Claude --- .../socket-mode-reconnect-rejections.md | 5 ++ .../socket-mode/src/SocketModeClient.test.ts | 65 +++++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 24 +++++-- packages/socket-mode/src/errors.test.ts | 13 ++++ packages/socket-mode/src/errors.ts | 9 +++ packages/socket-mode/src/index.ts | 1 + 6 files changed, 112 insertions(+), 5 deletions(-) create mode 100644 .changeset/socket-mode-reconnect-rejections.md diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md new file mode 100644 index 000000000..df1fc00f6 --- /dev/null +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -0,0 +1,5 @@ +--- +"@slack/socket-mode": patch +--- + +Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called while the client is still waiting for `apps.connections.open` no longer leaves a connection opening afterwards: `start()` rejects with the new `SMDisconnectedWhileConnectingError` instead. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index eed6574b0..bdb34d06a 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -511,6 +511,71 @@ describe('SocketModeClient', () => { sinon.assert.calledOnce(startStub); }); }); + + describe('reconnect failures (issue #2656)', () => { + let unhandledRejection: sinon.SinonSpy; + beforeEach(() => { + unhandledRejection = sandbox.spy(); + process.on('unhandledRejection', unhandledRejection); + }); + afterEach(() => { + process.off('unhandledRejection', unhandledRejection); + }); + + function clientWithLogger() { + const logger = new ConsoleLogger(); + const error = sandbox.stub(logger, 'error'); + sandbox.stub(logger, 'debug'); + const client = new SocketModeClient({ appToken: 'xapp-', clientPingTimeout: 1, logger }); + return { client, error }; + } + + function holdWSSURL(client: SocketModeClient) { + let resolveURL: (url: string) => void = () => {}; + sandbox + .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') + .returns(new Promise((resolve) => (resolveURL = resolve))); + return (url: string) => resolveURL(url); + } + + it('should log a rejected reconnect instead of leaving an unhandled rejection', async () => { + const { client, error } = clientWithLogger(); + sandbox.stub(client, 'start').rejects(new Error('invalid_auth')); + + client.emit('close'); + await sleep(10); + + sinon.assert.calledWithMatch(error, 'invalid_auth'); + sinon.assert.notCalled(unhandledRejection); + }); + + it('should not open a connection when disconnect() wins the race with a reconnect', async () => { + const { client, error } = clientWithLogger(); + const releaseURL = holdWSSURL(client); + + client.emit('close'); + await sleep(10); + await client.disconnect(); + releaseURL('ws://127.0.0.1:1/'); + await sleep(10); + + assert.strictEqual(client.websocket, undefined); + sinon.assert.notCalled(error); + sinon.assert.notCalled(unhandledRejection); + }); + + it('should reject start() when disconnect() is called while it is connecting', async () => { + const { client } = clientWithLogger(); + const releaseURL = holdWSSURL(client); + + const starting = client.start(); + await client.disconnect(); + releaseURL('ws://127.0.0.1:1/'); + + await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + assert.strictEqual(client.websocket, undefined); + }); + }); }); async function sleep(ms: number): Promise { diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 5d69a67c1..e0daa287c 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -12,7 +12,12 @@ import { EventEmitter } from 'eventemitter3'; import { type RequestInit, fetch as undiciFetch } from 'undici'; import packageJson from '../package.json'; -import { SMSendWhileDisconnectedError, SMSendWhileNotReadyError, SMWebsocketError } from './errors'; +import { + SMDisconnectedWhileConnectingError, + SMSendWhileDisconnectedError, + SMSendWhileNotReadyError, + SMWebsocketError, +} from './errors'; import log, { type Logger, LogLevel } from './logger'; import { SlackWebSocket, WS_READY_STATES } from './SlackWebSocket'; import type { SocketModeDispatcher, SocketModeOptions } from './SocketModeOptions'; @@ -160,7 +165,11 @@ export class SocketModeClient extends EventEmitter { if (this.websocket?.isActive()) return; if (this.reconnectionTimer) return; if (!this.shuttingDown && this.autoReconnectEnabled) { - this.delayReconnectAttempt(this.start); + this.delayReconnectAttempt(this.start).catch((error) => { + if (!(error instanceof SMDisconnectedWhileConnectingError)) { + this.logger.error(`Failed to reconnect the Socket Mode client (error: ${error})`); + } + }); } else { // If reconnect is disabled or user explicitly called `disconnect()`, emit a disconnected state. this.emit(State.Disconnected); @@ -181,9 +190,13 @@ export class SocketModeClient extends EventEmitter { // python equiv: SocketModeClient.connect this.shuttingDown = false; this.logger.debug('Starting Socket Mode session ...'); + const url = await this.retrieveWSSURL(); + if (this.shuttingDown) { + throw new SMDisconnectedWhileConnectingError(); + } // create a socket connection using SlackWebSocket this.websocket = new SlackWebSocket({ - url: await this.retrieveWSSURL(), + url, // web socket events relevant to this client will be emitted into the instance of this class // see bottom of constructor for where we bind to these events client: this, @@ -248,15 +261,16 @@ export class SocketModeClient extends EventEmitter { this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - return new Promise((res, _rej) => { + return new Promise((res, rej) => { this.reconnectionTimer = setTimeout(() => { this.reconnectionTimer = undefined; if (this.shuttingDown) { this.logger.debug('Client shutting down, will not attempt reconnect.'); + rej(new SMDisconnectedWhileConnectingError()); } else { this.logger.debug('Continuing with reconnect...'); this.emit(State.Reconnecting); - cb.apply(this).then(res); + cb.apply(this).then(res, rej); } }, msBeforeRetry); }); diff --git a/packages/socket-mode/src/errors.test.ts b/packages/socket-mode/src/errors.test.ts index a181fc8a3..6728d1ae0 100644 --- a/packages/socket-mode/src/errors.test.ts +++ b/packages/socket-mode/src/errors.test.ts @@ -4,6 +4,7 @@ import { describe, it } from 'node:test'; import { ErrorCode, SlackSocketModeError, + SMDisconnectedWhileConnectingError, SMNoReplyReceivedError, SMPlatformError, SMSendWhileDisconnectedError, @@ -76,4 +77,16 @@ describe('error classes', () => { assert.ok(err.message.includes('not ready')); }); }); + + describe('SMDisconnectedWhileConnectingError', () => { + it('should be an instance of Error, SlackSocketModeError, and SMDisconnectedWhileConnectingError', () => { + const err = new SMDisconnectedWhileConnectingError(); + assert.ok(err instanceof Error); + assert.ok(err instanceof SlackSocketModeError); + assert.ok(err instanceof SMDisconnectedWhileConnectingError); + assert.equal(err.code, ErrorCode.DisconnectedWhileConnectingError); + assert.equal(err.name, 'SMDisconnectedWhileConnectingError'); + assert.ok(err.message.includes('disconnect()')); + }); + }); }); diff --git a/packages/socket-mode/src/errors.ts b/packages/socket-mode/src/errors.ts index 20e220db0..b144bac7d 100644 --- a/packages/socket-mode/src/errors.ts +++ b/packages/socket-mode/src/errors.ts @@ -15,6 +15,7 @@ export enum ErrorCode { WebsocketError = 'slack_socket_mode_websocket_error', NoReplyReceivedError = 'slack_socket_mode_no_reply_received_error', InitializationError = 'slack_socket_mode_initialization_error', + DisconnectedWhileConnectingError = 'slack_socket_mode_disconnected_while_connecting_error', } export type SMCallError = @@ -81,6 +82,14 @@ export class SMSendWhileDisconnectedError extends SlackSocketModeError { } } +export class SMDisconnectedWhileConnectingError extends SlackSocketModeError { + readonly code = ErrorCode.DisconnectedWhileConnectingError; + + constructor() { + super('Stopped connecting because disconnect() was called before the connection was established'); + } +} + export class SMSendWhileNotReadyError extends SlackSocketModeError { readonly code = ErrorCode.SendWhileNotReadyError; diff --git a/packages/socket-mode/src/index.ts b/packages/socket-mode/src/index.ts index 05ed0ec2a..212250a84 100644 --- a/packages/socket-mode/src/index.ts +++ b/packages/socket-mode/src/index.ts @@ -4,6 +4,7 @@ export { ErrorCode, SlackSocketModeError, SMCallError, + SMDisconnectedWhileConnectingError, SMNoReplyReceivedError, SMPlatformError, SMPlatformErrorEvent, From 362c891310e899fae08287e98a2d671ffb28c2ae Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 5 Nov 2026 13:19:44 -0500 Subject: [PATCH 02/29] refactor(socket-mode): use try/catch for the reconnect failure handler Co-Authored-By: Claude --- packages/socket-mode/src/SocketModeClient.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index e0daa287c..735ce56e4 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -160,16 +160,18 @@ export class SocketModeClient extends EventEmitter { this.on('error', (err) => { this.logger.error(`WebSocket error! ${err}`); }); - this.on('close', () => { + this.on('close', async () => { // Underlying WebSocket connection was closed, possibly reconnect. if (this.websocket?.isActive()) return; if (this.reconnectionTimer) return; if (!this.shuttingDown && this.autoReconnectEnabled) { - this.delayReconnectAttempt(this.start).catch((error) => { + try { + await this.delayReconnectAttempt(this.start); + } catch (error) { if (!(error instanceof SMDisconnectedWhileConnectingError)) { this.logger.error(`Failed to reconnect the Socket Mode client (error: ${error})`); } - }); + } } else { // If reconnect is disabled or user explicitly called `disconnect()`, emit a disconnected state. this.emit(State.Disconnected); From 7f3dde6d7a27dd905112b6183532e28dd3a186f9 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 5 Nov 2026 13:25:48 -0500 Subject: [PATCH 03/29] refactor(socket-mode): await the reconnect delay instead of chaining .then delayReconnectAttempt is now async, so start() runs a microtask after the timer fires. The at-most-one-reconnect test awaits the clock, faking only setTimeout so tickAsync does not stall the node:test runner. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 6 ++--- packages/socket-mode/src/SocketModeClient.ts | 24 +++++++++---------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index bdb34d06a..b7f4f0461 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -499,14 +499,14 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(startStub); }); - it('should schedule at most one reconnect when multiple close events fire', () => { + it('should schedule at most one reconnect when multiple close events fire', async () => { const client = new SocketModeClient({ appToken: 'xapp-', logLevel: LogLevel.ERROR }); const startStub = sandbox.stub(client, 'start').resolves(undefined as never); - const clock = sandbox.useFakeTimers(); + const clock = sandbox.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); client.emit('close'); client.emit('close'); - clock.tick(1_000_000); + await clock.tickAsync(1_000_000); sinon.assert.calledOnce(startStub); }); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 735ce56e4..3c9b12d65 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -259,23 +259,21 @@ export class SocketModeClient extends EventEmitter { * Initiates a reconnect, taking into account configurable delays and number of reconnect attempts and failures. * Accepts a callback to invoke after any calculated delays. */ - private delayReconnectAttempt(cb: () => Promise): Promise { + private async delayReconnectAttempt(cb: () => Promise): Promise { this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - return new Promise((res, rej) => { - this.reconnectionTimer = setTimeout(() => { - this.reconnectionTimer = undefined; - if (this.shuttingDown) { - this.logger.debug('Client shutting down, will not attempt reconnect.'); - rej(new SMDisconnectedWhileConnectingError()); - } else { - this.logger.debug('Continuing with reconnect...'); - this.emit(State.Reconnecting); - cb.apply(this).then(res, rej); - } - }, msBeforeRetry); + await new Promise((resolve) => { + this.reconnectionTimer = setTimeout(resolve, msBeforeRetry); }); + this.reconnectionTimer = undefined; + if (this.shuttingDown) { + this.logger.debug('Client shutting down, will not attempt reconnect.'); + throw new SMDisconnectedWhileConnectingError(); + } + this.logger.debug('Continuing with reconnect...'); + this.emit(State.Reconnecting); + return cb.apply(this); } /** From 026874a8bfeddd863859a83d90220e82067976c2 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 5 Nov 2026 15:05:56 -0500 Subject: [PATCH 04/29] fix(socket-mode): reject start() with the typed error in every connect phase disconnect() during the WebSocket handshake rejected start() with undefined, so a stopped reconnect logged a spurious error. disconnect() during a WSS URL retry wait cleared the timer without settling the delay, so start() never settled. start() now rejects with SMDisconnectedWhileConnectingError whenever it is shutting down, and disconnect() ends the pending reconnect delay. Co-Authored-By: Claude --- .../socket-mode-reconnect-rejections.md | 2 +- .../socket-mode/src/SocketModeClient.test.ts | 55 +++++++++++++++++-- packages/socket-mode/src/SocketModeClient.ts | 6 +- 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index df1fc00f6..b76c482aa 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -2,4 +2,4 @@ "@slack/socket-mode": patch --- -Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called while the client is still waiting for `apps.connections.open` no longer leaves a connection opening afterwards: `start()` rejects with the new `SMDisconnectedWhileConnectingError` instead. +Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMDisconnectedWhileConnectingError` instead of hanging or rejecting with `undefined`. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index b7f4f0461..a2897f28c 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -1,12 +1,12 @@ import assert from 'node:assert/strict'; import { afterEach, beforeEach, describe, it } from 'node:test'; import { ConsoleLogger } from '@slack/logger'; -import type { FetchFunction } from '@slack/web-api'; +import type { FetchFunction, WebClient } from '@slack/web-api'; import proxyquire from 'proxyquire'; import sinon from 'sinon'; import logModule, { LogLevel } from './logger'; -import type { SlackWebSocket } from './SlackWebSocket'; +import { SlackWebSocket } from './SlackWebSocket'; import { SocketModeClient } from './SocketModeClient'; import type { SocketModeDispatcher } from './SocketModeOptions'; @@ -522,14 +522,26 @@ describe('SocketModeClient', () => { process.off('unhandledRejection', unhandledRejection); }); - function clientWithLogger() { + function clientWithLogger(clientPingTimeout = 1) { const logger = new ConsoleLogger(); const error = sandbox.stub(logger, 'error'); sandbox.stub(logger, 'debug'); - const client = new SocketModeClient({ appToken: 'xapp-', clientPingTimeout: 1, logger }); + const client = new SocketModeClient({ appToken: 'xapp-', clientPingTimeout, logger }); return { client, error }; } + function holdHandshake(client: SocketModeClient) { + sandbox + .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') + .resolves('ws://127.0.0.1:1/'); + sandbox.stub(SlackWebSocket.prototype, 'connect'); + } + + function failWSSURL(client: SocketModeClient) { + const { webClient } = client as unknown as { webClient: WebClient }; + sandbox.stub(webClient.apps.connections, 'open').rejects(new Error('internal_error')); + } + function holdWSSURL(client: SocketModeClient) { let resolveURL: (url: string) => void = () => {}; sandbox @@ -575,6 +587,41 @@ describe('SocketModeClient', () => { await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); assert.strictEqual(client.websocket, undefined); }); + + it('should reject start() when disconnect() is called during the WebSocket handshake', async () => { + const { client } = clientWithLogger(); + holdHandshake(client); + + const starting = client.start(); + await sleep(10); + await client.disconnect(); + + await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + }); + + it('should not log an error when disconnect() stops a reconnect during the WebSocket handshake', async () => { + const { client, error } = clientWithLogger(); + holdHandshake(client); + + client.emit('close'); + await sleep(10); + await client.disconnect(); + await sleep(10); + + sinon.assert.notCalled(error); + sinon.assert.notCalled(unhandledRejection); + }); + + it('should reject start() when disconnect() is called while waiting to retry the WSS URL', async () => { + const { client } = clientWithLogger(60_000); + failWSSURL(client); + + const starting = client.start(); + await sleep(10); + await client.disconnect(); + + await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + }); }); }); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 3c9b12d65..ac78e27a5 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -109,6 +109,8 @@ export class SocketModeClient extends EventEmitter { */ private reconnectionTimer: ReturnType | undefined; + private endReconnectDelay: () => void = () => {}; + public constructor( { logger = undefined, @@ -222,7 +224,7 @@ export class SocketModeClient extends EventEmitter { }; disconnectedCallback = (err) => { this.removeListener(State.Connected, connectedCallback); - reject(err); + reject(this.shuttingDown ? new SMDisconnectedWhileConnectingError() : err); }; this.once(State.Connected, connectedCallback); this.once(State.Disconnected, disconnectedCallback); @@ -239,6 +241,7 @@ export class SocketModeClient extends EventEmitter { this.shuttingDown = true; clearTimeout(this.reconnectionTimer); this.reconnectionTimer = undefined; + this.endReconnectDelay(); this.logger.debug('Manually disconnecting this Socket Mode client'); this.emit(State.Disconnecting); return new Promise((resolve, _reject) => { @@ -264,6 +267,7 @@ export class SocketModeClient extends EventEmitter { const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); await new Promise((resolve) => { + this.endReconnectDelay = resolve; this.reconnectionTimer = setTimeout(resolve, msBeforeRetry); }); this.reconnectionTimer = undefined; From a3fbb4ed24eecd01611ffd374e6a4891001b4ee0 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 5 Nov 2026 15:21:32 -0500 Subject: [PATCH 05/29] refactor(socket-mode): rename SMDisconnectedWhileConnectingError to SMConnectAbortedError A shorter name that fits every path that throws it, the internal reconnect included, and matches the State.Connecting vocabulary. The error code becomes slack_socket_mode_connect_aborted_error. Unreleased, so no compatibility shim. Co-Authored-By: Claude --- .changeset/socket-mode-reconnect-rejections.md | 2 +- packages/socket-mode/src/SocketModeClient.test.ts | 6 +++--- packages/socket-mode/src/SocketModeClient.ts | 10 +++++----- packages/socket-mode/src/errors.test.ts | 14 +++++++------- packages/socket-mode/src/errors.ts | 6 +++--- packages/socket-mode/src/index.ts | 2 +- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index b76c482aa..c901b78c0 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -2,4 +2,4 @@ "@slack/socket-mode": patch --- -Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMDisconnectedWhileConnectingError` instead of hanging or rejecting with `undefined`. +Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index a2897f28c..a59d4d039 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -584,7 +584,7 @@ describe('SocketModeClient', () => { await client.disconnect(); releaseURL('ws://127.0.0.1:1/'); - await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + await assert.rejects(starting, { name: 'SMConnectAbortedError' }); assert.strictEqual(client.websocket, undefined); }); @@ -596,7 +596,7 @@ describe('SocketModeClient', () => { await sleep(10); await client.disconnect(); - await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); it('should not log an error when disconnect() stops a reconnect during the WebSocket handshake', async () => { @@ -620,7 +620,7 @@ describe('SocketModeClient', () => { await sleep(10); await client.disconnect(); - await assert.rejects(starting, { name: 'SMDisconnectedWhileConnectingError' }); + await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); }); }); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index ac78e27a5..9fbf05d88 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -13,7 +13,7 @@ import { type RequestInit, fetch as undiciFetch } from 'undici'; import packageJson from '../package.json'; import { - SMDisconnectedWhileConnectingError, + SMConnectAbortedError, SMSendWhileDisconnectedError, SMSendWhileNotReadyError, SMWebsocketError, @@ -170,7 +170,7 @@ export class SocketModeClient extends EventEmitter { try { await this.delayReconnectAttempt(this.start); } catch (error) { - if (!(error instanceof SMDisconnectedWhileConnectingError)) { + if (!(error instanceof SMConnectAbortedError)) { this.logger.error(`Failed to reconnect the Socket Mode client (error: ${error})`); } } @@ -196,7 +196,7 @@ export class SocketModeClient extends EventEmitter { this.logger.debug('Starting Socket Mode session ...'); const url = await this.retrieveWSSURL(); if (this.shuttingDown) { - throw new SMDisconnectedWhileConnectingError(); + throw new SMConnectAbortedError(); } // create a socket connection using SlackWebSocket this.websocket = new SlackWebSocket({ @@ -224,7 +224,7 @@ export class SocketModeClient extends EventEmitter { }; disconnectedCallback = (err) => { this.removeListener(State.Connected, connectedCallback); - reject(this.shuttingDown ? new SMDisconnectedWhileConnectingError() : err); + reject(this.shuttingDown ? new SMConnectAbortedError() : err); }; this.once(State.Connected, connectedCallback); this.once(State.Disconnected, disconnectedCallback); @@ -273,7 +273,7 @@ export class SocketModeClient extends EventEmitter { this.reconnectionTimer = undefined; if (this.shuttingDown) { this.logger.debug('Client shutting down, will not attempt reconnect.'); - throw new SMDisconnectedWhileConnectingError(); + throw new SMConnectAbortedError(); } this.logger.debug('Continuing with reconnect...'); this.emit(State.Reconnecting); diff --git a/packages/socket-mode/src/errors.test.ts b/packages/socket-mode/src/errors.test.ts index 6728d1ae0..752062657 100644 --- a/packages/socket-mode/src/errors.test.ts +++ b/packages/socket-mode/src/errors.test.ts @@ -4,7 +4,7 @@ import { describe, it } from 'node:test'; import { ErrorCode, SlackSocketModeError, - SMDisconnectedWhileConnectingError, + SMConnectAbortedError, SMNoReplyReceivedError, SMPlatformError, SMSendWhileDisconnectedError, @@ -78,14 +78,14 @@ describe('error classes', () => { }); }); - describe('SMDisconnectedWhileConnectingError', () => { - it('should be an instance of Error, SlackSocketModeError, and SMDisconnectedWhileConnectingError', () => { - const err = new SMDisconnectedWhileConnectingError(); + describe('SMConnectAbortedError', () => { + it('should be an instance of Error, SlackSocketModeError, and SMConnectAbortedError', () => { + const err = new SMConnectAbortedError(); assert.ok(err instanceof Error); assert.ok(err instanceof SlackSocketModeError); - assert.ok(err instanceof SMDisconnectedWhileConnectingError); - assert.equal(err.code, ErrorCode.DisconnectedWhileConnectingError); - assert.equal(err.name, 'SMDisconnectedWhileConnectingError'); + assert.ok(err instanceof SMConnectAbortedError); + assert.equal(err.code, ErrorCode.ConnectAbortedError); + assert.equal(err.name, 'SMConnectAbortedError'); assert.ok(err.message.includes('disconnect()')); }); }); diff --git a/packages/socket-mode/src/errors.ts b/packages/socket-mode/src/errors.ts index b144bac7d..279ff859e 100644 --- a/packages/socket-mode/src/errors.ts +++ b/packages/socket-mode/src/errors.ts @@ -15,7 +15,7 @@ export enum ErrorCode { WebsocketError = 'slack_socket_mode_websocket_error', NoReplyReceivedError = 'slack_socket_mode_no_reply_received_error', InitializationError = 'slack_socket_mode_initialization_error', - DisconnectedWhileConnectingError = 'slack_socket_mode_disconnected_while_connecting_error', + ConnectAbortedError = 'slack_socket_mode_connect_aborted_error', } export type SMCallError = @@ -82,8 +82,8 @@ export class SMSendWhileDisconnectedError extends SlackSocketModeError { } } -export class SMDisconnectedWhileConnectingError extends SlackSocketModeError { - readonly code = ErrorCode.DisconnectedWhileConnectingError; +export class SMConnectAbortedError extends SlackSocketModeError { + readonly code = ErrorCode.ConnectAbortedError; constructor() { super('Stopped connecting because disconnect() was called before the connection was established'); diff --git a/packages/socket-mode/src/index.ts b/packages/socket-mode/src/index.ts index 212250a84..ab85b6bc2 100644 --- a/packages/socket-mode/src/index.ts +++ b/packages/socket-mode/src/index.ts @@ -4,7 +4,7 @@ export { ErrorCode, SlackSocketModeError, SMCallError, - SMDisconnectedWhileConnectingError, + SMConnectAbortedError, SMNoReplyReceivedError, SMPlatformError, SMPlatformErrorEvent, From 4482a2379f195a45ae39be6b3fa73194700f30b8 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 09:48:19 -0500 Subject: [PATCH 06/29] fix(socket-mode): emit disconnected when a reconnect gives up A reconnect that fails for good (invalid_auth after a token revoke) was only logged, leaving the process up with no socket and nothing for the app to listen to. Emit State.Disconnected with the cause so apps and Bolt can react, as they could when the rejection crashed the process. Co-Authored-By: Claude --- .changeset/socket-mode-reconnect-rejections.md | 2 +- .../socket-mode/src/SocketModeClient.test.ts | 16 ++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index c901b78c0..227616674 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -2,4 +2,4 @@ "@slack/socket-mode": patch --- -Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. +Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged, and the client emits `disconnected` with the error so apps can react. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index a59d4d039..873f70b13 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -561,6 +561,19 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(unhandledRejection); }); + it('should emit disconnected with the cause when a reconnect fails for good', async () => { + const { client } = clientWithLogger(); + const cause = new Error('invalid_auth'); + sandbox.stub(client, 'start').rejects(cause); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + client.emit('close'); + await sleep(10); + + sinon.assert.calledOnceWithExactly(disconnected, cause); + }); + it('should not open a connection when disconnect() wins the race with a reconnect', async () => { const { client, error } = clientWithLogger(); const releaseURL = holdWSSURL(client); @@ -602,6 +615,8 @@ describe('SocketModeClient', () => { it('should not log an error when disconnect() stops a reconnect during the WebSocket handshake', async () => { const { client, error } = clientWithLogger(); holdHandshake(client); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); client.emit('close'); await sleep(10); @@ -610,6 +625,7 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(error); sinon.assert.notCalled(unhandledRejection); + sinon.assert.calledOnce(disconnected); }); it('should reject start() when disconnect() is called while waiting to retry the WSS URL', async () => { diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 9fbf05d88..3c7290710 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -172,6 +172,7 @@ export class SocketModeClient extends EventEmitter { } catch (error) { if (!(error instanceof SMConnectAbortedError)) { this.logger.error(`Failed to reconnect the Socket Mode client (error: ${error})`); + this.emit(State.Disconnected, error); } } } else { From 0a7371d306b4f3c574fa90b52b2d603c981e6c30 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 09:49:05 -0500 Subject: [PATCH 07/29] fix(socket-mode): skip the reconnect delay once disconnect() is called When disconnect() landed while apps.connections.open was in flight and that call then failed recoverably, a fresh backoff was armed after disconnect() had already ended the pending one, so start() only rejected after clientPingTimeout * n ms. Bail before arming the wait. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 20 +++++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 3 +++ 2 files changed, 23 insertions(+) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 873f70b13..997dd5dad 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -542,6 +542,15 @@ describe('SocketModeClient', () => { sandbox.stub(webClient.apps.connections, 'open').rejects(new Error('internal_error')); } + function holdThenFailWSSURL(client: SocketModeClient) { + const { webClient } = client as unknown as { webClient: WebClient }; + let rejectURL: (error: Error) => void = () => {}; + sandbox + .stub(webClient.apps.connections, 'open') + .returns(new Promise((_resolve, reject) => (rejectURL = reject))); + return (error: Error) => rejectURL(error); + } + function holdWSSURL(client: SocketModeClient) { let resolveURL: (url: string) => void = () => {}; sandbox @@ -638,6 +647,17 @@ describe('SocketModeClient', () => { await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); + + it('should reject start() without waiting to retry when the WSS URL fails after disconnect()', async () => { + const { client } = clientWithLogger(60_000); + const failURL = holdThenFailWSSURL(client); + + const starting = client.start(); + await client.disconnect(); + failURL(new Error('internal_error')); + + await assert.rejects(starting, { name: 'SMConnectAbortedError' }); + }); }); }); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 3c7290710..12be05b79 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -264,6 +264,9 @@ export class SocketModeClient extends EventEmitter { * Accepts a callback to invoke after any calculated delays. */ private async delayReconnectAttempt(cb: () => Promise): Promise { + if (this.shuttingDown) { + throw new SMConnectAbortedError(); + } this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); From 6cd76f8419f579f9060a1dca7fc1faef7064d135 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 09:53:24 -0500 Subject: [PATCH 08/29] test(socket-mode): hold the handshake on a real socket The handshake tests stubbed SlackWebSocket.connect, so disconnect() took the already-disconnected cleanup branch instead of closing a CONNECTING socket. Point them at a local TCP server that never upgrades. Closing a CONNECTING socket logs a WebSocket error (also on main), so the reconnect test now asserts only that the reconnect failure is not logged. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 997dd5dad..04babb340 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { type AddressInfo, createServer, type Server, type Socket } from 'node:net'; import { afterEach, beforeEach, describe, it } from 'node:test'; import { ConsoleLogger } from '@slack/logger'; import type { FetchFunction, WebClient } from '@slack/web-api'; @@ -6,7 +7,7 @@ import proxyquire from 'proxyquire'; import sinon from 'sinon'; import logModule, { LogLevel } from './logger'; -import { SlackWebSocket } from './SlackWebSocket'; +import type { SlackWebSocket } from './SlackWebSocket'; import { SocketModeClient } from './SocketModeClient'; import type { SocketModeDispatcher } from './SocketModeOptions'; @@ -514,12 +515,19 @@ describe('SocketModeClient', () => { describe('reconnect failures (issue #2656)', () => { let unhandledRejection: sinon.SinonSpy; - beforeEach(() => { + let neverUpgrades: Server; + let heldSockets: Socket[]; + beforeEach(async () => { unhandledRejection = sandbox.spy(); process.on('unhandledRejection', unhandledRejection); + heldSockets = []; + neverUpgrades = createServer((socket) => heldSockets.push(socket)); + await new Promise((resolve) => neverUpgrades.listen(0, '127.0.0.1', resolve)); }); - afterEach(() => { + afterEach(async () => { process.off('unhandledRejection', unhandledRejection); + for (const socket of heldSockets) socket.destroy(); + await new Promise((resolve) => neverUpgrades.close(resolve)); }); function clientWithLogger(clientPingTimeout = 1) { @@ -531,10 +539,10 @@ describe('SocketModeClient', () => { } function holdHandshake(client: SocketModeClient) { + const { port } = neverUpgrades.address() as AddressInfo; sandbox .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') - .resolves('ws://127.0.0.1:1/'); - sandbox.stub(SlackWebSocket.prototype, 'connect'); + .resolves(`ws://127.0.0.1:${port}/`); } function failWSSURL(client: SocketModeClient) { @@ -545,9 +553,7 @@ describe('SocketModeClient', () => { function holdThenFailWSSURL(client: SocketModeClient) { const { webClient } = client as unknown as { webClient: WebClient }; let rejectURL: (error: Error) => void = () => {}; - sandbox - .stub(webClient.apps.connections, 'open') - .returns(new Promise((_resolve, reject) => (rejectURL = reject))); + sandbox.stub(webClient.apps.connections, 'open').returns(new Promise((_resolve, reject) => (rejectURL = reject))); return (error: Error) => rejectURL(error); } @@ -632,7 +638,7 @@ describe('SocketModeClient', () => { await client.disconnect(); await sleep(10); - sinon.assert.notCalled(error); + sinon.assert.neverCalledWithMatch(error, 'Failed to reconnect'); sinon.assert.notCalled(unhandledRejection); sinon.assert.calledOnce(disconnected); }); From 429a51436cd2907d88541352ffcbea1997ef27b6 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 10:30:51 -0500 Subject: [PATCH 09/29] docs(socket-mode): explain how a failed reconnect now ends the process A reconnect that fails for good used to crash with exit code 1, which restart-on-failure supervisors relied on. Now it logs, emits disconnected, and exits 0 when nothing else holds the event loop, or keeps running without a connection. Spell that out in the changeset with the opt-in to keep crashing. Co-Authored-By: Claude --- .changeset/socket-mode-reconnect-rejections.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index 227616674..d8d4a6a74 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -2,4 +2,14 @@ "@slack/socket-mode": patch --- -Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged, and the client emits `disconnected` with the error so apps can react. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. +Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged, and the client emits `disconnected` with the error so apps can react. The process no longer crashes: with nothing else keeping it alive it exits with code 0, otherwise it keeps running without a connection. To keep the old crash-and-restart behavior, exit on that event: + +```js +client.on('disconnected', (error) => { + if (error) process.exit(1); +}); +``` + +In Bolt, the client is `receiver.client`. + +Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. From c7e0441745f55346f75e500695009b8e4f8eba93 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 10:57:04 -0500 Subject: [PATCH 10/29] refactor(socket-mode): cancel the reconnect delay with an AbortSignal clearTimeout never settles the promise awaiting the timer, so disconnect() needed a stored resolver to end the wait. The abortable setTimeout from node:timers/promises does that directly and replaces both the timer handle and the resolver. A new test pins that disconnect() clears the pending delay right away, which keeps the close listener from ignoring the close event disconnect() itself triggers. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 16 ++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 22 ++++++++----------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 04babb340..497c92dfa 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -604,6 +604,22 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(unhandledRejection); }); + it('should resolve disconnect() while a reconnect is waiting', { timeout: 2000 }, async () => { + const { client } = clientWithLogger(60_000); + const startStub = sandbox.stub(client, 'start'); + client.websocket = { + isActive: () => false, + disconnect: () => client.emit('close'), + } as unknown as SlackWebSocket; + + client.emit('close'); + await sleep(10); + await client.disconnect(); + + sinon.assert.notCalled(startStub); + sinon.assert.notCalled(unhandledRejection); + }); + it('should reject start() when disconnect() is called while it is connecting', async () => { const { client } = clientWithLogger(); const releaseURL = holdWSSURL(client); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 12be05b79..09a2d69e3 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -1,3 +1,4 @@ +import { setTimeout as sleep } from 'node:timers/promises'; import { type AppsConnectionsOpenResponse, addAppMetadata, @@ -105,11 +106,9 @@ export class SocketModeClient extends EventEmitter { private shuttingDown = false; /** - * Timer handle for scheduling automatic reconnection attempts after a disconnect. + * Cancels the pending wait before an automatic reconnection attempt. */ - private reconnectionTimer: ReturnType | undefined; - - private endReconnectDelay: () => void = () => {}; + private reconnectDelay: AbortController | undefined; public constructor( { @@ -165,7 +164,7 @@ export class SocketModeClient extends EventEmitter { this.on('close', async () => { // Underlying WebSocket connection was closed, possibly reconnect. if (this.websocket?.isActive()) return; - if (this.reconnectionTimer) return; + if (this.reconnectDelay) return; if (!this.shuttingDown && this.autoReconnectEnabled) { try { await this.delayReconnectAttempt(this.start); @@ -240,9 +239,8 @@ export class SocketModeClient extends EventEmitter { */ public disconnect(): Promise { this.shuttingDown = true; - clearTimeout(this.reconnectionTimer); - this.reconnectionTimer = undefined; - this.endReconnectDelay(); + this.reconnectDelay?.abort(); + this.reconnectDelay = undefined; this.logger.debug('Manually disconnecting this Socket Mode client'); this.emit(State.Disconnecting); return new Promise((resolve, _reject) => { @@ -270,11 +268,9 @@ export class SocketModeClient extends EventEmitter { this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - await new Promise((resolve) => { - this.endReconnectDelay = resolve; - this.reconnectionTimer = setTimeout(resolve, msBeforeRetry); - }); - this.reconnectionTimer = undefined; + this.reconnectDelay = new AbortController(); + await sleep(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {}); + this.reconnectDelay = undefined; if (this.shuttingDown) { this.logger.debug('Client shutting down, will not attempt reconnect.'); throw new SMConnectAbortedError(); From 501fea251a69651d443b6e6fed75e7c3a8e1047e Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 11:08:18 -0500 Subject: [PATCH 11/29] refactor(socket-mode): import setTimeout from timers/promises without an alias Co-Authored-By: Claude --- packages/socket-mode/src/SocketModeClient.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 09a2d69e3..ef94b3201 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -1,4 +1,4 @@ -import { setTimeout as sleep } from 'node:timers/promises'; +import { setTimeout } from 'node:timers/promises'; import { type AppsConnectionsOpenResponse, addAppMetadata, @@ -269,7 +269,7 @@ export class SocketModeClient extends EventEmitter { const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); this.reconnectDelay = new AbortController(); - await sleep(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {}); + await setTimeout(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {}); this.reconnectDelay = undefined; if (this.shuttingDown) { this.logger.debug('Client shutting down, will not attempt reconnect.'); From 6815c933d9f2fad6100582881803bd07a9409d67 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 10:48:36 -0800 Subject: [PATCH 12/29] Update .changeset/socket-mode-reconnect-rejections.md Co-authored-by: Michael Brooks --- .changeset/socket-mode-reconnect-rejections.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index d8d4a6a74..3ad56f11e 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -1,5 +1,5 @@ --- -"@slack/socket-mode": patch +"@slack/socket-mode": minor --- Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged, and the client emits `disconnected` with the error so apps can react. The process no longer crashes: with nothing else keeping it alive it exits with code 0, otherwise it keeps running without a connection. To keep the old crash-and-restart behavior, exit on that event: From d26bb3d39bf85e7ac89f475ce82efe7e0e094ab8 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Fri, 6 Nov 2026 15:01:35 -0500 Subject: [PATCH 13/29] fix(socket-mode): swallow only an aborted reconnect, keep real failures loud The close handler now ignores only SMConnectAbortedError, the disconnect() race from #2656. A reconnect that fails for good rejects with its cause, as on main, instead of being logged and emitted as `disconnected`. Bolt never listens for that event, so a default app exited 0 and on-failure supervisors stopped restarting it, and nested reconnects emitted `disconnected` twice. Co-Authored-By: Claude --- .../socket-mode-reconnect-rejections.md | 10 +------ .../socket-mode/src/SocketModeClient.test.ts | 26 ++++--------------- packages/socket-mode/src/SocketModeClient.ts | 3 +-- 3 files changed, 7 insertions(+), 32 deletions(-) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index 3ad56f11e..66cbbac5d 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -2,14 +2,6 @@ "@slack/socket-mode": minor --- -Fix an unhandled promise rejection when an automatic reconnect fails ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)), which could crash the process. The failure is now logged, and the client emits `disconnected` with the error so apps can react. The process no longer crashes: with nothing else keeping it alive it exits with code 0, otherwise it keeps running without a connection. To keep the old crash-and-restart behavior, exit on that event: - -```js -client.on('disconnected', (error) => { - if (error) process.exit(1); -}); -``` - -In Bolt, the client is `receiver.client`. +Fix an unhandled promise rejection of `undefined` that could crash the process when `disconnect()` raced a pending automatic reconnect ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)). A reconnect that fails for good still rejects as before, with its cause. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 497c92dfa..d5d4ba1f5 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -565,28 +565,13 @@ describe('SocketModeClient', () => { return (url: string) => resolveURL(url); } - it('should log a rejected reconnect instead of leaving an unhandled rejection', async () => { - const { client, error } = clientWithLogger(); - sandbox.stub(client, 'start').rejects(new Error('invalid_auth')); - - client.emit('close'); - await sleep(10); - - sinon.assert.calledWithMatch(error, 'invalid_auth'); - sinon.assert.notCalled(unhandledRejection); - }); - - it('should emit disconnected with the cause when a reconnect fails for good', async () => { + it('should reject with the cause when a reconnect fails for good', async () => { const { client } = clientWithLogger(); const cause = new Error('invalid_auth'); sandbox.stub(client, 'start').rejects(cause); - const disconnected = sandbox.spy(); - client.on('disconnected', disconnected); + const [onClose] = client.listeners('close'); - client.emit('close'); - await sleep(10); - - sinon.assert.calledOnceWithExactly(disconnected, cause); + await assert.rejects(async () => onClose(), cause); }); it('should not open a connection when disconnect() wins the race with a reconnect', async () => { @@ -643,8 +628,8 @@ describe('SocketModeClient', () => { await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); - it('should not log an error when disconnect() stops a reconnect during the WebSocket handshake', async () => { - const { client, error } = clientWithLogger(); + it('should stop a reconnect during the WebSocket handshake without an unhandled rejection', async () => { + const { client } = clientWithLogger(); holdHandshake(client); const disconnected = sandbox.spy(); client.on('disconnected', disconnected); @@ -654,7 +639,6 @@ describe('SocketModeClient', () => { await client.disconnect(); await sleep(10); - sinon.assert.neverCalledWithMatch(error, 'Failed to reconnect'); sinon.assert.notCalled(unhandledRejection); sinon.assert.calledOnce(disconnected); }); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index ef94b3201..61d559ae3 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -170,8 +170,7 @@ export class SocketModeClient extends EventEmitter { await this.delayReconnectAttempt(this.start); } catch (error) { if (!(error instanceof SMConnectAbortedError)) { - this.logger.error(`Failed to reconnect the Socket Mode client (error: ${error})`); - this.emit(State.Disconnected, error); + throw error; } } } else { From f17fd06c1d8f33c9bc93da178ee01da797ed4b8c Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:47:52 -0500 Subject: [PATCH 14/29] refactor(socket-mode): emit close with the closed SlackWebSocket The close handler now ignores a close from any connection other than the current one, by identity, instead of asking whether the current one is still active. Same outcome for the stale-close case from #2709, and it lets the next commits tell connections apart. Co-Authored-By: Claude --- .../socket-mode/src/SlackWebSocket.test.ts | 18 ++++++++++++++++++ packages/socket-mode/src/SlackWebSocket.ts | 2 +- .../socket-mode/src/SocketModeClient.test.ts | 14 +++++++------- packages/socket-mode/src/SocketModeClient.ts | 4 ++-- 4 files changed, 28 insertions(+), 10 deletions(-) diff --git a/packages/socket-mode/src/SlackWebSocket.test.ts b/packages/socket-mode/src/SlackWebSocket.test.ts index 92d18e77c..fb620fd62 100644 --- a/packages/socket-mode/src/SlackWebSocket.test.ts +++ b/packages/socket-mode/src/SlackWebSocket.test.ts @@ -358,6 +358,24 @@ describe('SlackWebSocket', () => { }); }); + describe('close notification', () => { + it('should emit "close" with the closed SlackWebSocket, so the client can tell connections apart', () => { + const client = new EventEmitter(); + const closed = sandbox.spy(); + client.on('close', closed); + const sws = new SlackWebSocket({ + url: 'ws://127.0.0.1/', + client, + clientPingTimeoutMS: 1, + serverPingTimeoutMS: 1, + }); + + sws.disconnect(); + + sinon.assert.calledOnceWithExactly(closed, sws); + }); + }); + describe('buildDefaultDispatcher() connect hook', () => { type ConnectCb = (err: Error | null, socket: unknown) => void; type ConnectFn = (opts: unknown, cb: ConnectCb) => void; diff --git a/packages/socket-mode/src/SlackWebSocket.ts b/packages/socket-mode/src/SlackWebSocket.ts index a8b01cbf9..0544f87be 100644 --- a/packages/socket-mode/src/SlackWebSocket.ts +++ b/packages/socket-mode/src/SlackWebSocket.ts @@ -296,7 +296,7 @@ export class SlackWebSocket { clearTimeout(this.closeHandshakeTimeout); // Emit event back to client letting it know connection has closed (in case it needs to reconnect if // reconnecting is enabled) - this.options.client.emit('close'); + this.options.client.emit('close', this); } /** diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index d5d4ba1f5..945183436 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -494,7 +494,7 @@ describe('SocketModeClient', () => { const startStub = sandbox.stub(client, 'start').resolves(undefined as never); const clock = sandbox.useFakeTimers(); - client.emit('close'); + client.emit('close', {} as SlackWebSocket); clock.tick(1_000_000); sinon.assert.notCalled(startStub); @@ -505,8 +505,8 @@ describe('SocketModeClient', () => { const startStub = sandbox.stub(client, 'start').resolves(undefined as never); const clock = sandbox.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); - client.emit('close'); - client.emit('close'); + client.emit('close', client.websocket); + client.emit('close', client.websocket); await clock.tickAsync(1_000_000); sinon.assert.calledOnce(startStub); @@ -578,7 +578,7 @@ describe('SocketModeClient', () => { const { client, error } = clientWithLogger(); const releaseURL = holdWSSURL(client); - client.emit('close'); + client.emit('close', client.websocket); await sleep(10); await client.disconnect(); releaseURL('ws://127.0.0.1:1/'); @@ -594,10 +594,10 @@ describe('SocketModeClient', () => { const startStub = sandbox.stub(client, 'start'); client.websocket = { isActive: () => false, - disconnect: () => client.emit('close'), + disconnect: () => client.emit('close', client.websocket), } as unknown as SlackWebSocket; - client.emit('close'); + client.emit('close', client.websocket); await sleep(10); await client.disconnect(); @@ -634,7 +634,7 @@ describe('SocketModeClient', () => { const disconnected = sandbox.spy(); client.on('disconnected', disconnected); - client.emit('close'); + client.emit('close', client.websocket); await sleep(10); await client.disconnect(); await sleep(10); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 61d559ae3..88410104c 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -161,9 +161,9 @@ export class SocketModeClient extends EventEmitter { this.on('error', (err) => { this.logger.error(`WebSocket error! ${err}`); }); - this.on('close', async () => { + this.on('close', async (socket: SlackWebSocket) => { // Underlying WebSocket connection was closed, possibly reconnect. - if (this.websocket?.isActive()) return; + if (socket !== this.websocket) return; if (this.reconnectDelay) return; if (!this.shuttingDown && this.autoReconnectEnabled) { try { From 05e173b395141227ee4b004a8f653a04b50aad8b Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:49:31 -0500 Subject: [PATCH 15/29] fix(socket-mode): skip a reconnect while one is waiting or fetching its URL A count of connects in flight covers the backoff wait and the apps.connections.open fetch, and drops once the new socket is assigned, so a failed handshake still reconnects through the close handler as before. A close during start()'s URL fetch no longer schedules a second connection. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 93 +++++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 35 ++++--- 2 files changed, 116 insertions(+), 12 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 945183436..422a823c3 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -16,6 +16,82 @@ describe('SocketModeClient', () => { afterEach(() => { sandbox.restore(); }); + + const CONNECTING = 0; + const OPEN = 1; + + class FakeSlackWebSocket { + static instances: FakeSlackWebSocket[] = []; + readyState: number | undefined = CONNECTING; + sent: string[] = []; + disconnectCalls = 0; + private client: { emit: (event: string, ...args: unknown[]) => boolean }; + constructor({ client }: { client: { emit: (event: string, ...args: unknown[]) => boolean } }) { + this.client = client; + FakeSlackWebSocket.instances.push(this); + } + connect() {} + isActive() { + return this.readyState === OPEN; + } + open() { + this.readyState = OPEN; + return this; + } + receive(message: Record) { + this.client.emit('ws_message', JSON.stringify(message), false, this); + } + hello() { + this.receive({ type: 'hello' }); + } + drop() { + this.readyState = undefined; + this.client.emit('close', this); + } + disconnect() { + this.disconnectCalls += 1; + this.drop(); + } + send(data: string, cb: (err: Error | undefined) => void) { + this.sent.push(data); + cb(undefined); + } + } + + const sockets = FakeSlackWebSocket.instances; + + function createClient(options: { clientPingTimeout?: number; autoReconnectEnabled?: boolean } = {}) { + sockets.length = 0; + const ProxiedSocketModeClient: typeof SocketModeClient = proxyquire('./SocketModeClient', { + './SlackWebSocket': { SlackWebSocket: FakeSlackWebSocket }, + }).SocketModeClient; + const logger = new ConsoleLogger(); + const error = sandbox.stub(logger, 'error'); + sandbox.stub(logger, 'debug'); + const client = new ProxiedSocketModeClient({ appToken: 'xapp-', clientPingTimeout: 60_000, logger, ...options }); + const urls: Array> = []; + const fetches = sandbox + .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') + .callsFake(() => urls.shift() ?? Promise.resolve('wss://fake')); + const holdNextURL = () => { + let release: () => void = () => {}; + urls.push(new Promise((resolve) => (release = () => resolve('wss://fake')))); + return () => release(); + }; + const failNextURL = (cause: Error) => { + urls.push(Promise.reject(cause)); + }; + client.on('interactive', ({ ack }) => ack()); + return { client, error, fetches, holdNextURL, failNextURL }; + } + + async function connect(client: SocketModeClient) { + const started = client.start(); + await sleep(0); + sockets[sockets.length - 1].open().hello(); + await started; + return sockets[sockets.length - 1]; + } describe('constructor', () => { let logFactory: sinon.SinonStub; beforeEach(() => { @@ -605,6 +681,23 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(unhandledRejection); }); + it('should not schedule a reconnect while start() is fetching its URL', async () => { + const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); + const releaseURL = holdNextURL(); + + const restarted = client.start(); + old.drop(); + await sleep(10); + releaseURL(); + await sleep(0); + sockets[1].open().hello(); + await restarted; + await sleep(10); + + assert.strictEqual(sockets.length, 2); + }); + it('should reject start() when disconnect() is called while it is connecting', async () => { const { client } = clientWithLogger(); const releaseURL = holdWSSURL(client); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 88410104c..91234b725 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -99,6 +99,8 @@ export class SocketModeClient extends EventEmitter { private customLoggerProvided = false; + private connectsInFlight = 0; + /** * Sentinel tracking if user invoked `disconnect()`; for enforcing shutting down of client * even if `autoReconnectEnabled` is `true`. @@ -164,18 +166,18 @@ export class SocketModeClient extends EventEmitter { this.on('close', async (socket: SlackWebSocket) => { // Underlying WebSocket connection was closed, possibly reconnect. if (socket !== this.websocket) return; - if (this.reconnectDelay) return; - if (!this.shuttingDown && this.autoReconnectEnabled) { - try { - await this.delayReconnectAttempt(this.start); - } catch (error) { - if (!(error instanceof SMConnectAbortedError)) { - throw error; - } - } - } else { + if (this.shuttingDown || !this.autoReconnectEnabled) { // If reconnect is disabled or user explicitly called `disconnect()`, emit a disconnected state. this.emit(State.Disconnected); + return; + } + if (this.connectsInFlight > 0) return; + try { + await this.delayReconnectAttempt(this.start); + } catch (error) { + if (!(error instanceof SMConnectAbortedError)) { + throw error; + } } }); this.on('ws_message', this.onWebSocketMessage.bind(this)); @@ -193,7 +195,7 @@ export class SocketModeClient extends EventEmitter { // python equiv: SocketModeClient.connect this.shuttingDown = false; this.logger.debug('Starting Socket Mode session ...'); - const url = await this.retrieveWSSURL(); + const url = await this.inFlight(this.retrieveWSSURL()); if (this.shuttingDown) { throw new SMConnectAbortedError(); } @@ -256,6 +258,15 @@ export class SocketModeClient extends EventEmitter { // PRIVATE/PROTECTED METHODS + private async inFlight(work: Promise): Promise { + this.connectsInFlight += 1; + try { + return await work; + } finally { + this.connectsInFlight -= 1; + } + } + /** * Initiates a reconnect, taking into account configurable delays and number of reconnect attempts and failures. * Accepts a callback to invoke after any calculated delays. @@ -268,7 +279,7 @@ export class SocketModeClient extends EventEmitter { const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); this.reconnectDelay = new AbortController(); - await setTimeout(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {}); + await this.inFlight(setTimeout(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {})); this.reconnectDelay = undefined; if (this.shuttingDown) { this.logger.debug('Client shutting down, will not attempt reconnect.'); From 3b693b4f37c7731bee19911e4f710f6b6386a3a7 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:50:08 -0500 Subject: [PATCH 16/29] fix(socket-mode): check the session signal captured before each await disconnect() aborts the session's AbortController and start() opens a new one, so a wait or URL fetch from before the restart sees its own session was stopped instead of reading a flag the restart already reset. This fixes disconnect(); start() during the reconnect wait or its URL fetch, which opened a second live connection. The per-wait reconnectDelay controller is gone. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 38 ++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 44 +++++++++---------- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 422a823c3..085c05fa8 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -681,6 +681,44 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(unhandledRejection); }); + it('should open one connection when disconnect() and start() run during the reconnect wait', async () => { + const { client, fetches } = createClient({ clientPingTimeout: 20 }); + const old = await connect(client); + + old.drop(); + await client.disconnect(); + const restarted = client.start(); + await sleep(0); + sockets[1].open().hello(); + await restarted; + await sleep(50); + + assert.strictEqual(sockets.length, 2); + sinon.assert.calledTwice(fetches); + }); + + it('should drop a reconnect URL that arrives after disconnect() and start()', async () => { + const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); + const releaseURL = holdNextURL(); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + old.drop(); + await sleep(10); + await client.disconnect(); + const restarted = client.start(); + await sleep(0); + sockets[1].open().hello(); + await restarted; + releaseURL(); + await sleep(10); + + assert.strictEqual(sockets.length, 2); + assert.strictEqual(client.websocket, sockets[1]); + sinon.assert.calledOnce(disconnected); + }); + it('should not schedule a reconnect while start() is fetching its URL', async () => { const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); const old = await connect(client); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 91234b725..403c3bc31 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -101,16 +101,15 @@ export class SocketModeClient extends EventEmitter { private connectsInFlight = 0; + private lifecycle = new AbortController(); + /** * Sentinel tracking if user invoked `disconnect()`; for enforcing shutting down of client * even if `autoReconnectEnabled` is `true`. */ - private shuttingDown = false; - - /** - * Cancels the pending wait before an automatic reconnection attempt. - */ - private reconnectDelay: AbortController | undefined; + private get shuttingDown(): boolean { + return this.lifecycle.signal.aborted; + } public constructor( { @@ -173,7 +172,7 @@ export class SocketModeClient extends EventEmitter { } if (this.connectsInFlight > 0) return; try { - await this.delayReconnectAttempt(this.start); + await this.delayReconnectAttempt(() => this.start(), this.lifecycle.signal); } catch (error) { if (!(error instanceof SMConnectAbortedError)) { throw error; @@ -193,10 +192,13 @@ export class SocketModeClient extends EventEmitter { */ public async start(): Promise { // python equiv: SocketModeClient.connect - this.shuttingDown = false; - this.logger.debug('Starting Socket Mode session ...'); - const url = await this.inFlight(this.retrieveWSSURL()); if (this.shuttingDown) { + this.lifecycle = new AbortController(); + } + const { signal } = this.lifecycle; + this.logger.debug('Starting Socket Mode session ...'); + const url = await this.inFlight(this.retrieveWSSURL(signal)); + if (signal.aborted) { throw new SMConnectAbortedError(); } // create a socket connection using SlackWebSocket @@ -225,7 +227,7 @@ export class SocketModeClient extends EventEmitter { }; disconnectedCallback = (err) => { this.removeListener(State.Connected, connectedCallback); - reject(this.shuttingDown ? new SMConnectAbortedError() : err); + reject(signal.aborted ? new SMConnectAbortedError() : err); }; this.once(State.Connected, connectedCallback); this.once(State.Disconnected, disconnectedCallback); @@ -239,9 +241,7 @@ export class SocketModeClient extends EventEmitter { * unless you call start() again later. */ public disconnect(): Promise { - this.shuttingDown = true; - this.reconnectDelay?.abort(); - this.reconnectDelay = undefined; + this.lifecycle.abort(); this.logger.debug('Manually disconnecting this Socket Mode client'); this.emit(State.Disconnecting); return new Promise((resolve, _reject) => { @@ -271,29 +271,27 @@ export class SocketModeClient extends EventEmitter { * Initiates a reconnect, taking into account configurable delays and number of reconnect attempts and failures. * Accepts a callback to invoke after any calculated delays. */ - private async delayReconnectAttempt(cb: () => Promise): Promise { - if (this.shuttingDown) { + private async delayReconnectAttempt(cb: () => Promise, signal: AbortSignal): Promise { + if (signal.aborted) { throw new SMConnectAbortedError(); } this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - this.reconnectDelay = new AbortController(); - await this.inFlight(setTimeout(msBeforeRetry, undefined, { signal: this.reconnectDelay.signal }).catch(() => {})); - this.reconnectDelay = undefined; - if (this.shuttingDown) { + await this.inFlight(setTimeout(msBeforeRetry, undefined, { signal }).catch(() => {})); + if (signal.aborted) { this.logger.debug('Client shutting down, will not attempt reconnect.'); throw new SMConnectAbortedError(); } this.logger.debug('Continuing with reconnect...'); this.emit(State.Reconnecting); - return cb.apply(this); + return cb(); } /** * Retrieves a new WebSocket URL to connect to. */ - private async retrieveWSSURL(): Promise { + private async retrieveWSSURL(signal: AbortSignal): Promise { // python equiv: BaseSocketModeClient.issue_new_wss_url try { this.logger.debug('Going to retrieve a new WSS URL ...'); @@ -322,7 +320,7 @@ export class SocketModeClient extends EventEmitter { isRecoverable = false; } if (this.autoReconnectEnabled && isRecoverable) { - return await this.delayReconnectAttempt(this.retrieveWSSURL); + return await this.delayReconnectAttempt(() => this.retrieveWSSURL(signal), signal); } throw error; } From 931a3cc0ddb7f06a08050bb02812292e70d275a2 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:50:56 -0500 Subject: [PATCH 17/29] test(socket-mode): drive the fails-for-good reconnect through the real start() The test no longer stubs start(): a reconnect whose URL fetch fails for good makes the close handler reject with that cause. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 085c05fa8..8d6a96a7c 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -69,17 +69,18 @@ describe('SocketModeClient', () => { const error = sandbox.stub(logger, 'error'); sandbox.stub(logger, 'debug'); const client = new ProxiedSocketModeClient({ appToken: 'xapp-', clientPingTimeout: 60_000, logger, ...options }); - const urls: Array> = []; + const urls: Array<() => Promise> = []; const fetches = sandbox .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') - .callsFake(() => urls.shift() ?? Promise.resolve('wss://fake')); + .callsFake(() => urls.shift()?.() ?? Promise.resolve('wss://fake')); const holdNextURL = () => { let release: () => void = () => {}; - urls.push(new Promise((resolve) => (release = () => resolve('wss://fake')))); + const held = new Promise((resolve) => (release = () => resolve('wss://fake'))); + urls.push(() => held); return () => release(); }; const failNextURL = (cause: Error) => { - urls.push(Promise.reject(cause)); + urls.push(() => Promise.reject(cause)); }; client.on('interactive', ({ ack }) => ack()); return { client, error, fetches, holdNextURL, failNextURL }; @@ -642,12 +643,15 @@ describe('SocketModeClient', () => { } it('should reject with the cause when a reconnect fails for good', async () => { - const { client } = clientWithLogger(); + const { client, failNextURL } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); const cause = new Error('invalid_auth'); - sandbox.stub(client, 'start').rejects(cause); + failNextURL(cause); const [onClose] = client.listeners('close'); - await assert.rejects(async () => onClose(), cause); + old.readyState = undefined; + + await assert.rejects(async () => onClose(old), cause); }); it('should not open a connection when disconnect() wins the race with a reconnect', async () => { From 380f13813d3bfa90ac4a21dc28747b2128c9d3ea Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:58:40 -0500 Subject: [PATCH 18/29] test(socket-mode): cover a restart during the reconnect wait end to end Against the mock servers, disconnect() and start() during the reconnect wait leave one connection open. The 409 test no longer swallows unhandled rejections: a reconnect stopped by disconnect() now settles quietly. Co-Authored-By: Claude --- .../test/integrations/integration.test.js | 36 ++++++++++++------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/packages/socket-mode/test/integrations/integration.test.js b/packages/socket-mode/test/integrations/integration.test.js index 6724da519..e80f6cc6f 100644 --- a/packages/socket-mode/test/integrations/integration.test.js +++ b/packages/socket-mode/test/integrations/integration.test.js @@ -97,6 +97,28 @@ describe('Integration tests with a WebSocket server', { timeout: 30000 }, () => await client.disconnect(); }); }); + describe('restarting during a reconnect (issue #2656)', () => { + it('opens one connection when disconnect() and start() run during the reconnect wait', async () => { + client = new SocketModeClient({ + appToken: 'whatever', + logLevel: LogLevel.ERROR, + clientOptions: { + slackApiUrl: `http://localhost:${HTTP_PORT}/`, + }, + clientPingTimeout: 100, + }); + await client.start(); + + exposed_ws_connection.terminate(); + await sleep(20); + await client.disconnect(); + await client.start(); + await sleep(300); + + assert.strictEqual(wss.clients.size, 1); + await client.disconnect(); + }); + }); describe('`apps.connections.open` API failure modes', () => { beforeEach(() => { client = new SocketModeClient({ @@ -177,15 +199,8 @@ describe('Integration tests with a WebSocket server', { timeout: 30000 }, () => assert.strictEqual(debugLoggerSpy.calledWith(sinon.match('Unable to parse an incoming WebSocket message')), true); await client.disconnect(); }); - it('should maintain one serial reconnection attempt if WSS server sends unexpected HTTP response during handshake, like a 409', async (t) => { + it('should maintain one serial reconnection attempt if WSS server sends unexpected HTTP response during handshake, like a 409', async () => { // test for https://github.com/slackapi/node-slack-sdk/issues/2094 - // SocketModeClient's internal reconnection loop creates promises that reject - // with `undefined` after disconnect(). node:test detects these as unhandled - // rejections (mocha did not). Mock process.emit to swallow them during cleanup. - const originalEmit = process.emit.bind(process); - t.after(() => { - process.emit = originalEmit; - }); // override socket mode client instance with lower client ping timeout, which controls reconnection rate client = new SocketModeClient({ appToken: 'whatever', @@ -238,11 +253,6 @@ describe('Integration tests with a WebSocket server', { timeout: 30000 }, () => else res(); }); }); - // Swallow unhandled rejections from internal reconnection cleanup - process.emit = (event, ...args) => { - if (event === 'unhandledRejection') return true; - return originalEmit(event, ...args); - }; // Allow event loop to drain any pending async activity from reconnection attempts await sleep(100); assert.strictEqual(retries, 2, 'unexpected number of times `close` event was raised during reconnection!'); From 0b579996a3da780277a16fe227934ba1d86f7d04 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 10:58:51 -0500 Subject: [PATCH 19/29] docs(socket-mode): note the restart fix in the changeset Co-Authored-By: Claude --- .changeset/socket-mode-reconnect-rejections.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.changeset/socket-mode-reconnect-rejections.md b/.changeset/socket-mode-reconnect-rejections.md index 66cbbac5d..115c253ac 100644 --- a/.changeset/socket-mode-reconnect-rejections.md +++ b/.changeset/socket-mode-reconnect-rejections.md @@ -5,3 +5,5 @@ Fix an unhandled promise rejection of `undefined` that could crash the process when `disconnect()` raced a pending automatic reconnect ([#2656](https://github.com/slackapi/node-slack-sdk/issues/2656)). A reconnect that fails for good still rejects as before, with its cause. Also, `disconnect()` called before `start()` finishes connecting (while fetching the WebSocket URL, waiting to retry it, or during the WebSocket handshake) no longer leaves a connection opening afterwards: `start()` rejects with the new `SMConnectAbortedError` instead of hanging or rejecting with `undefined`. + +Calling `start()` right after `disconnect()`, while a reconnect is waiting or fetching its URL, now opens one connection instead of two. From 011dc33b5db0fa15839aa0c281c60acb801f0162 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 11:44:09 -0500 Subject: [PATCH 20/29] refactor(socket-mode): track pending connects in a set Each wait or URL fetch adds its own promise and removes exactly that one when it settles, so the busy check reads as "is any connect pending" and a holder can't release another's slot. Same behavior as the count. Co-Authored-By: Claude --- packages/socket-mode/src/SocketModeClient.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 403c3bc31..b726a7cf9 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -99,7 +99,7 @@ export class SocketModeClient extends EventEmitter { private customLoggerProvided = false; - private connectsInFlight = 0; + private pendingConnects = new Set>(); private lifecycle = new AbortController(); @@ -170,7 +170,7 @@ export class SocketModeClient extends EventEmitter { this.emit(State.Disconnected); return; } - if (this.connectsInFlight > 0) return; + if (this.pendingConnects.size > 0) return; try { await this.delayReconnectAttempt(() => this.start(), this.lifecycle.signal); } catch (error) { @@ -197,7 +197,7 @@ export class SocketModeClient extends EventEmitter { } const { signal } = this.lifecycle; this.logger.debug('Starting Socket Mode session ...'); - const url = await this.inFlight(this.retrieveWSSURL(signal)); + const url = await this.whileConnecting(this.retrieveWSSURL(signal)); if (signal.aborted) { throw new SMConnectAbortedError(); } @@ -258,12 +258,12 @@ export class SocketModeClient extends EventEmitter { // PRIVATE/PROTECTED METHODS - private async inFlight(work: Promise): Promise { - this.connectsInFlight += 1; + private async whileConnecting(work: Promise): Promise { + this.pendingConnects.add(work); try { return await work; } finally { - this.connectsInFlight -= 1; + this.pendingConnects.delete(work); } } @@ -278,7 +278,7 @@ export class SocketModeClient extends EventEmitter { this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - await this.inFlight(setTimeout(msBeforeRetry, undefined, { signal }).catch(() => {})); + await this.whileConnecting(setTimeout(msBeforeRetry, undefined, { signal }).catch(() => {})); if (signal.aborted) { this.logger.debug('Client shutting down, will not attempt reconnect.'); throw new SMConnectAbortedError(); From 56970650047d8ce07b470d8201426e56e577f778 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 11:45:30 -0500 Subject: [PATCH 21/29] refactor(socket-mode): catch only the aborted reconnect wait The wait uses try/catch instead of .catch(() => {}), and rethrows anything that isn't the abort. Co-Authored-By: Claude --- packages/socket-mode/src/SocketModeClient.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index b726a7cf9..e35514e6a 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -278,7 +278,13 @@ export class SocketModeClient extends EventEmitter { this.numOfConsecutiveReconnectionFailures += 1; const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); - await this.whileConnecting(setTimeout(msBeforeRetry, undefined, { signal }).catch(() => {})); + try { + await this.whileConnecting(setTimeout(msBeforeRetry, undefined, { signal })); + } catch (error) { + if (!signal.aborted) { + throw error; + } + } if (signal.aborted) { this.logger.debug('Client shutting down, will not attempt reconnect.'); throw new SMConnectAbortedError(); From 29d62509f38be6554ba33b2c817d8912f2ef5c83 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 11:54:24 -0500 Subject: [PATCH 22/29] refactor(socket-mode): name the pending connect set connectOperations Matches python-slack-sdk's connect_operation_lock, the sibling SDK's guard for the same job. Co-Authored-By: Claude --- packages/socket-mode/src/SocketModeClient.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index e35514e6a..8b147bca2 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -99,7 +99,7 @@ export class SocketModeClient extends EventEmitter { private customLoggerProvided = false; - private pendingConnects = new Set>(); + private connectOperations = new Set>(); private lifecycle = new AbortController(); @@ -170,7 +170,7 @@ export class SocketModeClient extends EventEmitter { this.emit(State.Disconnected); return; } - if (this.pendingConnects.size > 0) return; + if (this.connectOperations.size > 0) return; try { await this.delayReconnectAttempt(() => this.start(), this.lifecycle.signal); } catch (error) { @@ -197,7 +197,7 @@ export class SocketModeClient extends EventEmitter { } const { signal } = this.lifecycle; this.logger.debug('Starting Socket Mode session ...'); - const url = await this.whileConnecting(this.retrieveWSSURL(signal)); + const url = await this.withConnectOperation(this.retrieveWSSURL(signal)); if (signal.aborted) { throw new SMConnectAbortedError(); } @@ -258,12 +258,12 @@ export class SocketModeClient extends EventEmitter { // PRIVATE/PROTECTED METHODS - private async whileConnecting(work: Promise): Promise { - this.pendingConnects.add(work); + private async withConnectOperation(work: Promise): Promise { + this.connectOperations.add(work); try { return await work; } finally { - this.pendingConnects.delete(work); + this.connectOperations.delete(work); } } @@ -279,7 +279,7 @@ export class SocketModeClient extends EventEmitter { const msBeforeRetry = this.clientPingTimeoutMS * this.numOfConsecutiveReconnectionFailures; this.logger.debug(`Before trying to reconnect, this client will wait for ${msBeforeRetry} milliseconds`); try { - await this.whileConnecting(setTimeout(msBeforeRetry, undefined, { signal })); + await this.withConnectOperation(setTimeout(msBeforeRetry, undefined, { signal })); } catch (error) { if (!signal.aborted) { throw error; From 41e1339f6c0330ebdd91a3abf3a54dd74fdfe169 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 14:53:11 -0500 Subject: [PATCH 23/29] test(socket-mode): map coverage to TypeScript source lines Without --enable-source-maps the coverage report gives line numbers of the compiled output, so codecov's patch check reads the wrong lines. Co-Authored-By: Claude --- packages/socket-mode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/socket-mode/package.json b/packages/socket-mode/package.json index f3481cd53..5d5624495 100644 --- a/packages/socket-mode/package.json +++ b/packages/socket-mode/package.json @@ -44,7 +44,7 @@ "docs": "npx typedoc --plugin typedoc-plugin-markdown", "prepack": "npm run build", "test": "npm run test:unit && npm run test:integration", - "test:coverage": "npm run build && bash -c 'node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts test/integrations/*.test.js'", + "test:coverage": "npm run build && bash -c 'node --enable-source-maps --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts test/integrations/*.test.js'", "test:integration": "npm run build && bash -c 'node --import tsx --test test/integrations/*.test.js'", "test:types": "tsd", "test:unit": "npm run build && bash -c 'node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts'", From 0299c76c8d0fd12005a223be30a53d0fda48ef58 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 15:29:45 -0500 Subject: [PATCH 24/29] fix(socket-mode): forget an aborted session's pending connects on restart A URL fetch still in flight from a session that disconnect() aborted kept connectOperations non-empty, so after start() the close handler skipped every reconnect of the new session. The stale fetch throws on its own aborted signal before it can connect, so the new session starts with an empty set. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 16 ++++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 1 + 2 files changed, 17 insertions(+) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 8d6a96a7c..0a83c8bdc 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -701,6 +701,22 @@ describe('SocketModeClient', () => { sinon.assert.calledTwice(fetches); }); + it('should reconnect after a drop while an aborted session is still fetching its URL', async () => { + const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); + holdNextURL(); + client.start().catch(() => {}); + await client.disconnect(); + const restarted = client.start(); + await sleep(0); + sockets[0].open().hello(); + await restarted; + + sockets[0].drop(); + await sleep(20); + + assert.strictEqual(sockets.length, 2); + }); + it('should drop a reconnect URL that arrives after disconnect() and start()', async () => { const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); const old = await connect(client); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 8b147bca2..46de335ee 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -194,6 +194,7 @@ export class SocketModeClient extends EventEmitter { // python equiv: SocketModeClient.connect if (this.shuttingDown) { this.lifecycle = new AbortController(); + this.connectOperations = new Set(); } const { signal } = this.lifecycle; this.logger.debug('Starting Socket Mode session ...'); From 7aa5170cfc2648af8087606de4fc97c64fd7b5f3 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 15:30:31 -0500 Subject: [PATCH 25/29] test(socket-mode): hold reconnect URLs with the shared fake client The two tests that held the WSS URL now use createClient's holdNextURL and a real connection drop instead of a second URL stub and a close event for a socket that never existed. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 0a83c8bdc..1d46237e7 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -634,14 +634,6 @@ describe('SocketModeClient', () => { return (error: Error) => rejectURL(error); } - function holdWSSURL(client: SocketModeClient) { - let resolveURL: (url: string) => void = () => {}; - sandbox - .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') - .returns(new Promise((resolve) => (resolveURL = resolve))); - return (url: string) => resolveURL(url); - } - it('should reject with the cause when a reconnect fails for good', async () => { const { client, failNextURL } = createClient({ clientPingTimeout: 1 }); const old = await connect(client); @@ -655,16 +647,17 @@ describe('SocketModeClient', () => { }); it('should not open a connection when disconnect() wins the race with a reconnect', async () => { - const { client, error } = clientWithLogger(); - const releaseURL = holdWSSURL(client); + const { client, error, holdNextURL } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); + const releaseURL = holdNextURL(); - client.emit('close', client.websocket); + old.drop(); await sleep(10); await client.disconnect(); - releaseURL('ws://127.0.0.1:1/'); + releaseURL(); await sleep(10); - assert.strictEqual(client.websocket, undefined); + assert.strictEqual(sockets.length, 1); sinon.assert.notCalled(error); sinon.assert.notCalled(unhandledRejection); }); @@ -757,15 +750,15 @@ describe('SocketModeClient', () => { }); it('should reject start() when disconnect() is called while it is connecting', async () => { - const { client } = clientWithLogger(); - const releaseURL = holdWSSURL(client); + const { client, holdNextURL } = createClient(); + const releaseURL = holdNextURL(); const starting = client.start(); await client.disconnect(); - releaseURL('ws://127.0.0.1:1/'); + releaseURL(); await assert.rejects(starting, { name: 'SMConnectAbortedError' }); - assert.strictEqual(client.websocket, undefined); + assert.strictEqual(sockets.length, 0); }); it('should reject start() when disconnect() is called during the WebSocket handshake', async () => { From 1606941f2274b79ca6aee73630f63fdc9952b515 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 15:31:07 -0500 Subject: [PATCH 26/29] test(socket-mode): drive the handshake tests with the fake WebSocket SlackWebSocket's own tests already pin that disconnect() while CONNECTING emits close, so the client tests only need a socket that never says hello. The local TCP server that never upgraded, its socket bookkeeping, and the node:net import go away. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 31 +++++-------------- 1 file changed, 8 insertions(+), 23 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 1d46237e7..654a54ea4 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -1,5 +1,4 @@ import assert from 'node:assert/strict'; -import { type AddressInfo, createServer, type Server, type Socket } from 'node:net'; import { afterEach, beforeEach, describe, it } from 'node:test'; import { ConsoleLogger } from '@slack/logger'; import type { FetchFunction, WebClient } from '@slack/web-api'; @@ -592,19 +591,12 @@ describe('SocketModeClient', () => { describe('reconnect failures (issue #2656)', () => { let unhandledRejection: sinon.SinonSpy; - let neverUpgrades: Server; - let heldSockets: Socket[]; - beforeEach(async () => { + beforeEach(() => { unhandledRejection = sandbox.spy(); process.on('unhandledRejection', unhandledRejection); - heldSockets = []; - neverUpgrades = createServer((socket) => heldSockets.push(socket)); - await new Promise((resolve) => neverUpgrades.listen(0, '127.0.0.1', resolve)); }); - afterEach(async () => { + afterEach(() => { process.off('unhandledRejection', unhandledRejection); - for (const socket of heldSockets) socket.destroy(); - await new Promise((resolve) => neverUpgrades.close(resolve)); }); function clientWithLogger(clientPingTimeout = 1) { @@ -615,13 +607,6 @@ describe('SocketModeClient', () => { return { client, error }; } - function holdHandshake(client: SocketModeClient) { - const { port } = neverUpgrades.address() as AddressInfo; - sandbox - .stub(client as unknown as { retrieveWSSURL: () => Promise }, 'retrieveWSSURL') - .resolves(`ws://127.0.0.1:${port}/`); - } - function failWSSURL(client: SocketModeClient) { const { webClient } = client as unknown as { webClient: WebClient }; sandbox.stub(webClient.apps.connections, 'open').rejects(new Error('internal_error')); @@ -762,27 +747,27 @@ describe('SocketModeClient', () => { }); it('should reject start() when disconnect() is called during the WebSocket handshake', async () => { - const { client } = clientWithLogger(); - holdHandshake(client); + const { client } = createClient(); const starting = client.start(); - await sleep(10); + await sleep(0); await client.disconnect(); await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); it('should stop a reconnect during the WebSocket handshake without an unhandled rejection', async () => { - const { client } = clientWithLogger(); - holdHandshake(client); + const { client } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); const disconnected = sandbox.spy(); client.on('disconnected', disconnected); - client.emit('close', client.websocket); + old.drop(); await sleep(10); await client.disconnect(); await sleep(10); + assert.strictEqual(sockets.length, 2); sinon.assert.notCalled(unhandledRejection); sinon.assert.calledOnce(disconnected); }); From 74c7594cb1a5ab1033425410ee40ace3bda7675d Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 15:32:19 -0500 Subject: [PATCH 27/29] test(socket-mode): make the reconnect tests fail when the guard they name is gone - The waiting-reconnect test now asserts after the aborted wait settles, so it fails if the wait reconnects anyway. - The stale-close test is named for the identity check and ticks asynchronously, so it fails if a non-current close reconnects. - The multiple-close test closes a named current socket instead of an undefined one, and the fails-for-good test drops an unused readyState line. Co-Authored-By: Claude --- .../socket-mode/src/SocketModeClient.test.ts | 43 ++++++++----------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 654a54ea4..b1a2d4b78 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -564,14 +564,14 @@ describe('SocketModeClient', () => { }); describe("reconnection on 'close' (issue #2709)", () => { - it('should not reconnect on a stale close event while the current connection is still active', () => { + it('should not reconnect on a close event from a connection that is no longer current', async () => { const client = new SocketModeClient({ appToken: 'xapp-', logLevel: LogLevel.ERROR }); - client.websocket = { isActive: () => true } as unknown as SlackWebSocket; + client.websocket = {} as SlackWebSocket; const startStub = sandbox.stub(client, 'start').resolves(undefined as never); - const clock = sandbox.useFakeTimers(); + const clock = sandbox.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); client.emit('close', {} as SlackWebSocket); - clock.tick(1_000_000); + await clock.tickAsync(1_000_000); sinon.assert.notCalled(startStub); }); @@ -580,9 +580,11 @@ describe('SocketModeClient', () => { const client = new SocketModeClient({ appToken: 'xapp-', logLevel: LogLevel.ERROR }); const startStub = sandbox.stub(client, 'start').resolves(undefined as never); const clock = sandbox.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const current = {} as SlackWebSocket; + client.websocket = current; - client.emit('close', client.websocket); - client.emit('close', client.websocket); + client.emit('close', current); + client.emit('close', current); await clock.tickAsync(1_000_000); sinon.assert.calledOnce(startStub); @@ -599,12 +601,11 @@ describe('SocketModeClient', () => { process.off('unhandledRejection', unhandledRejection); }); - function clientWithLogger(clientPingTimeout = 1) { + function clientWithLogger() { const logger = new ConsoleLogger(); - const error = sandbox.stub(logger, 'error'); + sandbox.stub(logger, 'error'); sandbox.stub(logger, 'debug'); - const client = new SocketModeClient({ appToken: 'xapp-', clientPingTimeout, logger }); - return { client, error }; + return new SocketModeClient({ appToken: 'xapp-', clientPingTimeout: 60_000, logger }); } function failWSSURL(client: SocketModeClient) { @@ -626,8 +627,6 @@ describe('SocketModeClient', () => { failNextURL(cause); const [onClose] = client.listeners('close'); - old.readyState = undefined; - await assert.rejects(async () => onClose(old), cause); }); @@ -647,19 +646,15 @@ describe('SocketModeClient', () => { sinon.assert.notCalled(unhandledRejection); }); - it('should resolve disconnect() while a reconnect is waiting', { timeout: 2000 }, async () => { - const { client } = clientWithLogger(60_000); - const startStub = sandbox.stub(client, 'start'); - client.websocket = { - isActive: () => false, - disconnect: () => client.emit('close', client.websocket), - } as unknown as SlackWebSocket; + it('should not reconnect when disconnect() is called while a reconnect is waiting', async () => { + const { client, fetches } = createClient(); + const old = await connect(client); - client.emit('close', client.websocket); - await sleep(10); + old.drop(); await client.disconnect(); + await sleep(10); - sinon.assert.notCalled(startStub); + sinon.assert.calledOnce(fetches); sinon.assert.notCalled(unhandledRejection); }); @@ -773,7 +768,7 @@ describe('SocketModeClient', () => { }); it('should reject start() when disconnect() is called while waiting to retry the WSS URL', async () => { - const { client } = clientWithLogger(60_000); + const client = clientWithLogger(); failWSSURL(client); const starting = client.start(); @@ -784,7 +779,7 @@ describe('SocketModeClient', () => { }); it('should reject start() without waiting to retry when the WSS URL fails after disconnect()', async () => { - const { client } = clientWithLogger(60_000); + const client = clientWithLogger(); const failURL = holdThenFailWSSURL(client); const starting = client.start(); From dea9b452c8c15018c04107f54f14b65dd2cd92e5 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 9 Nov 2026 16:54:55 -0500 Subject: [PATCH 28/29] fix(socket-mode): open the replacement connection before closing the old one on refresh (#2821) Co-authored-by: hippi345 <13539685+hippi345@users.noreply.github.com> Co-authored-by: Claude --- .changeset/socket-mode-refresh-overlap.md | 7 + packages/socket-mode/README.md | 14 +- .../socket-mode/src/SlackWebSocket.test.ts | 30 ++ packages/socket-mode/src/SlackWebSocket.ts | 2 +- .../socket-mode/src/SocketModeClient.test.ts | 289 +++++++++++++++++- packages/socket-mode/src/SocketModeClient.ts | 67 +++- .../test/integrations/integration.test.js | 83 +++++ 7 files changed, 472 insertions(+), 20 deletions(-) create mode 100644 .changeset/socket-mode-refresh-overlap.md diff --git a/.changeset/socket-mode-refresh-overlap.md b/.changeset/socket-mode-refresh-overlap.md new file mode 100644 index 000000000..565a2a2eb --- /dev/null +++ b/.changeset/socket-mode-refresh-overlap.md @@ -0,0 +1,7 @@ +--- +"@slack/socket-mode": patch +--- + +Fix a 5 to 12 second gap without a connection each time Slack refreshes a Socket Mode connection ([#2767](https://github.com/slackapi/node-slack-sdk/issues/2767)). On a `disconnect` message the client now opens the replacement connection right away, without a reconnect backoff, and leaves the old connection open until Slack sends it a `disconnect` message too, so payloads Slack still sends on it during the switch are received instead of dropped. Each payload is acknowledged on the connection it arrived on. While the replacement is being opened, the current connection keeps serving, and overlapping `disconnect` messages open one replacement. A replacement that fails for good rejects with its cause, as a failed reconnect does. A `link_disabled` message still closes the connection first, since a replacement can't connect while Socket Mode is off. + +**Note:** during each refresh, a client now holds two connections for about 60 seconds, until Slack sends the old one its own `disconnect` (`refresh_requested`, about a minute after the `warning`). Both count toward Slack's limit of 10 open Socket Mode connections per app, so apps that run many instances at once should leave room for one extra connection per instance while they refresh. diff --git a/packages/socket-mode/README.md b/packages/socket-mode/README.md index 6463d578b..42bc71073 100644 --- a/packages/socket-mode/README.md +++ b/packages/socket-mode/README.md @@ -127,13 +127,13 @@ The client's connection to Slack has a lifecycle. This means the client can be s In the table below, the client's states are listed, which are also the names of the events you can use to observe the transition to that state. The table also includes descriptions for the states and arguments that a listener would receive. -| Event Name | Arguments | Description | -| --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `connecting` | | The client is in the process of connecting to the platform. | -| `connected` | | The client is connected to the platform and incoming events will start being emitted. | -| `disconnecting` | | The client is no longer connected to the platform and cleaning up its resources. It will soon transition to `disconnected`. | -| `reconnecting` | | The client is no longer connected to the platform and cleaning up its resources. It will soon transition to `connecting`. | -| `disconnected` | `(error)` | The client is not connected to the platform. This is a steady state - no attempt to connect is occurring. The `error` argument will be `undefined` when the client initiated the disconnect (normal). | +| Event Name | Arguments | Description | +| --------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `connecting` | | The client is in the process of connecting to the platform. | +| `connected` | | The client is connected to the platform and incoming events will start being emitted. | +| `disconnecting` | | The client is no longer connected to the platform and cleaning up its resources. It will soon transition to `disconnected`. | +| `reconnecting` | | The client is replacing its connection. On a Slack refresh, the current connection keeps serving after the new one is `connected`, until Slack sends it `disconnect`. It will soon transition to `connecting`. | +| `disconnected` | `(error)` | The client is not connected to the platform. This is a steady state - no attempt to connect is occurring. The `error` argument will be `undefined` when the client initiated the disconnect (normal). | The client also emits events that are part of its lifecycle, but aren't states. Instead, they represent specific moments that might be helpful to your app. The following table lists these events, their description, and includes the arguments that a listener would receive. diff --git a/packages/socket-mode/src/SlackWebSocket.test.ts b/packages/socket-mode/src/SlackWebSocket.test.ts index fb620fd62..ceae6a8c9 100644 --- a/packages/socket-mode/src/SlackWebSocket.test.ts +++ b/packages/socket-mode/src/SlackWebSocket.test.ts @@ -93,6 +93,36 @@ describe('SlackWebSocket', () => { ws.dispatchEvent(new ErrorEvent('error', { error: new Error('boom'), message: 'boom' })); sinon.assert.calledOnce(discStub); }); + + it('should emit "ws_message" with the receiving SlackWebSocket, so the client can tell connections apart', () => { + const ws = new WSMock(); + SlackWebSocket = proxyquire.load('./SlackWebSocket', { + undici: { + WebSocket: class Fake { + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: for test mocking purposes + return ws; + } + }, + CloseEvent, + ErrorEvent, + MessageEvent, + ping: () => {}, + }, + }).SlackWebSocket; + const client = new EventEmitter(); + const received = sandbox.spy(); + client.on('ws_message', received); + const sws = new SlackWebSocket({ + url: 'whatevs', + client, + clientPingTimeoutMS: 1, + serverPingTimeoutMS: 1, + }); + sws.connect(); + ws.dispatchEvent(new MessageEvent('message', { data: '{"type":"hello"}' })); + sinon.assert.calledOnceWithExactly(received, '{"type":"hello"}', false, sws); + }); }); describe('disconnect() with an unresponsive peer', () => { diff --git a/packages/socket-mode/src/SlackWebSocket.ts b/packages/socket-mode/src/SlackWebSocket.ts index 0544f87be..8e40452b2 100644 --- a/packages/socket-mode/src/SlackWebSocket.ts +++ b/packages/socket-mode/src/SlackWebSocket.ts @@ -179,7 +179,7 @@ export class SlackWebSocket { return; } const isBinary = typeof event.data !== 'string'; - this.options.client.emit('ws_message', event.data, isBinary); + this.options.client.emit('ws_message', event.data, isBinary, this); }; this.websocket.addEventListener('message', this.messageHandler); diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index b1a2d4b78..8588346d8 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -311,7 +311,7 @@ describe('SocketModeClient', () => { assert.strictEqual(args.type, 'events_api'); assert.deepEqual(args.body, body); await args.ack({}); - sinon.assert.calledOnceWithExactly(send, 'malformed', {}); + sinon.assert.calledOnceWithExactly(send, 'malformed', {}, undefined); } }); @@ -789,6 +789,293 @@ describe('SocketModeClient', () => { await assert.rejects(starting, { name: 'SMConnectAbortedError' }); }); }); + + describe('server-requested disconnect (issue #2767)', () => { + const refreshRequested = { type: 'disconnect', reason: 'refresh_requested' }; + const envelope = { type: 'interactive', envelope_id: 'e-1', payload: {} }; + + it('should open the replacement right away and leave the old connection open after it says hello', async () => { + const { client, error } = createClient(); + const old = await connect(client); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + old.receive(refreshRequested); + await sleep(0); + + assert.strictEqual(sockets.length, 2, 'the replacement should open without waiting for a backoff'); + assert.strictEqual(old.disconnectCalls, 0); + + sockets[1].open().hello(); + await sleep(10); + + assert.strictEqual(old.disconnectCalls, 0, 'Slack may still deliver on the old connection'); + assert.strictEqual(client.websocket, sockets[1]); + old.drop(); + await sleep(10); + assert.strictEqual(sockets.length, 2, "the old connection's close must not trigger another reconnect"); + sinon.assert.notCalled(disconnected); + sinon.assert.notCalled(error); + }); + + it('should acknowledge each envelope on the connection it arrived on', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive(refreshRequested); + await sleep(0); + old.receive(envelope); + sockets[1].open(); + old.receive(envelope); + await sleep(0); + + assert.strictEqual(old.sent.length, 2); + assert.strictEqual(sockets[1].sent.length, 0); + + sockets[1].hello(); + sockets[1].receive(envelope); + old.receive(envelope); + await sleep(0); + + assert.strictEqual(sockets[1].sent.length, 1); + assert.strictEqual(old.sent.length, 3); + }); + + it('should acknowledge on the current connection when the arrival connection has closed', async () => { + const { client } = createClient(); + const old = await connect(client); + const acks: Array<() => Promise> = []; + client.on('slash_commands', ({ ack }) => acks.push(ack)); + + old.receive(refreshRequested); + await sleep(0); + sockets[1].open().hello(); + old.receive({ type: 'slash_commands', envelope_id: 'e-2', payload: {} }); + old.drop(); + await acks[0](); + + assert.strictEqual(old.sent.length, 0); + assert.strictEqual(sockets[1].sent.length, 1); + }); + + it('should close the old connection at the next refresh or on disconnect()', async () => { + const { client } = createClient(); + const old = await connect(client); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + old.receive(refreshRequested); + await sleep(0); + sockets[1].open().hello(); + assert.strictEqual(old.disconnectCalls, 0); + sockets[1].receive(refreshRequested); + await sleep(0); + + assert.strictEqual(old.disconnectCalls, 1); + assert.strictEqual(sockets[1].disconnectCalls, 0); + + await client.disconnect(); + + assert.strictEqual(sockets[1].disconnectCalls, 1); + assert.strictEqual(sockets[2].disconnectCalls, 1); + sinon.assert.calledOnce(disconnected); + }); + + it('should not close an old connection again after Slack closed it', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive(refreshRequested); + await sleep(0); + sockets[1].open().hello(); + old.drop(); + await client.disconnect(); + + assert.strictEqual(old.disconnectCalls, 0); + }); + + it('should back off and keep the old connection serving when the replacement fails before hello', async () => { + const { client } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); + + old.receive(refreshRequested); + await sleep(0); + sockets[1].drop(); + await sleep(10); + + assert.strictEqual(sockets.length, 3, 'the failed replacement should be retried with the usual backoff'); + assert.strictEqual(old.disconnectCalls, 0); + old.receive(envelope); + await sleep(0); + assert.strictEqual(old.sent.length, 1); + + sockets[2].open().hello(); + await sleep(0); + + assert.strictEqual(old.disconnectCalls, 0); + assert.strictEqual(client.websocket, sockets[2]); + }); + + it('should open only the replacement when the old connection closes while its URL is fetched', async () => { + const { client, holdNextURL } = createClient({ clientPingTimeout: 1 }); + const old = await connect(client); + const releaseURL = holdNextURL(); + const events = { connected: sandbox.spy(), reconnecting: sandbox.spy() }; + for (const [name, spy] of Object.entries(events)) client.on(name, spy); + + old.receive(refreshRequested); + await sleep(0); + old.drop(); + await sleep(10); + releaseURL(); + await sleep(0); + sockets[1].open().hello(); + await sleep(10); + + assert.deepStrictEqual( + sockets.map((socket) => socket.isActive()), + [false, true], + ); + assert.strictEqual(client.websocket, sockets[1]); + sinon.assert.calledOnce(events.connected); + sinon.assert.calledOnce(events.reconnecting); + }); + + it('should open one replacement when disconnect messages arrive back to back', async () => { + const { client } = createClient(); + const old = await connect(client); + const reconnecting = sandbox.spy(); + client.on('reconnecting', reconnecting); + + old.receive({ type: 'disconnect', reason: 'warning' }); + old.receive(refreshRequested); + await sleep(0); + sockets[1].open().hello(); + await sleep(10); + + assert.strictEqual(sockets.length, 2); + assert.strictEqual(client.websocket, sockets[1]); + sinon.assert.calledOnce(reconnecting); + }); + + it('should close the retiring connection, not open another, on its disconnect message while the replacement handshakes', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive({ type: 'disconnect', reason: 'warning' }); + await sleep(0); + const replacement = sockets[1].open(); + old.receive(refreshRequested); + await sleep(0); + + assert.strictEqual(sockets.length, 2); + assert.strictEqual(old.disconnectCalls, 1); + + replacement.hello(); + replacement.receive(envelope); + await sleep(0); + + assert.strictEqual(replacement.disconnectCalls, 0); + assert.strictEqual(replacement.sent.length, 1); + assert.strictEqual(client.websocket, replacement); + }); + + it('should reject with the cause when the replacement fails for good', async () => { + const { client, failNextURL } = createClient(); + const old = await connect(client); + const cause = new Error('invalid_auth'); + failNextURL(cause); + const [onMessage] = client.listeners('ws_message'); + + await assert.rejects(async () => onMessage(JSON.stringify(refreshRequested), false, old), cause); + }); + + it('should close a replacement that never opened when start() replaces it', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive(refreshRequested); + await sleep(0); + const restarted = client.start(); + await sleep(0); + sockets[2].open().hello(); + await restarted; + + assert.strictEqual(sockets[1].disconnectCalls, 1); + assert.strictEqual(old.disconnectCalls, 0); + assert.strictEqual(client.websocket, sockets[2]); + }); + + it('should close both connections and emit disconnected once when disconnect() runs mid-refresh', async () => { + const { client, error } = createClient(); + const old = await connect(client); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + old.receive(refreshRequested); + await sleep(0); + await client.disconnect(); + await sleep(10); + + assert.strictEqual(old.disconnectCalls, 1); + assert.strictEqual(sockets[1].disconnectCalls, 1); + sinon.assert.calledOnce(disconnected); + sinon.assert.notCalled(error); + }); + + it('should close without reconnecting when auto-reconnect is disabled', async () => { + const { client } = createClient({ autoReconnectEnabled: false }); + const old = await connect(client); + const disconnected = sandbox.spy(); + client.on('disconnected', disconnected); + + old.receive(refreshRequested); + await sleep(10); + + assert.strictEqual(old.disconnectCalls, 1); + assert.strictEqual(sockets.length, 1); + sinon.assert.calledOnce(disconnected); + }); + + it('should close the connection instead of opening a replacement when the link is disabled', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive({ type: 'disconnect', reason: 'link_disabled' }); + await sleep(0); + + assert.strictEqual(sockets.length, 1); + assert.strictEqual(old.disconnectCalls, 1); + await client.disconnect(); + }); + + it('should ignore a disconnect message that arrives after disconnect()', async () => { + const { client } = createClient(); + const old = await connect(client); + + await client.disconnect(); + old.receive(refreshRequested); + await sleep(10); + + assert.strictEqual(sockets.length, 1); + }); + + it('should ignore a late disconnect message from a connection a later refresh closed', async () => { + const { client } = createClient(); + const old = await connect(client); + + old.receive(refreshRequested); + await sleep(0); + sockets[1].open().hello(); + sockets[1].receive(refreshRequested); + await sleep(0); + sockets[2].open().hello(); + old.receive(refreshRequested); + await sleep(10); + + assert.strictEqual(sockets.length, 3); + }); + }); }); async function sleep(ms: number): Promise { diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index 46de335ee..d28eb53c7 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -77,6 +77,8 @@ export class SocketModeClient extends EventEmitter { public websocket?: SlackWebSocket; + private retiringWebsocket?: SlackWebSocket; + /** * Enables ping-pong detailed logging if true */ @@ -164,6 +166,7 @@ export class SocketModeClient extends EventEmitter { }); this.on('close', async (socket: SlackWebSocket) => { // Underlying WebSocket connection was closed, possibly reconnect. + if (socket === this.retiringWebsocket) this.retiringWebsocket = undefined; if (socket !== this.websocket) return; if (this.shuttingDown || !this.autoReconnectEnabled) { // If reconnect is disabled or user explicitly called `disconnect()`, emit a disconnected state. @@ -202,6 +205,7 @@ export class SocketModeClient extends EventEmitter { if (signal.aborted) { throw new SMConnectAbortedError(); } + const previous = this.websocket; // create a socket connection using SlackWebSocket this.websocket = new SlackWebSocket({ url, @@ -215,6 +219,7 @@ export class SocketModeClient extends EventEmitter { serverPingTimeoutMS: this.serverPingTimeoutMS, pingPongLoggingEnabled: this.pingPongLoggingEnabled, }); + this.retire(previous); // Return a promise that resolves with the connection information return new Promise((resolve, reject) => { @@ -243,6 +248,7 @@ export class SocketModeClient extends EventEmitter { */ public disconnect(): Promise { this.lifecycle.abort(); + this.closeRetiringWebsocket(); this.logger.debug('Manually disconnecting this Socket Mode client'); this.emit(State.Disconnecting); return new Promise((resolve, _reject) => { @@ -259,6 +265,33 @@ export class SocketModeClient extends EventEmitter { // PRIVATE/PROTECTED METHODS + private retire(previous: SlackWebSocket | undefined): void { + if (previous?.isActive()) { + this.closeRetiringWebsocket(); + this.retiringWebsocket = previous; + } else if (previous?.readyState !== undefined) { + previous.disconnect(); + } + } + + private closeRetiringWebsocket(): void { + this.retiringWebsocket?.disconnect(); + this.retiringWebsocket = undefined; + } + + private async openReplacement(reason: string): Promise { + if (this.connectOperations.size > 0) return; + this.logger.debug(`Received "disconnect" (${reason}) message - opening a replacement connection.`); + this.emit(State.Reconnecting); + try { + await this.start(); + } catch (error) { + if (!(error instanceof SMConnectAbortedError)) { + throw error; + } + } + } + private async withConnectOperation(work: Promise): Promise { this.connectOperations.add(work); try { @@ -340,7 +373,11 @@ export class SocketModeClient extends EventEmitter { * - raising the State.Connected event (when Slack sends a type:hello message) * - disconnecting the underlying socket (when Slack sends a type:disconnect message) */ - protected async onWebSocketMessage(data: string | ArrayBuffer, isBinary: boolean): Promise { + protected async onWebSocketMessage( + data: string | ArrayBuffer, + isBinary: boolean, + socket?: SlackWebSocket, + ): Promise { if (isBinary) { this.logger.debug('Unexpected binary message received, ignoring.'); return; @@ -377,10 +414,17 @@ export class SocketModeClient extends EventEmitter { // Slack is recycling the pod handling the connection (or otherwise requires the client to reconnect) if (event.type === 'disconnect') { - this.logger.debug( - `Received "${event.type}" (${event.reason}) message - disconnecting.${this.autoReconnectEnabled ? ' Will reconnect.' : ''}`, - ); - this.websocket?.disconnect(); + if (socket && socket === this.retiringWebsocket) { + this.closeRetiringWebsocket(); + return; + } + if (socket && socket !== this.websocket) return; + if (this.autoReconnectEnabled && !this.shuttingDown && event.reason !== 'link_disabled') { + await this.openReplacement(event.reason); + } else { + this.logger.debug(`Received "${event.type}" (${event.reason}) message - disconnecting.`); + this.websocket?.disconnect(); + } return; } @@ -391,7 +435,7 @@ export class SocketModeClient extends EventEmitter { `Calling ack() - type: ${event.type}, envelope_id: ${event.envelope_id}, data: ${JSON.stringify(response)}`, ); } - await this.send(event.envelope_id, response); + await this.send(event.envelope_id, response, socket); }; // For events_api messages, expose the type of the event @@ -441,19 +485,20 @@ export class SocketModeClient extends EventEmitter { * @param id the envelope id * @param body the message body or string text */ - private send(id: string, body = {}): Promise { + private send(id: string, body = {}, socket?: SlackWebSocket): Promise { const _body = typeof body === 'string' ? { text: body } : body; const message = { envelope_id: id, payload: { ..._body } }; return new Promise((resolve, reject) => { - const wsState = this.websocket?.readyState; + const websocket = socket?.isActive() ? socket : this.websocket; + const wsState = websocket?.readyState; this.logger.debug( `send() method was called (WebSocket state: ${wsState ? WS_READY_STATES[wsState] : 'uninitialized'})`, ); - if (this.websocket === undefined) { + if (websocket === undefined) { this.logger.error('Failed to send a message as the client is not connected'); reject(new SMSendWhileDisconnectedError()); - } else if (!this.websocket.isActive()) { + } else if (!websocket.isActive()) { this.logger.error('Failed to send a message as the client has no active connection'); reject(new SMSendWhileNotReadyError()); } else { @@ -461,7 +506,7 @@ export class SocketModeClient extends EventEmitter { const flatMessage = JSON.stringify(message); this.logger.debug(`Sending a WebSocket message: ${flatMessage}`); - this.websocket.send(flatMessage, (error) => { + websocket.send(flatMessage, (error) => { if (error) { this.logger.error(`Failed to send a WebSocket message (error: ${error})`); return reject(new SMWebsocketError(error)); diff --git a/packages/socket-mode/test/integrations/integration.test.js b/packages/socket-mode/test/integrations/integration.test.js index e80f6cc6f..2f490977d 100644 --- a/packages/socket-mode/test/integrations/integration.test.js +++ b/packages/socket-mode/test/integrations/integration.test.js @@ -119,6 +119,89 @@ describe('Integration tests with a WebSocket server', { timeout: 30000 }, () => await client.disconnect(); }); }); + describe('overlapping refreshes (issue #2767)', () => { + beforeEach(() => { + client = new SocketModeClient({ + appToken: 'whatever', + logLevel: LogLevel.ERROR, + clientOptions: { + slackApiUrl: `http://localhost:${HTTP_PORT}/`, + }, + clientPingTimeout: 100, + }); + }); + it('opens only the replacement when the old connection closes while its URL is fetched', async () => { + await client.start(); + const old = exposed_ws_connection; + server.close(); + server = createServer((_req, res) => { + setTimeout(() => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ ok: true, url: `ws://localhost:${WSS_PORT}/` })); + }, 300); + }); + server.listen(HTTP_PORT); + let connections = 0; + const replaced = new Promise((resolve) => { + wss.on('connection', () => { + connections += 1; + resolve(); + }); + }); + + old.send(JSON.stringify({ type: 'disconnect', reason: 'refresh_requested' })); + await sleep(50); + old.terminate(); + await replaced; + await sleep(300); + + assert.strictEqual(connections, 1); + assert.strictEqual(wss.clients.size, 1); + await client.disconnect(); + }); + it('opens one replacement when refresh_requested arrives on the old connection before the new one says hello', async () => { + await client.start(); + const old = exposed_ws_connection; + let connections = 0; + wss.removeAllListeners('connection'); + wss.on('connection', (ws) => { + connections += 1; + exposed_ws_connection = ws; + setTimeout(() => ws.send(JSON.stringify({ type: 'hello' })), 300); + }); + + old.send(JSON.stringify({ type: 'disconnect', reason: 'warning' })); + await sleep(100); + old.send(JSON.stringify({ type: 'disconnect', reason: 'refresh_requested' })); + await sleep(500); + + assert.strictEqual(connections, 1); + assert.strictEqual(wss.clients.size, 1); + await client.disconnect(); + }); + it('receives and acknowledges an envelope sent on the old connection after the new one says hello', async () => { + await client.start(); + const old = exposed_ws_connection; + const acks = []; + old.on('message', (data) => acks.push(JSON.parse(data).envelope_id)); + const connected = new Promise((resolve) => client.once('connected', resolve)); + const received = new Promise((resolve) => + client.once('interactive', async ({ ack, envelope_id }) => { + await ack(); + resolve(envelope_id); + }), + ); + + old.send(JSON.stringify({ type: 'disconnect', reason: 'warning' })); + await connected; + old.send(JSON.stringify({ type: 'interactive', envelope_id: 'e-old', payload: {} })); + + assert.strictEqual(await Promise.race([received, sleep(500)]), 'e-old'); + await sleep(50); + assert.deepStrictEqual(acks, ['e-old']); + await client.disconnect(); + }); + }); describe('`apps.connections.open` API failure modes', () => { beforeEach(() => { client = new SocketModeClient({ From e1ce02bfb0d9e6249ba2338be1e0438c5e327506 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Tue, 10 Nov 2026 10:41:46 -0500 Subject: [PATCH 29/29] fix(socket-mode): back off on disconnect reasons other than a refresh Only `warning` and `refresh_requested` open a replacement connection right away. Any other reason, like `too_many_websockets`, closes the connection and reconnects after the usual delay, as on `main`, so an unexpected reason can't loop fast on `apps.connections.open`. Co-Authored-By: Claude --- .changeset/socket-mode-refresh-overlap.md | 2 +- packages/socket-mode/src/SocketModeClient.test.ts | 14 ++++++++++++++ packages/socket-mode/src/SocketModeClient.ts | 3 ++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.changeset/socket-mode-refresh-overlap.md b/.changeset/socket-mode-refresh-overlap.md index 565a2a2eb..6909ad4ca 100644 --- a/.changeset/socket-mode-refresh-overlap.md +++ b/.changeset/socket-mode-refresh-overlap.md @@ -2,6 +2,6 @@ "@slack/socket-mode": patch --- -Fix a 5 to 12 second gap without a connection each time Slack refreshes a Socket Mode connection ([#2767](https://github.com/slackapi/node-slack-sdk/issues/2767)). On a `disconnect` message the client now opens the replacement connection right away, without a reconnect backoff, and leaves the old connection open until Slack sends it a `disconnect` message too, so payloads Slack still sends on it during the switch are received instead of dropped. Each payload is acknowledged on the connection it arrived on. While the replacement is being opened, the current connection keeps serving, and overlapping `disconnect` messages open one replacement. A replacement that fails for good rejects with its cause, as a failed reconnect does. A `link_disabled` message still closes the connection first, since a replacement can't connect while Socket Mode is off. +Fix a 5 to 12 second gap without a connection each time Slack refreshes a Socket Mode connection ([#2767](https://github.com/slackapi/node-slack-sdk/issues/2767)). On a `disconnect` message with the `warning` or `refresh_requested` reason, the client now opens the replacement connection right away, without a reconnect backoff, and leaves the old connection open until Slack sends it a `disconnect` message too, so payloads Slack still sends on it during the switch are received instead of dropped. Each payload is acknowledged on the connection it arrived on. While the replacement is being opened, the current connection keeps serving, and overlapping `disconnect` messages open one replacement. A replacement that fails for good rejects with its cause, as a failed reconnect does. Any other reason, such as `link_disabled`, still closes the connection first and reconnects after the usual delay. **Note:** during each refresh, a client now holds two connections for about 60 seconds, until Slack sends the old one its own `disconnect` (`refresh_requested`, about a minute after the `warning`). Both count toward Slack's limit of 10 open Socket Mode connections per app, so apps that run many instances at once should leave room for one extra connection per instance while they refresh. diff --git a/packages/socket-mode/src/SocketModeClient.test.ts b/packages/socket-mode/src/SocketModeClient.test.ts index 8588346d8..6bdda9ab9 100644 --- a/packages/socket-mode/src/SocketModeClient.test.ts +++ b/packages/socket-mode/src/SocketModeClient.test.ts @@ -1049,6 +1049,20 @@ describe('SocketModeClient', () => { await client.disconnect(); }); + it('should close the connection and reconnect after the backoff on an unexpected reason', async () => { + const { client } = createClient({ clientPingTimeout: 20 }); + const old = await connect(client); + + old.receive({ type: 'disconnect', reason: 'too_many_websockets' }); + await sleep(0); + + assert.strictEqual(sockets.length, 1); + assert.strictEqual(old.disconnectCalls, 1); + await sleep(40); + assert.strictEqual(sockets.length, 2); + await client.disconnect(); + }); + it('should ignore a disconnect message that arrives after disconnect()', async () => { const { client } = createClient(); const old = await connect(client); diff --git a/packages/socket-mode/src/SocketModeClient.ts b/packages/socket-mode/src/SocketModeClient.ts index d28eb53c7..04ce1e5c5 100644 --- a/packages/socket-mode/src/SocketModeClient.ts +++ b/packages/socket-mode/src/SocketModeClient.ts @@ -419,7 +419,8 @@ export class SocketModeClient extends EventEmitter { return; } if (socket && socket !== this.websocket) return; - if (this.autoReconnectEnabled && !this.shuttingDown && event.reason !== 'link_disabled') { + const isRefresh = event.reason === 'warning' || event.reason === 'refresh_requested'; + if (this.autoReconnectEnabled && !this.shuttingDown && isRefresh) { await this.openReplacement(event.reason); } else { this.logger.debug(`Received "${event.type}" (${event.reason}) message - disconnecting.`);