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-client): prevent uncaught WebSocket error on disconnect (#13635)

Inneia2eab24536d4
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index b45e5e3727a..c2b75211e84 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -506,16 +506,38 @@ describe('GatewayClient', () => {
});
describe('closeWebSocket edge cases', () => {
- it('should handle ws in CONNECTING state', async () => {
+ it('should keep suppressing close errors until the socket closes', async () => {
client.connect();
await vi.advanceTimersByTimeAsync(1);
const ws = (client as any).ws;
ws.readyState = 0; // CONNECTING
- ws.close = vi.fn();
- ws.removeAllListeners = vi.fn();
+ ws.close = vi.fn(() => {
+ setTimeout(() => {
+ ws.emit('error', new Error('WebSocket was closed before the connection was established'));
+ ws.emit('close', 1006, Buffer.from(''));
+ }, 0);
+ });
- (client as any).closeWebSocket();
+ expect(() => (client as any).closeWebSocket()).not.toThrow();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(ws.close).toHaveBeenCalled();
+ expect(() => ws.emit('error', new Error('listener should be removed after close'))).toThrow(
+ 'listener should be removed after close',
+ );
+ });
+
+ it('should handle ws.close throwing synchronously', async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws = (client as any).ws;
+ ws.readyState = 1; // OPEN
+ ws.close = vi.fn(() => {
+ throw new Error('close failed');
+ });
+
+ expect(() => (client as any).closeWebSocket()).not.toThrow();
expect(ws.close).toHaveBeenCalled();
});
@@ -526,7 +548,6 @@ describe('GatewayClient', () => {
const ws = (client as any).ws;
ws.readyState = 3; // CLOSED
ws.close = vi.fn();
- ws.removeAllListeners = vi.fn();
(client as any).closeWebSocket();
expect(ws.close).not.toHaveBeenCalled();
@@ -546,9 +567,7 @@ describe('GatewayClient', () => {
await vi.advanceTimersByTimeAsync(1);
const ws = (client as any).ws;
- expect(ws.send).toHaveBeenCalledWith(
- expect.stringContaining('"token":"refreshed-token"'),
- );
+ expect(ws.send).toHaveBeenCalledWith(expect.stringContaining('"token":"refreshed-token"'));
});
});
@@ -574,9 +593,7 @@ describe('GatewayClient', () => {
expect(client.connectionStatus).toBe('authenticating');
const ws = (client as any).ws;
- expect(ws.send).toHaveBeenCalledWith(
- expect.stringContaining('"token":"new-token"'),
- );
+ expect(ws.send).toHaveBeenCalledWith(expect.stringContaining('"token":"new-token"'));
});
it('should reset reconnect delay', async () => {
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 6293c4c899d..9bbfc733cc1 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -294,11 +294,9 @@ 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.logger.warn(`Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`);
this.closeWebSocket();
- // handleClose won't fire after removeAllListeners, so trigger reconnect manually
+ // Listeners are detached in closeWebSocket; handleClose won't run — drive reconnect here
this.stopHeartbeat();
if (this.autoReconnect) {
this.setStatus('reconnecting');
@@ -364,14 +362,38 @@ export class GatewayClient extends EventEmitter {
}
private closeWebSocket() {
- if (this.ws) {
- this.ws.removeAllListeners();
+ if (!this.ws) {
+ return;
+ }
+ const ws = this.ws;
+ const suppressCloseError = (error: Error) => {
+ this.logger.debug(`Ignoring WebSocket error during close: ${error.message}`);
+ };
+ const cleanupCloseErrorSuppression = () => {
+ ws.off('close', cleanupCloseErrorSuppression);
+ ws.off('error', suppressCloseError);
+ };
+
+ // Remove only listeners registered by this client.
+ // Keep a temporary error handler while closing to avoid unhandled
+ // "WebSocket was closed before the connection was established" errors.
+ ws.off('open', this.handleOpen);
+ ws.off('message', this.handleMessage);
+ ws.off('close', this.handleClose);
+ ws.off('error', this.handleError);
+ ws.on('error', suppressCloseError);
+ ws.once('close', cleanupCloseErrorSuppression);
- if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
- this.ws.close(1000, 'Client disconnect');
+ try {
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
+ ws.close(1000, 'Client disconnect');
}
- this.ws = null;
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ this.logger.warn(`Failed to close WebSocket gracefully: ${errorMsg}`);
}
+
+ this.ws = null;
}
private cleanup() {
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
index f701e3c1263..77479dfb086 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
@@ -3,6 +3,7 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import Tool from './Tool';
+import { shouldRenderToolCall } from './toolRenderRules';
interface ToolsRendererProps {
disableEditing?: boolean;
@@ -13,9 +14,13 @@ interface ToolsRendererProps {
export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId, tools }) => {
if (!tools || tools.length === 0) return null;
+ const visibleTools = tools.filter(shouldRenderToolCall);
+
+ if (visibleTools.length === 0) return null;
+
return (
<Flexbox gap={8}>
- {tools.map((tool) => (
+ {visibleTools.map((tool) => (
<Tool
apiName={tool.apiName}
arguments={tool.arguments}
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts
new file mode 100644
index 00000000000..1cf9c274eed
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts
@@ -0,0 +1,36 @@
+import {
+ WebOnboardingApiName,
+ WebOnboardingIdentifier,
+} from '@lobechat/builtin-tool-web-onboarding';
+import { describe, expect, it } from 'vitest';
+
+import { shouldRenderToolCall } from './toolRenderRules';
+
+describe('shouldRenderToolCall', () => {
+ it('hides the onboarding completion tool call', () => {
+ expect(
+ shouldRenderToolCall({
+ apiName: WebOnboardingApiName.finishOnboarding,
+ identifier: WebOnboardingIdentifier,
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps other onboarding tool calls visible', () => {
+ expect(
+ shouldRenderToolCall({
+ apiName: WebOnboardingApiName.saveUserQuestion,
+ identifier: WebOnboardingIdentifier,
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps non-onboarding tool calls visible', () => {
+ expect(
+ shouldRenderToolCall({
+ apiName: 'search',
+ identifier: 'lobe-web-browsing',
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts
new file mode 100644
index 00000000000..7617f1fac2b
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts
@@ -0,0 +1,18 @@
+import {
+ WebOnboardingApiName,
+ WebOnboardingIdentifier,
+} from '@lobechat/builtin-tool-web-onboarding';
+
+interface ToolRenderRuleTarget {
+ apiName: string;
+ identifier: string;
+}
+
+export const shouldRenderToolCall = ({ apiName, identifier }: ToolRenderRuleTarget) => {
+ // This call immediately ends onboarding and switches the UI to the completion state.
+ if (identifier === WebOnboardingIdentifier && apiName === WebOnboardingApiName.finishOnboarding) {
+ return false;
+ }
+
+ return true;
+};