Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(device-gateway): stop a hung handshake from parking the device client offline (#19021)

Arvin Xu95c8abd1df76
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index 53573695d35..429f6a712fb 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -4,6 +4,10 @@ import { GatewayClient } from './client';
// Flag to control mock WS behavior
let mockWsShouldThrow = false;
+// When set, the socket never opens β€” the real-world black-holed TLS handshake,
+// which raises no event at all rather than an error.
+let mockWsShouldHang = false;
+const mockWsInstances: { options?: unknown; url: string }[] = [];
// Mock ws module β€” must use dynamic import for EventEmitter to avoid hoisting issues
vi.mock('ws', async () => {
@@ -24,6 +28,11 @@ vi.mock('ws', async () => {
mockWsShouldThrow = false;
throw new Error('connection refused');
}
+ mockWsInstances.push(this);
+ if (mockWsShouldHang) {
+ this.readyState = 0; // CONNECTING, and it stays there
+ return;
+ }
// Simulate async open
setTimeout(() => this.emit('open'), 0);
}
@@ -49,6 +58,8 @@ describe('GatewayClient', () => {
beforeEach(() => {
vi.useFakeTimers();
+ mockWsShouldHang = false;
+ mockWsInstances.length = 0;
client = new GatewayClient({
autoReconnect: false,
deviceId: 'test-device-id',
@@ -184,12 +195,87 @@ describe('GatewayClient', () => {
c.connect();
const ws = (c as any).ws;
expect(ws.options).toEqual({
+ handshakeTimeout: 15_000,
headers: { 'User-Agent': 'LobeHub Desktop/1.2.3' },
});
c.disconnect();
});
});
+ describe('connect watchdog', () => {
+ const makeClient = (connectTimeoutMs = 15_000) =>
+ new GatewayClient({
+ autoReconnect: true,
+ connectTimeoutMs,
+ deviceId: 'test-device-id',
+ gatewayUrl: 'https://gateway.test.com',
+ serverUrl: 'https://app.test.com',
+ token: 'test-token',
+ tokenType: 'apiKey',
+ userId: 'test-user',
+ });
+
+ it('bounds the handshake inside ws itself', () => {
+ client.connect();
+
+ expect(mockWsInstances.at(-1)?.options).toMatchObject({ handshakeTimeout: 15_000 });
+ });
+
+ it('retries when the handshake hangs without raising an event', () => {
+ // A black-holed TLS handshake emits no open/error/close, so nothing ever
+ // called scheduleReconnect: the daemon reported `connecting` while the
+ // device sat offline for 15+ minutes, and the run silently fell through
+ // to the cloud sandbox.
+ mockWsShouldHang = true;
+ const hung = makeClient(1000);
+ hung.connect();
+
+ expect(hung.connectionStatus).toBe('connecting');
+ expect(mockWsInstances).toHaveLength(1);
+
+ vi.advanceTimersByTime(1000);
+ expect(hung.connectionStatus).toBe('reconnecting');
+
+ // ...and the backoff actually produces a fresh attempt.
+ mockWsShouldHang = false;
+ vi.advanceTimersByTime(1000);
+ expect(mockWsInstances.length).toBeGreaterThan(1);
+
+ hung.disconnect();
+ });
+
+ it('retries when the socket opens but auth never comes back', async () => {
+ // `startHeartbeat` only runs on auth_success, so a lost auth reply left
+ // the client parked in `authenticating` with no watchdog of any kind.
+ const stalled = makeClient(1000);
+ stalled.connect();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(stalled.connectionStatus).toBe('authenticating');
+
+ vi.advanceTimersByTime(1000);
+ expect(stalled.connectionStatus).toBe('reconnecting');
+
+ stalled.disconnect();
+ });
+
+ it('disarms once authenticated', async () => {
+ const connected = makeClient(1000);
+ connected.connect();
+ await vi.advanceTimersByTimeAsync(0);
+ mockWsInstances.at(-1);
+ connected['handleMessage'](JSON.stringify({ type: 'auth_success' }));
+ expect(connected.connectionStatus).toBe('connected');
+
+ const attemptsBefore = mockWsInstances.length;
+ vi.advanceTimersByTime(10_000);
+
+ expect(connected.connectionStatus).toBe('connected');
+ expect(mockWsInstances).toHaveLength(attemptsBefore);
+
+ connected.disconnect();
+ });
+ });
+
describe('message handling', () => {
let handler: (data: any) => void;
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 8c338b731d4..0f980d7883c 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -28,6 +28,13 @@ const HEARTBEAT_INTERVAL = 30_000; // 30s
const INITIAL_RECONNECT_DELAY = 1000; // 1s
const MAX_RECONNECT_DELAY = 30_000; // 30s
const MAX_MISSED_HEARTBEATS = 3; // Force reconnect after 3 missed acks
+/**
+ * Budget for the whole pre-connected window: TCP + TLS + HTTP upgrade AND the
+ * `auth_success` reply. Neither phase raises an event of its own when it simply
+ * hangs, so without a deadline the client waits on the OS TCP timeout β€” observed
+ * stalling a reconnect for 15+ minutes while the device sat offline.
+ */
+const CONNECT_TIMEOUT = 15_000; // 15s
// ─── Logger Interface ───
@@ -62,6 +69,11 @@ export interface GatewayClientOptions {
* replace its own previous socket should pass a persisted value.
*/
connectionId?: string;
+ /**
+ * How long to wait for a connection to become fully authenticated before
+ * abandoning it and retrying (default: 15s).
+ */
+ connectTimeoutMs?: number;
deviceId?: string;
gatewayUrl?: string;
logger?: GatewayClientLogger;
@@ -83,6 +95,7 @@ export class GatewayClient extends EventEmitter {
private ws: WebSocket | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private connectWatchdogTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelay = INITIAL_RECONNECT_DELAY;
private missedHeartbeats = 0;
private status: ConnectionStatus = 'disconnected';
@@ -99,6 +112,7 @@ export class GatewayClient extends EventEmitter {
private serverUrl?: string;
private logger: GatewayClientLogger;
private autoReconnect: boolean;
+ private connectTimeoutMs: number;
constructor(options: GatewayClientOptions) {
super();
@@ -114,6 +128,7 @@ export class GatewayClient extends EventEmitter {
this.workspaceId = options.workspaceId;
this.logger = options.logger || noopLogger;
this.autoReconnect = options.autoReconnect ?? true;
+ this.connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT;
}
// ─── Public API ───
@@ -227,7 +242,14 @@ export class GatewayClient extends EventEmitter {
const wsUrl = this.buildWsUrl();
this.logger.debug(`Connecting to: ${wsUrl}`);
- const wsOptions = this.userAgent ? { headers: { 'User-Agent': this.userAgent } } : undefined;
+ // `handshakeTimeout` bounds TCP+TLS+upgrade inside `ws` itself, which turns
+ // a black-holed handshake into a normal error/close pair. The watchdog
+ // below is the belt to that suspenders: it also covers the phase `ws`
+ // knows nothing about β€” an opened socket whose `auth_success` never lands.
+ const wsOptions = {
+ handshakeTimeout: this.connectTimeoutMs,
+ ...(this.userAgent ? { headers: { 'User-Agent': this.userAgent } } : {}),
+ };
const ws = new WebSocket(wsUrl, wsOptions);
ws.on('open', this.handleOpen);
@@ -236,6 +258,7 @@ export class GatewayClient extends EventEmitter {
ws.on('error', this.handleError);
this.ws = ws;
+ this.startConnectWatchdog();
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
this.logger.error('Failed to create WebSocket:', msg);
@@ -314,6 +337,7 @@ export class GatewayClient extends EventEmitter {
switch (message.type) {
case 'auth_success': {
this.logger.info('Authentication successful');
+ this.clearConnectWatchdog();
this.setStatus('connected');
this.startHeartbeat();
this.emit('connected');
@@ -377,6 +401,10 @@ export class GatewayClient extends EventEmitter {
private handleClose = (code: number, reason: Buffer) => {
this.logger.info(`WebSocket closed: code=${code} reason=${reason.toString()}`);
this.stopHeartbeat();
+ // `handshakeTimeout` closes the socket on its own, so the watchdog must be
+ // disarmed here or it would fire later and force a SECOND reconnect on top
+ // of the one this close already scheduled.
+ this.clearConnectWatchdog();
this.ws = null;
if (!this.intentionalDisconnect && this.autoReconnect) {
@@ -401,17 +429,7 @@ export class GatewayClient extends EventEmitter {
this.heartbeatTimer = setInterval(() => {
this.missedHeartbeats++;
if (this.missedHeartbeats > MAX_MISSED_HEARTBEATS) {
- this.logger.warn(`Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`);
- this.closeWebSocket();
- // Listeners are detached in closeWebSocket; handleClose won't run β€” drive reconnect here
- this.stopHeartbeat();
- if (this.autoReconnect) {
- this.setStatus('reconnecting');
- this.scheduleReconnect();
- } else {
- this.setStatus('disconnected');
- this.emit('disconnected');
- }
+ this.forceReconnect(`Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`);
return;
}
this.sendMessage({ type: 'heartbeat' });
@@ -425,6 +443,45 @@ export class GatewayClient extends EventEmitter {
}
}
+ // ─── Connect watchdog ───
+
+ private startConnectWatchdog() {
+ this.clearConnectWatchdog();
+ this.connectWatchdogTimer = setTimeout(() => {
+ this.connectWatchdogTimer = null;
+ this.forceReconnect(
+ `No authenticated connection within ${this.connectTimeoutMs}ms (status: ${this.status}), forcing reconnect`,
+ );
+ }, this.connectTimeoutMs);
+ }
+
+ private clearConnectWatchdog() {
+ if (this.connectWatchdogTimer) {
+ clearTimeout(this.connectWatchdogTimer);
+ this.connectWatchdogTimer = null;
+ }
+ }
+
+ /**
+ * Abandon the current socket and drive the retry ourselves. `closeWebSocket`
+ * detaches our listeners, so `handleClose` will NOT run β€” every forced path
+ * has to schedule the next attempt itself or the client goes quiet for good.
+ */
+ private forceReconnect(reason: string) {
+ this.logger.warn(reason);
+ this.closeWebSocket();
+ this.stopHeartbeat();
+ this.clearConnectWatchdog();
+
+ if (this.autoReconnect) {
+ this.setStatus('reconnecting');
+ this.scheduleReconnect();
+ } else {
+ this.setStatus('disconnected');
+ this.emit('disconnected');
+ }
+ }
+
// ─── Reconnection (exponential backoff) ───
private scheduleReconnect() {
@@ -506,6 +563,7 @@ export class GatewayClient extends EventEmitter {
private cleanup() {
this.stopHeartbeat();
this.clearReconnectTimer();
+ this.clearConnectWatchdog();
this.closeWebSocket();
}
}