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: cli gateway auto reconnect (#13418)

Arvin Xu2c2795e73a00
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 2e34b893f7c..2598e5ce8cb 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -173,7 +173,7 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
}
async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
- const auth = await resolveToken(options);
+ let auth = await resolveToken(options);
const settings = loadSettings();
const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;
@@ -295,19 +295,30 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
process.exit(1);
});
- // Handle auth expired
+ // Handle auth expired β€” refresh token and reconnect automatically
client.on('auth_expired', async () => {
if (auth.tokenType === 'apiKey') {
+ // API keys don't expire; ignore stale auth_expired signals
return;
}
- error('Authentication expired. Attempting to refresh...');
- const refreshed = await resolveToken({});
- if (refreshed) {
- info('Token refreshed. Please reconnect.');
- } else {
- error("Could not refresh token. Run 'lh login' to re-authenticate.");
+ info('Authentication expired. Attempting to refresh token...');
+
+ try {
+ const refreshed = await resolveToken({});
+ if (refreshed) {
+ info('Token refreshed successfully. Reconnecting...');
+ client.updateToken(refreshed.token);
+ // Update cached auth so subsequent refreshes use the latest token
+ auth = refreshed;
+ await client.reconnect();
+ return;
+ }
+ } catch {
+ // refresh failed β€” fall through
}
+
+ error("Could not refresh token. Run 'lh login' to re-authenticate.");
cleanup();
process.exit(1);
});
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index 3613507f7aa..b45e5e3727a 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -532,4 +532,145 @@ describe('GatewayClient', () => {
expect(ws.close).not.toHaveBeenCalled();
});
});
+
+ describe('updateToken', () => {
+ it('should update the internal token', () => {
+ expect((client as any).token).toBe('test-token');
+ client.updateToken('new-token');
+ expect((client as any).token).toBe('new-token');
+ });
+
+ it('should use the new token on next connect', async () => {
+ client.updateToken('refreshed-token');
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws = (client as any).ws;
+ expect(ws.send).toHaveBeenCalledWith(
+ expect.stringContaining('"token":"refreshed-token"'),
+ );
+ });
+ });
+
+ describe('reconnect', () => {
+ it('should close existing connection and reconnect', async () => {
+ client = new GatewayClient({
+ autoReconnect: false,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'old-token',
+ });
+
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const handler = (client as any).handleMessage;
+ handler(JSON.stringify({ type: 'auth_success' }));
+ expect(client.connectionStatus).toBe('connected');
+
+ // Update token and reconnect
+ client.updateToken('new-token');
+ await client.reconnect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(client.connectionStatus).toBe('authenticating');
+ const ws = (client as any).ws;
+ expect(ws.send).toHaveBeenCalledWith(
+ expect.stringContaining('"token":"new-token"'),
+ );
+ });
+
+ it('should reset reconnect delay', async () => {
+ const reconnectClient = new GatewayClient({
+ autoReconnect: true,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+
+ reconnectClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ // Force backoff delay up
+ const closeHandler = (reconnectClient as any).handleClose;
+ closeHandler(1000, Buffer.from(''));
+ closeHandler(1000, Buffer.from(''));
+ expect((reconnectClient as any).reconnectDelay).toBe(4000);
+
+ // reconnect() should reset
+ await reconnectClient.reconnect();
+ expect((reconnectClient as any).reconnectDelay).toBe(1000);
+
+ reconnectClient.disconnect();
+ });
+ });
+
+ describe('missed heartbeat ack detection', () => {
+ it('should force reconnect after exceeding missed heartbeat threshold', async () => {
+ const reconnectClient = new GatewayClient({
+ autoReconnect: true,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+ const reconnectingCb = vi.fn();
+ reconnectClient.on('reconnecting', reconnectingCb);
+
+ reconnectClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ // Authenticate
+ const handler = (reconnectClient as any).handleMessage;
+ handler(JSON.stringify({ type: 'auth_success' }));
+ expect(reconnectClient.connectionStatus).toBe('connected');
+
+ // Advance 4 heartbeat intervals without any ack (30s Γ— 4 = 120s)
+ // After 3 missed, the 4th tick triggers forced reconnect
+ await vi.advanceTimersByTimeAsync(30_000 * 4);
+
+ expect(reconnectClient.connectionStatus).toBe('reconnecting');
+ expect(reconnectingCb).toHaveBeenCalled();
+
+ reconnectClient.disconnect();
+ });
+
+ it('should reset missed counter on heartbeat_ack', async () => {
+ const reconnectClient = new GatewayClient({
+ autoReconnect: true,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+
+ reconnectClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const handler = (reconnectClient as any).handleMessage;
+ handler(JSON.stringify({ type: 'auth_success' }));
+
+ // 2 heartbeats without ack
+ await vi.advanceTimersByTimeAsync(30_000 * 2);
+ expect((reconnectClient as any).missedHeartbeats).toBe(2);
+
+ // Receive ack β€” counter resets
+ handler(JSON.stringify({ type: 'heartbeat_ack' }));
+ expect((reconnectClient as any).missedHeartbeats).toBe(0);
+
+ reconnectClient.disconnect();
+ });
+
+ it('should emit disconnected when autoReconnect is false and heartbeats missed', async () => {
+ const disconnectedCb = vi.fn();
+ // client has autoReconnect: false
+ client.on('disconnected', disconnectedCb);
+
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const handler = (client as any).handleMessage;
+ handler(JSON.stringify({ type: 'auth_success' }));
+
+ // Advance past threshold: 4 intervals
+ await vi.advanceTimersByTimeAsync(30_000 * 4);
+
+ expect(client.connectionStatus).toBe('disconnected');
+ expect(disconnectedCb).toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 19f8c1bad46..6293c4c899d 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -21,6 +21,7 @@ const DEFAULT_GATEWAY_URL = 'https://device-gateway.lobehub.com';
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
// ─── Logger Interface ───
@@ -55,6 +56,7 @@ export class GatewayClient extends EventEmitter {
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelay = INITIAL_RECONNECT_DELAY;
+ private missedHeartbeats = 0;
private status: ConnectionStatus = 'disconnected';
private intentionalDisconnect = false;
private deviceId: string;
@@ -102,6 +104,25 @@ export class GatewayClient extends EventEmitter {
return super.emit(event, ...args);
}
+ /**
+ * Update the auth token used for (re)connections.
+ * Call this after refreshing an expired JWT, then call `reconnect()`.
+ */
+ updateToken(token: string): void {
+ this.token = token;
+ }
+
+ /**
+ * Force a reconnect cycle: close the current WebSocket and establish a new connection.
+ * Useful after calling `updateToken()` with a fresh JWT.
+ */
+ async reconnect(): Promise<void> {
+ this.cleanup();
+ this.intentionalDisconnect = false;
+ this.reconnectDelay = INITIAL_RECONNECT_DELAY;
+ this.doConnect();
+ }
+
async connect(): Promise<void> {
if (this.status === 'connected' || this.status === 'connecting') {
return;
@@ -216,6 +237,7 @@ export class GatewayClient extends EventEmitter {
}
case 'heartbeat_ack': {
+ this.missedHeartbeats = 0;
this.emit('heartbeat_ack');
break;
}
@@ -268,7 +290,25 @@ export class GatewayClient extends EventEmitter {
private startHeartbeat() {
this.stopHeartbeat();
+ this.missedHeartbeats = 0;
this.heartbeatTimer = setInterval(() => {
+ this.missedHeartbeats++;
+ if (this.missedHeartbeats > MAX_MISSED_HEARTBEATS) {
+ this.logger.warn(
+ `Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`,
+ );
+ this.closeWebSocket();
+ // handleClose won't fire after removeAllListeners, so trigger reconnect manually
+ this.stopHeartbeat();
+ if (this.autoReconnect) {
+ this.setStatus('reconnecting');
+ this.scheduleReconnect();
+ } else {
+ this.setStatus('disconnected');
+ this.emit('disconnected');
+ }
+ return;
+ }
this.sendMessage({ type: 'heartbeat' });
}, HEARTBEAT_INTERVAL);
}