@elqnt/chat 2.0.7 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +386 -0
- package/dist/api/index.d.mts +308 -0
- package/dist/api/index.d.ts +308 -0
- package/dist/api/index.js +220 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/index.mjs +183 -0
- package/dist/api/index.mjs.map +1 -0
- package/dist/hooks/index.d.mts +78 -0
- package/dist/hooks/index.d.ts +78 -0
- package/dist/hooks/index.js +709 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/index.mjs +683 -0
- package/dist/hooks/index.mjs.map +1 -0
- package/dist/index.d.mts +4 -109
- package/dist/index.d.ts +4 -109
- package/dist/index.js +699 -3607
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +690 -3584
- package/dist/index.mjs.map +1 -1
- package/dist/models/index.d.mts +76 -6
- package/dist/models/index.d.ts +76 -6
- package/dist/models/index.js +21 -0
- package/dist/models/index.js.map +1 -1
- package/dist/models/index.mjs +14 -0
- package/dist/models/index.mjs.map +1 -1
- package/dist/transport/index.d.mts +243 -0
- package/dist/transport/index.d.ts +243 -0
- package/dist/transport/index.js +875 -0
- package/dist/transport/index.js.map +1 -0
- package/dist/transport/index.mjs +843 -0
- package/dist/transport/index.mjs.map +1 -0
- package/dist/types-BB5nRdZs.d.mts +222 -0
- package/dist/types-CNvuxtcv.d.ts +222 -0
- package/package.json +32 -40
- package/dist/hooks/use-websocket-chat-admin.d.mts +0 -17
- package/dist/hooks/use-websocket-chat-admin.d.ts +0 -17
- package/dist/hooks/use-websocket-chat-admin.js +0 -1196
- package/dist/hooks/use-websocket-chat-admin.js.map +0 -1
- package/dist/hooks/use-websocket-chat-admin.mjs +0 -1172
- package/dist/hooks/use-websocket-chat-admin.mjs.map +0 -1
- package/dist/hooks/use-websocket-chat-base.d.mts +0 -81
- package/dist/hooks/use-websocket-chat-base.d.ts +0 -81
- package/dist/hooks/use-websocket-chat-base.js +0 -1025
- package/dist/hooks/use-websocket-chat-base.js.map +0 -1
- package/dist/hooks/use-websocket-chat-base.mjs +0 -1001
- package/dist/hooks/use-websocket-chat-base.mjs.map +0 -1
- package/dist/hooks/use-websocket-chat-customer.d.mts +0 -24
- package/dist/hooks/use-websocket-chat-customer.d.ts +0 -24
- package/dist/hooks/use-websocket-chat-customer.js +0 -1092
- package/dist/hooks/use-websocket-chat-customer.js.map +0 -1
- package/dist/hooks/use-websocket-chat-customer.mjs +0 -1068
- package/dist/hooks/use-websocket-chat-customer.mjs.map +0 -1
|
@@ -1,1001 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
"use client";
|
|
3
|
-
|
|
4
|
-
// hooks/use-websocket-chat-base.ts
|
|
5
|
-
import { useCallback, useEffect, useRef, useState } from "react";
|
|
6
|
-
var createDefaultLogger = (debug) => ({
|
|
7
|
-
debug: debug ? console.log : () => {
|
|
8
|
-
},
|
|
9
|
-
info: console.info,
|
|
10
|
-
warn: console.warn,
|
|
11
|
-
error: console.error
|
|
12
|
-
});
|
|
13
|
-
var DEFAULT_RETRY_CONFIG = {
|
|
14
|
-
maxRetries: 10,
|
|
15
|
-
intervals: [1e3, 2e3, 5e3],
|
|
16
|
-
backoffMultiplier: 1.5,
|
|
17
|
-
maxBackoffTime: 3e4
|
|
18
|
-
};
|
|
19
|
-
var DEFAULT_QUEUE_CONFIG = {
|
|
20
|
-
maxSize: 100,
|
|
21
|
-
dropStrategy: "oldest"
|
|
22
|
-
};
|
|
23
|
-
var DEFAULT_HEARTBEAT_INTERVAL = 3e4;
|
|
24
|
-
var DEFAULT_HEARTBEAT_TIMEOUT = 5e3;
|
|
25
|
-
var DEFAULT_TRANSPORT = "websocket";
|
|
26
|
-
function isChatEvent(data) {
|
|
27
|
-
return data && typeof data === "object" && (typeof data.type === "string" || data.message);
|
|
28
|
-
}
|
|
29
|
-
var useWebSocketChatBase = ({
|
|
30
|
-
serverBaseUrl,
|
|
31
|
-
orgId,
|
|
32
|
-
clientType,
|
|
33
|
-
product,
|
|
34
|
-
onMessage,
|
|
35
|
-
retryConfig = DEFAULT_RETRY_CONFIG,
|
|
36
|
-
queueConfig = DEFAULT_QUEUE_CONFIG,
|
|
37
|
-
debug = false,
|
|
38
|
-
logger = createDefaultLogger(debug),
|
|
39
|
-
heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,
|
|
40
|
-
heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT,
|
|
41
|
-
transport = DEFAULT_TRANSPORT
|
|
42
|
-
}) => {
|
|
43
|
-
const [connectionState, setConnectionState] = useState("disconnected");
|
|
44
|
-
const [error, setError] = useState(void 0);
|
|
45
|
-
const [startTime, setStartTime] = useState(void 0);
|
|
46
|
-
const [metrics, setMetrics] = useState({
|
|
47
|
-
latency: 0,
|
|
48
|
-
messagesSent: 0,
|
|
49
|
-
messagesReceived: 0,
|
|
50
|
-
messagesQueued: 0,
|
|
51
|
-
reconnectCount: 0,
|
|
52
|
-
transportType: transport
|
|
53
|
-
});
|
|
54
|
-
const wsRef = useRef(void 0);
|
|
55
|
-
const sseRef = useRef(void 0);
|
|
56
|
-
const transportRef = useRef(transport);
|
|
57
|
-
useEffect(() => {
|
|
58
|
-
transportRef.current = transport;
|
|
59
|
-
}, [transport]);
|
|
60
|
-
const reconnectTimeoutRef = useRef(void 0);
|
|
61
|
-
const retryCountRef = useRef(0);
|
|
62
|
-
const messageQueueRef = useRef([]);
|
|
63
|
-
const mountedRef = useRef(false);
|
|
64
|
-
const currentChatKeyRef = useRef(void 0);
|
|
65
|
-
const currentUserIdRef = useRef(void 0);
|
|
66
|
-
const intentionalDisconnectRef = useRef(false);
|
|
67
|
-
const eventHandlersRef = useRef(
|
|
68
|
-
/* @__PURE__ */ new Map()
|
|
69
|
-
);
|
|
70
|
-
const onMessageRef = useRef(onMessage);
|
|
71
|
-
const pendingMessagesRef = useRef(/* @__PURE__ */ new Map());
|
|
72
|
-
const heartbeatIntervalRef = useRef(void 0);
|
|
73
|
-
const heartbeatTimeoutRef = useRef(void 0);
|
|
74
|
-
const lastPongRef = useRef(Date.now());
|
|
75
|
-
const chatCreationPromiseRef = useRef(null);
|
|
76
|
-
const loadChatRetryMapRef = useRef(/* @__PURE__ */ new Map());
|
|
77
|
-
useEffect(() => {
|
|
78
|
-
onMessageRef.current = onMessage;
|
|
79
|
-
}, [onMessage]);
|
|
80
|
-
const isConnected = connectionState === "connected";
|
|
81
|
-
const on = useCallback((eventType, handler) => {
|
|
82
|
-
if (!eventHandlersRef.current.has(eventType)) {
|
|
83
|
-
eventHandlersRef.current.set(eventType, /* @__PURE__ */ new Set());
|
|
84
|
-
}
|
|
85
|
-
eventHandlersRef.current.get(eventType).add(handler);
|
|
86
|
-
return () => off(eventType, handler);
|
|
87
|
-
}, []);
|
|
88
|
-
const off = useCallback((eventType, handler) => {
|
|
89
|
-
const handlers = eventHandlersRef.current.get(eventType);
|
|
90
|
-
if (handlers) {
|
|
91
|
-
handlers.delete(handler);
|
|
92
|
-
if (handlers.size === 0) {
|
|
93
|
-
eventHandlersRef.current.delete(eventType);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
}, []);
|
|
97
|
-
const emit = useCallback(
|
|
98
|
-
(eventType, data) => {
|
|
99
|
-
const handlers = eventHandlersRef.current.get(eventType);
|
|
100
|
-
if (handlers) {
|
|
101
|
-
handlers.forEach((handler) => {
|
|
102
|
-
try {
|
|
103
|
-
handler(data);
|
|
104
|
-
} catch (error2) {
|
|
105
|
-
logger.error(`Error in event handler for ${eventType}:`, error2);
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
},
|
|
110
|
-
[logger]
|
|
111
|
-
);
|
|
112
|
-
const updateMetrics = useCallback((updates) => {
|
|
113
|
-
setMetrics((prev) => ({ ...prev, ...updates }));
|
|
114
|
-
}, []);
|
|
115
|
-
const addToQueue = useCallback(
|
|
116
|
-
(event) => {
|
|
117
|
-
const currentQueueSize = messageQueueRef.current.length;
|
|
118
|
-
const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize;
|
|
119
|
-
if (currentQueueSize >= maxSize) {
|
|
120
|
-
if (queueConfig.dropStrategy === "newest") {
|
|
121
|
-
logger.warn("Message queue full, dropping new message");
|
|
122
|
-
return false;
|
|
123
|
-
} else {
|
|
124
|
-
const dropped = messageQueueRef.current.shift();
|
|
125
|
-
logger.warn("Message queue full, dropped oldest message", dropped);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
messageQueueRef.current.push(event);
|
|
129
|
-
updateMetrics({ messagesQueued: messageQueueRef.current.length });
|
|
130
|
-
return true;
|
|
131
|
-
},
|
|
132
|
-
[queueConfig, logger, updateMetrics]
|
|
133
|
-
);
|
|
134
|
-
const calculateRetryInterval = useCallback(
|
|
135
|
-
(retryCount) => {
|
|
136
|
-
const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
|
|
137
|
-
const {
|
|
138
|
-
intervals = [],
|
|
139
|
-
backoffMultiplier = 1.5,
|
|
140
|
-
maxBackoffTime = 3e4
|
|
141
|
-
} = config;
|
|
142
|
-
if (retryCount < intervals.length) {
|
|
143
|
-
return intervals[retryCount];
|
|
144
|
-
}
|
|
145
|
-
const baseInterval = intervals[intervals.length - 1] || 5e3;
|
|
146
|
-
const backoffTime = baseInterval * Math.pow(backoffMultiplier, retryCount - intervals.length + 1);
|
|
147
|
-
return Math.min(backoffTime, maxBackoffTime);
|
|
148
|
-
},
|
|
149
|
-
[retryConfig]
|
|
150
|
-
);
|
|
151
|
-
const startHeartbeat = useCallback(() => {
|
|
152
|
-
if (!heartbeatInterval || heartbeatInterval <= 0) return;
|
|
153
|
-
const sendPing = () => {
|
|
154
|
-
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
|
155
|
-
const pingTime = Date.now();
|
|
156
|
-
wsRef.current.send(
|
|
157
|
-
JSON.stringify({ type: "ping", timestamp: pingTime })
|
|
158
|
-
);
|
|
159
|
-
heartbeatTimeoutRef.current = setTimeout(() => {
|
|
160
|
-
logger.warn("Heartbeat timeout - no pong received");
|
|
161
|
-
if (wsRef.current) {
|
|
162
|
-
wsRef.current.close(4e3, "Heartbeat timeout");
|
|
163
|
-
}
|
|
164
|
-
}, heartbeatTimeout);
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
if (heartbeatIntervalRef.current) {
|
|
168
|
-
clearInterval(heartbeatIntervalRef.current);
|
|
169
|
-
}
|
|
170
|
-
heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);
|
|
171
|
-
logger.debug("Heartbeat started");
|
|
172
|
-
}, [heartbeatInterval, heartbeatTimeout, logger]);
|
|
173
|
-
const stopHeartbeat = useCallback(() => {
|
|
174
|
-
if (heartbeatIntervalRef.current) {
|
|
175
|
-
clearInterval(heartbeatIntervalRef.current);
|
|
176
|
-
heartbeatIntervalRef.current = void 0;
|
|
177
|
-
}
|
|
178
|
-
if (heartbeatTimeoutRef.current) {
|
|
179
|
-
clearTimeout(heartbeatTimeoutRef.current);
|
|
180
|
-
heartbeatTimeoutRef.current = void 0;
|
|
181
|
-
}
|
|
182
|
-
logger.debug("Heartbeat stopped");
|
|
183
|
-
}, [logger]);
|
|
184
|
-
const cleanup = useCallback(() => {
|
|
185
|
-
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
|
186
|
-
wsRef.current.close(1e3, "Cleanup");
|
|
187
|
-
}
|
|
188
|
-
wsRef.current = void 0;
|
|
189
|
-
if (sseRef.current) {
|
|
190
|
-
sseRef.current.close();
|
|
191
|
-
sseRef.current = void 0;
|
|
192
|
-
}
|
|
193
|
-
if (reconnectTimeoutRef.current) {
|
|
194
|
-
clearTimeout(reconnectTimeoutRef.current);
|
|
195
|
-
reconnectTimeoutRef.current = void 0;
|
|
196
|
-
}
|
|
197
|
-
stopHeartbeat();
|
|
198
|
-
pendingMessagesRef.current.forEach(({ reject, timeout }) => {
|
|
199
|
-
clearTimeout(timeout);
|
|
200
|
-
reject(new Error("Connection closed"));
|
|
201
|
-
});
|
|
202
|
-
pendingMessagesRef.current.clear();
|
|
203
|
-
loadChatRetryMapRef.current.forEach((retryState) => {
|
|
204
|
-
if (retryState.timeoutId) {
|
|
205
|
-
clearTimeout(retryState.timeoutId);
|
|
206
|
-
}
|
|
207
|
-
});
|
|
208
|
-
loadChatRetryMapRef.current.clear();
|
|
209
|
-
}, [stopHeartbeat]);
|
|
210
|
-
const getRestApiUrl = useCallback((endpoint) => {
|
|
211
|
-
return `${serverBaseUrl}/${endpoint}`;
|
|
212
|
-
}, [serverBaseUrl]);
|
|
213
|
-
const sendRestMessage = useCallback(
|
|
214
|
-
async (endpoint, body) => {
|
|
215
|
-
const url = getRestApiUrl(endpoint);
|
|
216
|
-
logger.debug(`SSE REST API call: POST ${endpoint}`, body);
|
|
217
|
-
try {
|
|
218
|
-
const response = await fetch(url, {
|
|
219
|
-
method: "POST",
|
|
220
|
-
headers: {
|
|
221
|
-
"Content-Type": "application/json"
|
|
222
|
-
},
|
|
223
|
-
body: JSON.stringify(body)
|
|
224
|
-
});
|
|
225
|
-
if (!response.ok) {
|
|
226
|
-
const errorText = await response.text();
|
|
227
|
-
throw new Error(`REST API error: ${response.status} - ${errorText}`);
|
|
228
|
-
}
|
|
229
|
-
const data = await response.json();
|
|
230
|
-
return data;
|
|
231
|
-
} catch (error2) {
|
|
232
|
-
logger.error(`SSE REST API error for ${endpoint}:`, error2);
|
|
233
|
-
throw error2;
|
|
234
|
-
}
|
|
235
|
-
},
|
|
236
|
-
[getRestApiUrl, logger]
|
|
237
|
-
);
|
|
238
|
-
const connect = useCallback(
|
|
239
|
-
async (userId) => {
|
|
240
|
-
if (!mountedRef.current) {
|
|
241
|
-
mountedRef.current = true;
|
|
242
|
-
}
|
|
243
|
-
if (!orgId) {
|
|
244
|
-
const error2 = {
|
|
245
|
-
code: "CONNECTION_FAILED",
|
|
246
|
-
message: "Cannot connect: orgId is undefined",
|
|
247
|
-
retryable: false,
|
|
248
|
-
timestamp: Date.now()
|
|
249
|
-
};
|
|
250
|
-
logger.error("Cannot connect: orgId is undefined");
|
|
251
|
-
setError(error2);
|
|
252
|
-
return Promise.reject(error2);
|
|
253
|
-
}
|
|
254
|
-
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
|
255
|
-
logger.debug("Already connected (WebSocket)");
|
|
256
|
-
return Promise.resolve();
|
|
257
|
-
}
|
|
258
|
-
if (sseRef.current?.readyState === EventSource.OPEN) {
|
|
259
|
-
logger.debug("Already connected (SSE)");
|
|
260
|
-
return Promise.resolve();
|
|
261
|
-
}
|
|
262
|
-
if (connectionState === "connecting" || connectionState === "reconnecting") {
|
|
263
|
-
logger.debug("Connection already in progress");
|
|
264
|
-
return Promise.resolve();
|
|
265
|
-
}
|
|
266
|
-
const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
|
|
267
|
-
if (retryCountRef.current >= maxRetries && !intentionalDisconnectRef.current) {
|
|
268
|
-
const error2 = {
|
|
269
|
-
code: "CONNECTION_FAILED",
|
|
270
|
-
message: `Max retries (${maxRetries}) exceeded`,
|
|
271
|
-
retryable: false,
|
|
272
|
-
timestamp: Date.now()
|
|
273
|
-
};
|
|
274
|
-
setError(error2);
|
|
275
|
-
updateMetrics({ lastError: error2 });
|
|
276
|
-
return Promise.reject(error2);
|
|
277
|
-
}
|
|
278
|
-
cleanup();
|
|
279
|
-
setConnectionState(
|
|
280
|
-
retryCountRef.current > 0 ? "reconnecting" : "connecting"
|
|
281
|
-
);
|
|
282
|
-
intentionalDisconnectRef.current = false;
|
|
283
|
-
return new Promise((resolve, reject) => {
|
|
284
|
-
try {
|
|
285
|
-
const connectionStartTime = Date.now();
|
|
286
|
-
logger.info(`\u{1F504} Connecting with transport: ${transportRef.current}`);
|
|
287
|
-
if (transportRef.current === "sse") {
|
|
288
|
-
const sseUrl = getRestApiUrl(`stream?orgId=${orgId}&userId=${userId}&clientType=${clientType}&chatId=${currentChatKeyRef.current || ""}`);
|
|
289
|
-
logger.debug("Connecting to SSE:", sseUrl);
|
|
290
|
-
console.log(`\u23F3 Initiating SSE connection to ${sseUrl}...`);
|
|
291
|
-
const eventSource = new EventSource(sseUrl);
|
|
292
|
-
eventSource.onopen = () => {
|
|
293
|
-
if (!mountedRef.current) {
|
|
294
|
-
eventSource.close();
|
|
295
|
-
reject(new Error("Component unmounted"));
|
|
296
|
-
return;
|
|
297
|
-
}
|
|
298
|
-
const connectionTimeMs = Date.now() - connectionStartTime;
|
|
299
|
-
const connectionTimeSec = (connectionTimeMs / 1e3).toFixed(2);
|
|
300
|
-
logger.info("\u2705 SSE connected", {
|
|
301
|
-
userId,
|
|
302
|
-
retryCount: retryCountRef.current,
|
|
303
|
-
connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`
|
|
304
|
-
});
|
|
305
|
-
console.log(`\u{1F50C} SSE connection established in ${connectionTimeSec} seconds`);
|
|
306
|
-
setConnectionState("connected");
|
|
307
|
-
setError(void 0);
|
|
308
|
-
const wasReconnecting = retryCountRef.current > 0;
|
|
309
|
-
retryCountRef.current = 0;
|
|
310
|
-
updateMetrics({
|
|
311
|
-
connectedAt: Date.now(),
|
|
312
|
-
latency: connectionTimeMs,
|
|
313
|
-
transportType: "sse",
|
|
314
|
-
reconnectCount: wasReconnecting ? metrics.reconnectCount + 1 : metrics.reconnectCount
|
|
315
|
-
});
|
|
316
|
-
currentUserIdRef.current = userId;
|
|
317
|
-
if (currentChatKeyRef.current) {
|
|
318
|
-
logger.info("Loading chat after SSE reconnection:", currentChatKeyRef.current);
|
|
319
|
-
sendRestMessage("load", {
|
|
320
|
-
orgId,
|
|
321
|
-
chatKey: currentChatKeyRef.current,
|
|
322
|
-
userId
|
|
323
|
-
}).then((response) => {
|
|
324
|
-
if (response.success && response.data?.chat) {
|
|
325
|
-
const chatEvent = {
|
|
326
|
-
type: "load_chat_response",
|
|
327
|
-
orgId,
|
|
328
|
-
chatKey: currentChatKeyRef.current,
|
|
329
|
-
userId,
|
|
330
|
-
timestamp: Date.now(),
|
|
331
|
-
data: response.data
|
|
332
|
-
};
|
|
333
|
-
emit("load_chat_response", chatEvent);
|
|
334
|
-
if (onMessageRef.current) {
|
|
335
|
-
onMessageRef.current(chatEvent);
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
}).catch((err) => {
|
|
339
|
-
logger.error("Failed to load chat after SSE reconnection:", err);
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
emit("connected", { userId, wasReconnecting, transport: "sse" });
|
|
343
|
-
resolve();
|
|
344
|
-
};
|
|
345
|
-
const handleSSEMessage = (event) => {
|
|
346
|
-
if (!mountedRef.current) return;
|
|
347
|
-
if (!event.data || event.data === "") {
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
try {
|
|
351
|
-
const data = JSON.parse(event.data);
|
|
352
|
-
if (!isChatEvent(data)) {
|
|
353
|
-
logger.warn("Received invalid SSE message format:", data);
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
const chatEvent = data;
|
|
357
|
-
logger.debug("SSE message received:", chatEvent.type);
|
|
358
|
-
updateMetrics({
|
|
359
|
-
messagesReceived: metrics.messagesReceived + 1,
|
|
360
|
-
lastMessageAt: Date.now()
|
|
361
|
-
});
|
|
362
|
-
switch (chatEvent.type) {
|
|
363
|
-
case "new_chat_created":
|
|
364
|
-
const newChatKey = chatEvent.data?.chatKey;
|
|
365
|
-
if (newChatKey) {
|
|
366
|
-
logger.info("New chat created with key:", newChatKey);
|
|
367
|
-
currentChatKeyRef.current = newChatKey;
|
|
368
|
-
if (chatCreationPromiseRef.current) {
|
|
369
|
-
chatCreationPromiseRef.current.resolve(newChatKey);
|
|
370
|
-
chatCreationPromiseRef.current = null;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
break;
|
|
374
|
-
case "load_chat_response":
|
|
375
|
-
const chat = chatEvent.data?.chat;
|
|
376
|
-
if (chat && chat.key) {
|
|
377
|
-
logger.info("Chat loaded with key:", chat.key);
|
|
378
|
-
currentChatKeyRef.current = chat.key;
|
|
379
|
-
}
|
|
380
|
-
break;
|
|
381
|
-
case "chat_ended":
|
|
382
|
-
logger.info("Chat ended, clearing key");
|
|
383
|
-
currentChatKeyRef.current = void 0;
|
|
384
|
-
break;
|
|
385
|
-
}
|
|
386
|
-
emit(chatEvent.type || "message", chatEvent);
|
|
387
|
-
if (onMessageRef.current) {
|
|
388
|
-
onMessageRef.current(chatEvent);
|
|
389
|
-
}
|
|
390
|
-
} catch (error2) {
|
|
391
|
-
logger.error("Failed to parse SSE message:", error2);
|
|
392
|
-
}
|
|
393
|
-
};
|
|
394
|
-
eventSource.addEventListener("message", handleSSEMessage);
|
|
395
|
-
eventSource.addEventListener("reconnected", handleSSEMessage);
|
|
396
|
-
eventSource.addEventListener("typing", handleSSEMessage);
|
|
397
|
-
eventSource.addEventListener("stopped_typing", handleSSEMessage);
|
|
398
|
-
eventSource.addEventListener("waiting", handleSSEMessage);
|
|
399
|
-
eventSource.addEventListener("waiting_for_agent", handleSSEMessage);
|
|
400
|
-
eventSource.addEventListener("human_agent_joined", handleSSEMessage);
|
|
401
|
-
eventSource.addEventListener("human_agent_left", handleSSEMessage);
|
|
402
|
-
eventSource.addEventListener("chat_ended", handleSSEMessage);
|
|
403
|
-
eventSource.addEventListener("chat_updated", handleSSEMessage);
|
|
404
|
-
eventSource.addEventListener("load_chat_response", handleSSEMessage);
|
|
405
|
-
eventSource.addEventListener("new_chat_created", handleSSEMessage);
|
|
406
|
-
eventSource.addEventListener("show_csat_survey", handleSSEMessage);
|
|
407
|
-
eventSource.addEventListener("csat_response", handleSSEMessage);
|
|
408
|
-
eventSource.addEventListener("user_suggested_actions", handleSSEMessage);
|
|
409
|
-
eventSource.addEventListener("agent_execution_started", handleSSEMessage);
|
|
410
|
-
eventSource.addEventListener("agent_execution_ended", handleSSEMessage);
|
|
411
|
-
eventSource.addEventListener("agent_context_update", handleSSEMessage);
|
|
412
|
-
eventSource.addEventListener("plan_pending_approval", handleSSEMessage);
|
|
413
|
-
eventSource.addEventListener("step_started", handleSSEMessage);
|
|
414
|
-
eventSource.addEventListener("step_completed", handleSSEMessage);
|
|
415
|
-
eventSource.addEventListener("step_failed", handleSSEMessage);
|
|
416
|
-
eventSource.addEventListener("plan_completed", handleSSEMessage);
|
|
417
|
-
eventSource.addEventListener("skills_changed", handleSSEMessage);
|
|
418
|
-
eventSource.addEventListener("summary_update", handleSSEMessage);
|
|
419
|
-
eventSource.onerror = (error2) => {
|
|
420
|
-
logger.error("SSE error:", error2);
|
|
421
|
-
if (!mountedRef.current) return;
|
|
422
|
-
if (eventSource.readyState === EventSource.CLOSED) {
|
|
423
|
-
const sseError = {
|
|
424
|
-
code: "CONNECTION_FAILED",
|
|
425
|
-
message: "SSE connection failed",
|
|
426
|
-
retryable: true,
|
|
427
|
-
timestamp: Date.now()
|
|
428
|
-
};
|
|
429
|
-
setError(sseError);
|
|
430
|
-
updateMetrics({ lastError: sseError });
|
|
431
|
-
setConnectionState("disconnected");
|
|
432
|
-
emit("disconnected", { reason: "SSE error" });
|
|
433
|
-
if (!intentionalDisconnectRef.current && mountedRef.current) {
|
|
434
|
-
const retryInterval = calculateRetryInterval(retryCountRef.current);
|
|
435
|
-
retryCountRef.current++;
|
|
436
|
-
logger.info(`SSE reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`);
|
|
437
|
-
if (reconnectTimeoutRef.current) {
|
|
438
|
-
clearTimeout(reconnectTimeoutRef.current);
|
|
439
|
-
}
|
|
440
|
-
reconnectTimeoutRef.current = setTimeout(() => {
|
|
441
|
-
connect(userId);
|
|
442
|
-
}, retryInterval);
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
};
|
|
446
|
-
sseRef.current = eventSource;
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;
|
|
450
|
-
logger.debug("Connecting to WebSocket:", wsUrl);
|
|
451
|
-
console.log(`\u23F3 Initiating WebSocket connection to ${serverBaseUrl}...`);
|
|
452
|
-
const ws = new WebSocket(wsUrl);
|
|
453
|
-
ws.onopen = () => {
|
|
454
|
-
if (!mountedRef.current) {
|
|
455
|
-
ws.close(1e3, "Component unmounted");
|
|
456
|
-
reject(new Error("Component unmounted"));
|
|
457
|
-
return;
|
|
458
|
-
}
|
|
459
|
-
const connectionTimeMs = Date.now() - connectionStartTime;
|
|
460
|
-
const connectionTimeSec = (connectionTimeMs / 1e3).toFixed(2);
|
|
461
|
-
logger.info("\u2705 WebSocket connected", {
|
|
462
|
-
userId,
|
|
463
|
-
retryCount: retryCountRef.current,
|
|
464
|
-
connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`
|
|
465
|
-
});
|
|
466
|
-
console.log(`\u{1F50C} WebSocket connection established in ${connectionTimeSec} seconds`);
|
|
467
|
-
setConnectionState("connected");
|
|
468
|
-
setError(void 0);
|
|
469
|
-
const wasReconnecting = retryCountRef.current > 0;
|
|
470
|
-
retryCountRef.current = 0;
|
|
471
|
-
updateMetrics({
|
|
472
|
-
connectedAt: Date.now(),
|
|
473
|
-
latency: connectionTimeMs,
|
|
474
|
-
reconnectCount: wasReconnecting ? metrics.reconnectCount + 1 : metrics.reconnectCount
|
|
475
|
-
});
|
|
476
|
-
while (messageQueueRef.current.length > 0 && ws.readyState === WebSocket.OPEN) {
|
|
477
|
-
const event = messageQueueRef.current.shift();
|
|
478
|
-
if (event) {
|
|
479
|
-
ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));
|
|
480
|
-
updateMetrics({
|
|
481
|
-
messagesSent: metrics.messagesSent + 1,
|
|
482
|
-
messagesQueued: messageQueueRef.current.length
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
currentUserIdRef.current = userId;
|
|
487
|
-
if (currentChatKeyRef.current) {
|
|
488
|
-
if (!orgId) {
|
|
489
|
-
logger.error("Cannot resubscribe to chat: orgId is undefined");
|
|
490
|
-
} else {
|
|
491
|
-
logger.info(
|
|
492
|
-
"Resubscribing to chat after reconnection:",
|
|
493
|
-
currentChatKeyRef.current
|
|
494
|
-
);
|
|
495
|
-
const resubscribeEvent = {
|
|
496
|
-
type: "load_chat",
|
|
497
|
-
orgId,
|
|
498
|
-
chatKey: currentChatKeyRef.current,
|
|
499
|
-
userId,
|
|
500
|
-
timestamp: Date.now(),
|
|
501
|
-
data: {}
|
|
502
|
-
};
|
|
503
|
-
ws.send(JSON.stringify(resubscribeEvent));
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
startHeartbeat();
|
|
507
|
-
emit("connected", { userId, wasReconnecting });
|
|
508
|
-
resolve();
|
|
509
|
-
};
|
|
510
|
-
ws.onmessage = (event) => {
|
|
511
|
-
if (!mountedRef.current) return;
|
|
512
|
-
try {
|
|
513
|
-
const data = JSON.parse(event.data);
|
|
514
|
-
if (!isChatEvent(data)) {
|
|
515
|
-
logger.warn("Received invalid message format:", data);
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
const chatEvent = data;
|
|
519
|
-
logger.debug("Message received:", chatEvent.type);
|
|
520
|
-
updateMetrics({
|
|
521
|
-
messagesReceived: metrics.messagesReceived + 1,
|
|
522
|
-
lastMessageAt: Date.now()
|
|
523
|
-
});
|
|
524
|
-
if (chatEvent.type === "pong") {
|
|
525
|
-
if (heartbeatTimeoutRef.current) {
|
|
526
|
-
clearTimeout(heartbeatTimeoutRef.current);
|
|
527
|
-
heartbeatTimeoutRef.current = void 0;
|
|
528
|
-
}
|
|
529
|
-
const latency = Date.now() - (chatEvent.timestamp || Date.now());
|
|
530
|
-
lastPongRef.current = Date.now();
|
|
531
|
-
updateMetrics({ latency });
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
534
|
-
switch (chatEvent.type) {
|
|
535
|
-
case "new_chat_created":
|
|
536
|
-
const newChatKey = chatEvent.data?.chatKey;
|
|
537
|
-
if (newChatKey) {
|
|
538
|
-
logger.info("New chat created with key:", newChatKey);
|
|
539
|
-
currentChatKeyRef.current = newChatKey;
|
|
540
|
-
if (chatCreationPromiseRef.current) {
|
|
541
|
-
chatCreationPromiseRef.current.resolve(newChatKey);
|
|
542
|
-
chatCreationPromiseRef.current = null;
|
|
543
|
-
}
|
|
544
|
-
if (!orgId) {
|
|
545
|
-
logger.error("Cannot send load_chat: orgId is undefined");
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
const loadChatEvent = {
|
|
549
|
-
type: "load_chat",
|
|
550
|
-
orgId,
|
|
551
|
-
chatKey: newChatKey,
|
|
552
|
-
userId: currentUserIdRef.current || userId,
|
|
553
|
-
timestamp: Date.now(),
|
|
554
|
-
data: {}
|
|
555
|
-
};
|
|
556
|
-
ws.send(JSON.stringify(loadChatEvent));
|
|
557
|
-
}
|
|
558
|
-
break;
|
|
559
|
-
case "load_chat_response":
|
|
560
|
-
const chat = chatEvent.data?.chat;
|
|
561
|
-
if (chat && chat.key) {
|
|
562
|
-
logger.info("Chat loaded with key:", chat.key);
|
|
563
|
-
currentChatKeyRef.current = chat.key;
|
|
564
|
-
const retryState = loadChatRetryMapRef.current.get(chat.key);
|
|
565
|
-
if (retryState) {
|
|
566
|
-
if (retryState.timeoutId) {
|
|
567
|
-
clearTimeout(retryState.timeoutId);
|
|
568
|
-
}
|
|
569
|
-
loadChatRetryMapRef.current.delete(chat.key);
|
|
570
|
-
}
|
|
571
|
-
} else if (!chat) {
|
|
572
|
-
logger.warn("Chat load failed, clearing key");
|
|
573
|
-
currentChatKeyRef.current = void 0;
|
|
574
|
-
}
|
|
575
|
-
break;
|
|
576
|
-
case "chat_ended":
|
|
577
|
-
logger.info("Chat ended, clearing key");
|
|
578
|
-
currentChatKeyRef.current = void 0;
|
|
579
|
-
break;
|
|
580
|
-
case "error":
|
|
581
|
-
const errorMessage = chatEvent.data?.message || "Unknown error";
|
|
582
|
-
logger.error("Received error from server:", errorMessage);
|
|
583
|
-
if (errorMessage.includes("nats: key not found") || errorMessage.includes("Failed to load chat")) {
|
|
584
|
-
const chatKeyFromError = currentChatKeyRef.current;
|
|
585
|
-
if (chatKeyFromError) {
|
|
586
|
-
const maxRetries2 = 5;
|
|
587
|
-
let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);
|
|
588
|
-
if (!retryState) {
|
|
589
|
-
retryState = { retryCount: 0, timeoutId: null };
|
|
590
|
-
loadChatRetryMapRef.current.set(chatKeyFromError, retryState);
|
|
591
|
-
}
|
|
592
|
-
if (retryState.retryCount < maxRetries2) {
|
|
593
|
-
const delay = 200 * Math.pow(2, retryState.retryCount);
|
|
594
|
-
retryState.retryCount++;
|
|
595
|
-
logger.info(
|
|
596
|
-
`Chat load failed, retrying (${retryState.retryCount}/${maxRetries2}) in ${delay}ms...`,
|
|
597
|
-
chatKeyFromError
|
|
598
|
-
);
|
|
599
|
-
retryState.timeoutId = setTimeout(() => {
|
|
600
|
-
if (!wsRef.current || !mountedRef.current) return;
|
|
601
|
-
if (!orgId) {
|
|
602
|
-
logger.error("Cannot retry load_chat: orgId is undefined", chatKeyFromError);
|
|
603
|
-
loadChatRetryMapRef.current.delete(chatKeyFromError);
|
|
604
|
-
return;
|
|
605
|
-
}
|
|
606
|
-
logger.debug("Retrying load_chat:", chatKeyFromError);
|
|
607
|
-
const retryLoadEvent = {
|
|
608
|
-
type: "load_chat",
|
|
609
|
-
orgId,
|
|
610
|
-
chatKey: chatKeyFromError,
|
|
611
|
-
userId: currentUserIdRef.current || "",
|
|
612
|
-
timestamp: Date.now(),
|
|
613
|
-
data: {}
|
|
614
|
-
};
|
|
615
|
-
ws.send(JSON.stringify(retryLoadEvent));
|
|
616
|
-
}, delay);
|
|
617
|
-
} else {
|
|
618
|
-
logger.error("Max retries reached for loading chat:", chatKeyFromError);
|
|
619
|
-
loadChatRetryMapRef.current.delete(chatKeyFromError);
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
const wsError = {
|
|
624
|
-
code: "NETWORK_ERROR",
|
|
625
|
-
message: errorMessage,
|
|
626
|
-
retryable: true,
|
|
627
|
-
timestamp: Date.now()
|
|
628
|
-
};
|
|
629
|
-
setError(wsError);
|
|
630
|
-
updateMetrics({ lastError: wsError });
|
|
631
|
-
break;
|
|
632
|
-
}
|
|
633
|
-
emit(chatEvent.type || "message", chatEvent);
|
|
634
|
-
if (onMessageRef.current) {
|
|
635
|
-
onMessageRef.current(chatEvent);
|
|
636
|
-
}
|
|
637
|
-
} catch (error2) {
|
|
638
|
-
logger.error("Failed to parse WebSocket message:", error2);
|
|
639
|
-
const parseError = {
|
|
640
|
-
code: "PARSE_ERROR",
|
|
641
|
-
message: "Failed to parse message",
|
|
642
|
-
retryable: false,
|
|
643
|
-
timestamp: Date.now()
|
|
644
|
-
};
|
|
645
|
-
setError(parseError);
|
|
646
|
-
updateMetrics({ lastError: parseError });
|
|
647
|
-
}
|
|
648
|
-
};
|
|
649
|
-
ws.onclose = (event) => {
|
|
650
|
-
if (!mountedRef.current) return;
|
|
651
|
-
logger.info("WebSocket closed", {
|
|
652
|
-
code: event.code,
|
|
653
|
-
reason: event.reason
|
|
654
|
-
});
|
|
655
|
-
setConnectionState("disconnected");
|
|
656
|
-
wsRef.current = void 0;
|
|
657
|
-
stopHeartbeat();
|
|
658
|
-
emit("disconnected", { code: event.code, reason: event.reason });
|
|
659
|
-
if (event.code !== 1e3 && !intentionalDisconnectRef.current && mountedRef.current) {
|
|
660
|
-
const retryInterval = calculateRetryInterval(
|
|
661
|
-
retryCountRef.current
|
|
662
|
-
);
|
|
663
|
-
retryCountRef.current++;
|
|
664
|
-
logger.info(
|
|
665
|
-
`Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`
|
|
666
|
-
);
|
|
667
|
-
if (reconnectTimeoutRef.current) {
|
|
668
|
-
clearTimeout(reconnectTimeoutRef.current);
|
|
669
|
-
}
|
|
670
|
-
reconnectTimeoutRef.current = setTimeout(() => {
|
|
671
|
-
connect(userId);
|
|
672
|
-
}, retryInterval);
|
|
673
|
-
}
|
|
674
|
-
};
|
|
675
|
-
ws.onerror = (error2) => {
|
|
676
|
-
logger.error("WebSocket error:", error2);
|
|
677
|
-
if (!mountedRef.current) return;
|
|
678
|
-
const wsError = {
|
|
679
|
-
code: "CONNECTION_FAILED",
|
|
680
|
-
message: "WebSocket connection failed",
|
|
681
|
-
retryable: true,
|
|
682
|
-
timestamp: Date.now()
|
|
683
|
-
};
|
|
684
|
-
setError(wsError);
|
|
685
|
-
updateMetrics({ lastError: wsError });
|
|
686
|
-
reject(wsError);
|
|
687
|
-
};
|
|
688
|
-
wsRef.current = ws;
|
|
689
|
-
} catch (error2) {
|
|
690
|
-
logger.error("Failed to create WebSocket:", error2);
|
|
691
|
-
const wsError = {
|
|
692
|
-
code: "CONNECTION_FAILED",
|
|
693
|
-
message: error2 instanceof Error ? error2.message : "Failed to create connection",
|
|
694
|
-
retryable: true,
|
|
695
|
-
timestamp: Date.now()
|
|
696
|
-
};
|
|
697
|
-
setError(wsError);
|
|
698
|
-
updateMetrics({ lastError: wsError });
|
|
699
|
-
reject(wsError);
|
|
700
|
-
}
|
|
701
|
-
});
|
|
702
|
-
},
|
|
703
|
-
[
|
|
704
|
-
serverBaseUrl,
|
|
705
|
-
orgId,
|
|
706
|
-
clientType,
|
|
707
|
-
product,
|
|
708
|
-
connectionState,
|
|
709
|
-
logger,
|
|
710
|
-
retryConfig,
|
|
711
|
-
metrics,
|
|
712
|
-
updateMetrics,
|
|
713
|
-
cleanup,
|
|
714
|
-
calculateRetryInterval,
|
|
715
|
-
startHeartbeat,
|
|
716
|
-
emit
|
|
717
|
-
]
|
|
718
|
-
);
|
|
719
|
-
const sendMessage = useCallback(
|
|
720
|
-
(event, overrideUserId) => {
|
|
721
|
-
return new Promise(async (resolve, reject) => {
|
|
722
|
-
if (!mountedRef.current) {
|
|
723
|
-
reject(new Error("Component not mounted"));
|
|
724
|
-
return;
|
|
725
|
-
}
|
|
726
|
-
const fullEvent = {
|
|
727
|
-
...event,
|
|
728
|
-
timestamp: Date.now()
|
|
729
|
-
};
|
|
730
|
-
logger.debug("Sending message:", fullEvent.type);
|
|
731
|
-
if (transportRef.current === "sse") {
|
|
732
|
-
if (!sseRef.current || sseRef.current.readyState !== EventSource.OPEN) {
|
|
733
|
-
logger.debug("SSE not connected, attempting to connect");
|
|
734
|
-
if (connectionState === "disconnected" && overrideUserId) {
|
|
735
|
-
try {
|
|
736
|
-
await connect(overrideUserId);
|
|
737
|
-
} catch (error2) {
|
|
738
|
-
reject(error2);
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
} else {
|
|
742
|
-
reject(new Error("SSE not connected"));
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
try {
|
|
747
|
-
switch (fullEvent.type) {
|
|
748
|
-
case "message":
|
|
749
|
-
await sendRestMessage("send", {
|
|
750
|
-
orgId: fullEvent.orgId || orgId,
|
|
751
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
752
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
753
|
-
message: fullEvent.message
|
|
754
|
-
});
|
|
755
|
-
break;
|
|
756
|
-
case "typing":
|
|
757
|
-
await sendRestMessage("typing", {
|
|
758
|
-
orgId: fullEvent.orgId || orgId,
|
|
759
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
760
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
761
|
-
typing: true
|
|
762
|
-
});
|
|
763
|
-
break;
|
|
764
|
-
case "stopped_typing":
|
|
765
|
-
await sendRestMessage("typing", {
|
|
766
|
-
orgId: fullEvent.orgId || orgId,
|
|
767
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
768
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
769
|
-
typing: false
|
|
770
|
-
});
|
|
771
|
-
break;
|
|
772
|
-
case "load_chat":
|
|
773
|
-
const loadResponse = await sendRestMessage("load", {
|
|
774
|
-
orgId: fullEvent.orgId || orgId,
|
|
775
|
-
chatKey: fullEvent.chatKey,
|
|
776
|
-
userId: fullEvent.userId || currentUserIdRef.current
|
|
777
|
-
});
|
|
778
|
-
if (loadResponse.success && loadResponse.data?.chat) {
|
|
779
|
-
currentChatKeyRef.current = loadResponse.data.chat.key;
|
|
780
|
-
const chatEvent = {
|
|
781
|
-
type: "load_chat_response",
|
|
782
|
-
orgId: fullEvent.orgId,
|
|
783
|
-
chatKey: loadResponse.data.chat.key,
|
|
784
|
-
userId: fullEvent.userId,
|
|
785
|
-
timestamp: Date.now(),
|
|
786
|
-
data: loadResponse.data
|
|
787
|
-
};
|
|
788
|
-
emit("load_chat_response", chatEvent);
|
|
789
|
-
if (onMessageRef.current) {
|
|
790
|
-
onMessageRef.current(chatEvent);
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
break;
|
|
794
|
-
case "new_chat":
|
|
795
|
-
const createResponse = await sendRestMessage("create", {
|
|
796
|
-
orgId: fullEvent.orgId || orgId,
|
|
797
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
798
|
-
metadata: fullEvent.data
|
|
799
|
-
});
|
|
800
|
-
if (createResponse.success && createResponse.data?.chatKey) {
|
|
801
|
-
currentChatKeyRef.current = createResponse.data.chatKey;
|
|
802
|
-
const newChatEvent = {
|
|
803
|
-
type: "new_chat_created",
|
|
804
|
-
orgId: fullEvent.orgId,
|
|
805
|
-
chatKey: createResponse.data.chatKey,
|
|
806
|
-
userId: fullEvent.userId,
|
|
807
|
-
timestamp: Date.now(),
|
|
808
|
-
data: { chatKey: createResponse.data.chatKey }
|
|
809
|
-
};
|
|
810
|
-
emit("new_chat_created", newChatEvent);
|
|
811
|
-
if (onMessageRef.current) {
|
|
812
|
-
onMessageRef.current(newChatEvent);
|
|
813
|
-
}
|
|
814
|
-
if (chatCreationPromiseRef.current) {
|
|
815
|
-
chatCreationPromiseRef.current.resolve(createResponse.data.chatKey);
|
|
816
|
-
chatCreationPromiseRef.current = null;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
break;
|
|
820
|
-
case "end_chat":
|
|
821
|
-
await sendRestMessage("end", {
|
|
822
|
-
orgId: fullEvent.orgId || orgId,
|
|
823
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
824
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
825
|
-
data: fullEvent.data
|
|
826
|
-
});
|
|
827
|
-
break;
|
|
828
|
-
case "human_agent_joined":
|
|
829
|
-
await sendRestMessage("agent-join", {
|
|
830
|
-
orgId: fullEvent.orgId || orgId,
|
|
831
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
832
|
-
user: fullEvent.data?.user
|
|
833
|
-
});
|
|
834
|
-
break;
|
|
835
|
-
case "human_agent_left":
|
|
836
|
-
await sendRestMessage("agent-leave", {
|
|
837
|
-
orgId: fullEvent.orgId || orgId,
|
|
838
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
839
|
-
user: fullEvent.data?.user
|
|
840
|
-
});
|
|
841
|
-
break;
|
|
842
|
-
// Event types that use the generic /event endpoint
|
|
843
|
-
case "load_agent_context":
|
|
844
|
-
case "skill_activate":
|
|
845
|
-
case "skill_deactivate":
|
|
846
|
-
case "sync_metadata":
|
|
847
|
-
case "sync_user_session":
|
|
848
|
-
case "csat_response":
|
|
849
|
-
case "plan_approved":
|
|
850
|
-
case "plan_rejected":
|
|
851
|
-
await sendRestMessage("event", {
|
|
852
|
-
type: fullEvent.type,
|
|
853
|
-
orgId: fullEvent.orgId || orgId,
|
|
854
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
855
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
856
|
-
data: fullEvent.data
|
|
857
|
-
});
|
|
858
|
-
break;
|
|
859
|
-
default:
|
|
860
|
-
logger.warn("Sending unrecognized event type via generic endpoint:", fullEvent.type);
|
|
861
|
-
await sendRestMessage("event", {
|
|
862
|
-
type: fullEvent.type,
|
|
863
|
-
orgId: fullEvent.orgId || orgId,
|
|
864
|
-
chatKey: fullEvent.chatKey || currentChatKeyRef.current,
|
|
865
|
-
userId: fullEvent.userId || currentUserIdRef.current,
|
|
866
|
-
data: fullEvent.data
|
|
867
|
-
});
|
|
868
|
-
break;
|
|
869
|
-
}
|
|
870
|
-
updateMetrics({ messagesSent: metrics.messagesSent + 1 });
|
|
871
|
-
logger.debug("SSE REST message sent successfully");
|
|
872
|
-
resolve();
|
|
873
|
-
} catch (error2) {
|
|
874
|
-
logger.error("Failed to send SSE REST message:", error2);
|
|
875
|
-
const sendError = {
|
|
876
|
-
code: "SEND_FAILED",
|
|
877
|
-
message: error2 instanceof Error ? error2.message : "Failed to send message",
|
|
878
|
-
retryable: true,
|
|
879
|
-
timestamp: Date.now()
|
|
880
|
-
};
|
|
881
|
-
setError(sendError);
|
|
882
|
-
updateMetrics({ lastError: sendError });
|
|
883
|
-
reject(sendError);
|
|
884
|
-
}
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
|
888
|
-
if (addToQueue(fullEvent)) {
|
|
889
|
-
logger.debug("Message queued, attempting to connect");
|
|
890
|
-
if (connectionState === "disconnected" && overrideUserId) {
|
|
891
|
-
connect(overrideUserId).then(() => resolve()).catch(reject);
|
|
892
|
-
} else {
|
|
893
|
-
resolve();
|
|
894
|
-
}
|
|
895
|
-
} else {
|
|
896
|
-
reject(new Error("Message queue full"));
|
|
897
|
-
}
|
|
898
|
-
return;
|
|
899
|
-
}
|
|
900
|
-
try {
|
|
901
|
-
wsRef.current.send(JSON.stringify(fullEvent));
|
|
902
|
-
updateMetrics({ messagesSent: metrics.messagesSent + 1 });
|
|
903
|
-
logger.debug("Message sent successfully");
|
|
904
|
-
resolve();
|
|
905
|
-
} catch (error2) {
|
|
906
|
-
logger.error("Failed to send message:", error2);
|
|
907
|
-
if (addToQueue(fullEvent)) {
|
|
908
|
-
resolve();
|
|
909
|
-
} else {
|
|
910
|
-
const sendError = {
|
|
911
|
-
code: "SEND_FAILED",
|
|
912
|
-
message: error2 instanceof Error ? error2.message : "Failed to send message",
|
|
913
|
-
retryable: true,
|
|
914
|
-
timestamp: Date.now()
|
|
915
|
-
};
|
|
916
|
-
setError(sendError);
|
|
917
|
-
updateMetrics({ lastError: sendError });
|
|
918
|
-
reject(sendError);
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
});
|
|
922
|
-
},
|
|
923
|
-
[connectionState, connect, addToQueue, logger, metrics, updateMetrics, sendRestMessage, emit, orgId]
|
|
924
|
-
);
|
|
925
|
-
const startNewChat = useCallback(
|
|
926
|
-
(userId, data) => {
|
|
927
|
-
return new Promise((resolve, reject) => {
|
|
928
|
-
if (!userId) {
|
|
929
|
-
reject(new Error("User ID is required"));
|
|
930
|
-
return;
|
|
931
|
-
}
|
|
932
|
-
logger.info("Requesting new chat from server with userId:", userId);
|
|
933
|
-
setStartTime(/* @__PURE__ */ new Date());
|
|
934
|
-
chatCreationPromiseRef.current = { resolve, reject };
|
|
935
|
-
sendMessage(
|
|
936
|
-
{
|
|
937
|
-
type: "new_chat",
|
|
938
|
-
orgId,
|
|
939
|
-
chatKey: "",
|
|
940
|
-
// Server will generate
|
|
941
|
-
userId,
|
|
942
|
-
data: data ?? {}
|
|
943
|
-
},
|
|
944
|
-
userId
|
|
945
|
-
).catch((error2) => {
|
|
946
|
-
chatCreationPromiseRef.current = null;
|
|
947
|
-
reject(error2);
|
|
948
|
-
});
|
|
949
|
-
setTimeout(() => {
|
|
950
|
-
if (chatCreationPromiseRef.current) {
|
|
951
|
-
chatCreationPromiseRef.current = null;
|
|
952
|
-
reject(new Error("Chat creation timed out"));
|
|
953
|
-
}
|
|
954
|
-
}, 3e4);
|
|
955
|
-
});
|
|
956
|
-
},
|
|
957
|
-
[sendMessage, orgId, logger]
|
|
958
|
-
);
|
|
959
|
-
const disconnect = useCallback(
|
|
960
|
-
(intentional = true) => {
|
|
961
|
-
logger.info("Disconnecting", { intentional, transport: transportRef.current });
|
|
962
|
-
intentionalDisconnectRef.current = intentional;
|
|
963
|
-
cleanup();
|
|
964
|
-
setConnectionState("disconnected");
|
|
965
|
-
messageQueueRef.current = [];
|
|
966
|
-
retryCountRef.current = 0;
|
|
967
|
-
mountedRef.current = false;
|
|
968
|
-
currentChatKeyRef.current = void 0;
|
|
969
|
-
currentUserIdRef.current = void 0;
|
|
970
|
-
},
|
|
971
|
-
[cleanup, logger]
|
|
972
|
-
);
|
|
973
|
-
const clearError = useCallback(() => {
|
|
974
|
-
setError(void 0);
|
|
975
|
-
}, []);
|
|
976
|
-
useEffect(() => {
|
|
977
|
-
mountedRef.current = true;
|
|
978
|
-
return () => {
|
|
979
|
-
mountedRef.current = false;
|
|
980
|
-
disconnect(true);
|
|
981
|
-
};
|
|
982
|
-
}, []);
|
|
983
|
-
return {
|
|
984
|
-
connectionState,
|
|
985
|
-
isConnected,
|
|
986
|
-
sendMessage,
|
|
987
|
-
error,
|
|
988
|
-
connect,
|
|
989
|
-
startNewChat,
|
|
990
|
-
startTime,
|
|
991
|
-
disconnect,
|
|
992
|
-
metrics,
|
|
993
|
-
on,
|
|
994
|
-
off,
|
|
995
|
-
clearError
|
|
996
|
-
};
|
|
997
|
-
};
|
|
998
|
-
export {
|
|
999
|
-
useWebSocketChatBase
|
|
1000
|
-
};
|
|
1001
|
-
//# sourceMappingURL=use-websocket-chat-base.mjs.map
|