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): stop two clients of one install from trading the gateway connection (#20100)

Arvin Xu0e630481792a
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index a3d936c6731..37e57dd197d 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -313,6 +313,17 @@ describe('connect command', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
});
+ it('stops when another connect process takes over the connection', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'connect']);
+
+ clientEventHandlers['replaced']?.();
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('took over'));
+ expect(cleanupAllProcesses).toHaveBeenCalled();
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
it('should retry auth_failed with token refresh when new token available', async () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 2b57e00e1e0..e8cbb16a351 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -592,6 +592,13 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
closeWorkspaceConnection(wsId);
});
+ wsClient.on('replaced', () => {
+ error(
+ `Workspace ${wsId} share connection was taken over by another '${CLI_PRIMARY_BIN} connect' on this machine. Closing it here.`,
+ );
+ closeWorkspaceConnection(wsId);
+ });
+
wsClient.on('auth_failed', (reason) => {
// Only this share connection is affected β€” never exit the personal process.
error(`Workspace ${wsId} authentication failed: ${reason}. Closing share connection.`);
@@ -770,6 +777,17 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
process.exit(1);
});
+ // Another `lh connect` of this install (same persisted connection id) took
+ // over. The client no longer reconnects β€” doing so is what made the two trade
+ // the connection every second β€” so exit instead of sitting silently offline.
+ client.on('replaced', () => {
+ error(
+ `Another '${CLI_PRIMARY_BIN} connect' on this machine took over this device's gateway connection. Only one can be connected at a time; stopping this one.`,
+ );
+ cleanup();
+ process.exit(1);
+ });
+
// Handle errors
client.on('error', (err) => {
error(`Connection error: ${err.message}`);
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index ef748513eb0..980193da3ec 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -501,6 +501,12 @@ export default class GatewayConnectionService extends ServiceModule {
}
});
+ client.on('replaced', () => {
+ logger.warn(
+ `Gateway connection${scope ? ` for workspace ${scope.workspaceId}` : ''} was taken over by another client with the same connection id; not reconnecting`,
+ );
+ });
+
client.on('error', (error) => {
logger.error('WebSocket error:', error.message);
});
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index d0379e0624a..c08f6a280eb 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -739,6 +739,113 @@ describe('GatewayClient', () => {
reconnectClient.disconnect();
});
+ it('stays down when another client with the same connection id takes over', async () => {
+ const replacedClient = new GatewayClient({
+ autoReconnect: true,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+ const replacedCb = vi.fn();
+ const reconnectingCb = vi.fn();
+ replacedClient.on('replaced', replacedCb);
+ replacedClient.on('reconnecting', reconnectingCb);
+
+ replacedClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ const sockets = mockWsInstances.length;
+
+ (replacedClient as any).handleClose(1000, Buffer.from('Replaced by new connection'));
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ expect(replacedCb).toHaveBeenCalledTimes(1);
+ expect(reconnectingCb).not.toHaveBeenCalled();
+ expect(replacedClient.connectionStatus).toBe('disconnected');
+ // No new socket: reconnecting would knock the other client off in turn.
+ expect(mockWsInstances.length).toBe(sockets);
+
+ replacedClient.disconnect();
+ });
+
+ const abandonThenReplace = async (
+ abandonMidHandshake: boolean,
+ {
+ connectTimeoutMs,
+ takeoverAfterMs = 0,
+ }: { connectTimeoutMs?: number; takeoverAfterMs?: number } = {},
+ ) => {
+ const racingClient = new GatewayClient({
+ autoReconnect: true,
+ connectTimeoutMs,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+ const replacedCb = vi.fn();
+ racingClient.on('replaced', replacedCb);
+
+ mockWsShouldHang = abandonMidHandshake;
+ racingClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ // Abandon the socket ourselves (watchdog path), then let the retry open.
+ (racingClient as any).forceReconnect('stalled');
+ mockWsShouldHang = false;
+ await vi.advanceTimersByTimeAsync(1_001 + takeoverAfterMs);
+
+ (racingClient as any).handleClose(1000, Buffer.from('Replaced by new connection'));
+ const status = racingClient.connectionStatus;
+ racingClient.disconnect();
+ return { replaced: replacedCb.mock.calls.length > 0, status };
+ };
+
+ it('still reconnects when its own mid-handshake socket arrives late', async () => {
+ // The abandoned upgrade reaches the gateway after the retry and knocks it off.
+ expect(await abandonThenReplace(true)).toEqual({ replaced: false, status: 'reconnecting' });
+ });
+
+ it('lets one abandoned socket excuse only one takeover', async () => {
+ const racingClient = new GatewayClient({
+ autoReconnect: true,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ });
+ const replacedCb = vi.fn();
+ racingClient.on('replaced', replacedCb);
+
+ mockWsShouldHang = true;
+ racingClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (racingClient as any).forceReconnect('stalled'); // abandons A1 mid-handshake
+ mockWsShouldHang = false;
+ await vi.advanceTimersByTimeAsync(1_001);
+
+ // A1 lands late and knocks off A2: our own socket, so reconnect.
+ (racingClient as any).handleClose(1000, Buffer.from('Replaced by new connection'));
+ expect(replacedCb).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1_001);
+
+ // Still inside the window, a real second client replaces A3: stay down.
+ (racingClient as any).handleClose(1000, Buffer.from('Replaced by new connection'));
+ expect(replacedCb).toHaveBeenCalledTimes(1);
+ expect(racingClient.connectionStatus).toBe('disconnected');
+
+ racingClient.disconnect();
+ });
+
+ it('sizes the self-takeover window by the configured connect timeout', async () => {
+ // A 40s handshake budget: an upgrade abandoned 20s ago can still land.
+ expect(
+ await abandonThenReplace(true, { connectTimeoutMs: 40_000, takeoverAfterMs: 20_000 }),
+ ).toEqual({ replaced: false, status: 'reconnecting' });
+ // A 5s budget: 8s later that upgrade is gone, so the takeover is a peer.
+ expect(
+ await abandonThenReplace(true, { connectTimeoutMs: 5_000, takeoverAfterMs: 8_000 }),
+ ).toEqual({ replaced: true, status: 'disconnected' });
+ });
+
+ it('treats a takeover after abandoning an opened socket as another client', async () => {
+ // An opened socket was registered before the retry, so it cannot replace it.
+ expect(await abandonThenReplace(false)).toEqual({ replaced: true, status: 'disconnected' });
+ });
+
it('should emit disconnected when autoReconnect is false and ws closes', async () => {
const disconnectedCb = vi.fn();
client.on('disconnected', disconnectedCb);
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 46f0bc58624..96b1af56bf6 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -38,6 +38,13 @@ const MAX_MISSED_HEARTBEATS = 3; // Force reconnect after 3 missed acks
*/
const CONNECT_TIMEOUT = 15_000; // 15s
const METRICS_ACK_TIMEOUT_MS = 15_000;
+/**
+ * Close reason the gateway sends when a newer socket with the same
+ * `connectionId` takes over. `connectionId` is persisted per install, so this
+ * is how a second process of the same install (two `lh connect` sharing one
+ * home) shows up.
+ */
+const REPLACED_CLOSE_REASON = 'Replaced by new connection';
// ─── Logger Interface ───
@@ -116,6 +123,15 @@ export class GatewayClient extends EventEmitter {
{ reject: (error: Error) => void; resolve: () => void }
>();
private intentionalDisconnect = false;
+ /**
+ * When each socket abandoned mid-handshake was abandoned. Only such a socket
+ * can reach the gateway after its successor and knock it off with the
+ * takeover reason: an opened socket was registered before the successor
+ * existed. Each can do that at most once, and only within `connectTimeoutMs`
+ * (the handshake budget), so a takeover consumes one live entry and anything
+ * beyond them is another client.
+ */
+ private inFlightAbandons: number[] = [];
private deviceId: string;
private connectionId: string;
private channel?: string;
@@ -489,6 +505,25 @@ export class GatewayClient extends EventEmitter {
this.clearConnectWatchdog();
this.ws = null;
+ if (
+ !this.intentionalDisconnect &&
+ reason.toString() === REPLACED_CLOSE_REASON &&
+ !this.consumeInFlightAbandon()
+ ) {
+ // Another client holding our connectionId just took over. Reconnecting
+ // would knock it off in turn: the two would trade the connection every
+ // second, and each tool call would land on whichever connected last β€”
+ // including a getCommandOutput sent to the process that never ran the
+ // command. Newest wins; this one stays down.
+ this.logger.warn(
+ 'Connection taken over by another client with the same connection id; not reconnecting',
+ );
+ this.setStatus('disconnected');
+ this.emit('replaced');
+ this.emit('disconnected');
+ return;
+ }
+
if (!this.intentionalDisconnect && this.autoReconnect) {
this.setStatus('reconnecting');
this.scheduleReconnect();
@@ -498,6 +533,13 @@ export class GatewayClient extends EventEmitter {
}
};
+ /** Attribute a takeover to one of our own late sockets, if one can still land. */
+ private consumeInFlightAbandon(): boolean {
+ const now = Date.now();
+ this.inFlightAbandons = this.inFlightAbandons.filter((at) => now - at <= this.connectTimeoutMs);
+ return this.inFlightAbandons.shift() !== undefined;
+ }
+
private handleError = (error: Error) => {
this.logger.error('WebSocket error:', error.message);
this.emit('error', error);
@@ -625,6 +667,7 @@ export class GatewayClient extends EventEmitter {
return;
}
const ws = this.ws;
+ if (ws.readyState === WebSocket.CONNECTING) this.inFlightAbandons.push(Date.now());
const suppressCloseError = (error: Error) => {
this.logger.debug(`Ignoring WebSocket error during close: ${error.message}`);
};
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index bedd4979095..cfafb2a2ed2 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -515,6 +515,11 @@ export interface GatewayClientEvents {
heartbeat_ack: () => void;
message_api_request: (request: MessageApiRequestMessage) => void;
reconnecting: (delay: number) => void;
+ /**
+ * The gateway closed this connection because another client with the same
+ * `connectionId` connected. The client does not reconnect after this.
+ */
+ replaced: () => void;
rpc_request: (request: RpcRequestMessage) => void;
status_changed: (status: ConnectionStatus) => void;
system_info_request: (request: SystemInfoRequestMessage) => void;