mirror of
https://github.com/Funkoala14/KnowledgeBase_OOIN.git
synced 2025-06-08 05:09:44 +08:00
[dev]chat changed to ws
This commit is contained in:
parent
98b7a08143
commit
72a51d5059
@ -3,7 +3,7 @@ import AppRouter from './router/router';
|
|||||||
import { checkAuthThunk } from './store/auth/auth.thunk';
|
import { checkAuthThunk } from './store/auth/auth.thunk';
|
||||||
import { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { initWebSocket, closeWebSocket } from './services/websocket';
|
import { initWebSocket, closeWebSocket, initChatWebSocket, closeChatWebSocket } from './services/websocket';
|
||||||
import { setWebSocketConnected } from './store/notificationCenter/notificationCenter.slice';
|
import { setWebSocketConnected } from './store/notificationCenter/notificationCenter.slice';
|
||||||
import NavigationGuard from './components/NavigationGuard';
|
import NavigationGuard from './components/NavigationGuard';
|
||||||
|
|
||||||
@ -22,7 +22,7 @@ function App() {
|
|||||||
// 管理WebSocket连接
|
// 管理WebSocket连接
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log(user, isConnected);
|
console.log(user, isConnected);
|
||||||
|
console.log('app 管理WebSocket连接');
|
||||||
// 如果用户已认证但WebSocket未连接,则初始化连接
|
// 如果用户已认证但WebSocket未连接,则初始化连接
|
||||||
if (user && !isConnected) {
|
if (user && !isConnected) {
|
||||||
initWebSocket()
|
initWebSocket()
|
||||||
@ -33,12 +33,15 @@ function App() {
|
|||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error('Failed to initialize WebSocket connection:', error);
|
console.error('Failed to initialize WebSocket connection:', error);
|
||||||
});
|
});
|
||||||
|
initChatWebSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 组件卸载或用户登出时关闭WebSocket连接
|
// 组件卸载或用户登出时关闭WebSocket连接
|
||||||
return () => {
|
return () => {
|
||||||
if (isConnected) {
|
if (isConnected) {
|
||||||
|
console.log('app 卸载或用户登出时关闭WebSocket连接');
|
||||||
closeWebSocket();
|
closeWebSocket();
|
||||||
|
closeChatWebSocket();
|
||||||
dispatch(setWebSocketConnected(false));
|
dispatch(setWebSocketConnected(false));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -112,7 +112,7 @@ const SafeMarkdown = ({ content, isStreaming = false }) => {
|
|||||||
if (!content) return null;
|
if (!content) return null;
|
||||||
|
|
||||||
// 实际显示的内容 - 当流式传输时使用动画内容,否则使用完整内容
|
// 实际显示的内容 - 当流式传输时使用动画内容,否则使用完整内容
|
||||||
const displayContent = isStreaming ? animatedContent : content;
|
const displayContent = content;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ErrorBoundary fallback={renderFallback}>
|
<ErrorBoundary fallback={renderFallback}>
|
||||||
|
@ -1,13 +1,12 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { useDispatch, useSelector } from 'react-redux';
|
import { useDispatch, useSelector } from 'react-redux';
|
||||||
import { resetMessages, resetSendMessageStatus, addMessage } from '../../store/chat/chat.slice';
|
import { resetSendMessageStatus, addMessage, updateMessage } from '../../store/chat/chat.slice';
|
||||||
import { showNotification } from '../../store/notification.slice';
|
import { showNotification } from '../../store/notification.slice';
|
||||||
import { createChatRecord, fetchAvailableDatasets, fetchConversationDetail } from '../../store/chat/chat.thunks';
|
import { createChatRecord, fetchAvailableDatasets, fetchConversationDetail } from '../../store/chat/chat.thunks';
|
||||||
import { fetchKnowledgeBases } from '../../store/knowledgeBase/knowledgeBase.thunks';
|
|
||||||
import SvgIcon from '../../components/SvgIcon';
|
import SvgIcon from '../../components/SvgIcon';
|
||||||
import SafeMarkdown from '../../components/SafeMarkdown';
|
import SafeMarkdown from '../../components/SafeMarkdown';
|
||||||
import ResourceList from '../../components/ResourceList';
|
import ResourceList from '../../components/ResourceList';
|
||||||
import { get } from '../../services/api';
|
import { sendChatMessageViaWebSocket, processChatWebSocketMessage } from '../../services/websocket';
|
||||||
|
|
||||||
export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
@ -22,7 +21,6 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
const currentChat = chatList.find((chat) => chat.conversation_id === currentChatId);
|
const currentChat = chatList.find((chat) => chat.conversation_id === currentChatId);
|
||||||
const messages = currentChat?.messages || [];
|
const messages = currentChat?.messages || [];
|
||||||
const messageStatus = useSelector((state) => state.chat.list.messageStatus);
|
const messageStatus = useSelector((state) => state.chat.list.messageStatus);
|
||||||
const messageError = useSelector((state) => state.chat.list.messageError);
|
|
||||||
const { status: sendStatus, error: sendError } = useSelector((state) => state.chat.sendMessage);
|
const { status: sendStatus, error: sendError } = useSelector((state) => state.chat.sendMessage);
|
||||||
|
|
||||||
// 获取消息资源
|
// 获取消息资源
|
||||||
@ -31,7 +29,6 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
// 使用新的Redux状态结构
|
// 使用新的Redux状态结构
|
||||||
const knowledgeBases = useSelector((state) => state.knowledgeBase.knowledgeBases || []);
|
const knowledgeBases = useSelector((state) => state.knowledgeBase.knowledgeBases || []);
|
||||||
const knowledgeBase = knowledgeBases.find((kb) => kb.id === knowledgeBaseId);
|
const knowledgeBase = knowledgeBases.find((kb) => kb.id === knowledgeBaseId);
|
||||||
const isLoadingKnowledgeBases = useSelector((state) => state.knowledgeBase.loading);
|
|
||||||
|
|
||||||
// 获取可用数据集列表
|
// 获取可用数据集列表
|
||||||
const availableDatasets = useSelector((state) => state.chat.availableDatasets.items || []);
|
const availableDatasets = useSelector((state) => state.chat.availableDatasets.items || []);
|
||||||
@ -65,14 +62,12 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
// 优先使用conversation中的知识库列表
|
// 优先使用conversation中的知识库列表
|
||||||
if (conversation && conversation.datasets && conversation.datasets.length > 0) {
|
if (conversation && conversation.datasets && conversation.datasets.length > 0) {
|
||||||
const datasetIds = conversation.datasets.map((ds) => ds.id);
|
const datasetIds = conversation.datasets.map((ds) => ds.id);
|
||||||
console.log('从会话中获取知识库列表:', datasetIds);
|
|
||||||
setSelectedKnowledgeBaseIds(datasetIds);
|
setSelectedKnowledgeBaseIds(datasetIds);
|
||||||
}
|
}
|
||||||
// 其次使用URL中传入的知识库ID
|
// 其次使用URL中传入的知识库ID
|
||||||
else if (knowledgeBaseId) {
|
else if (knowledgeBaseId) {
|
||||||
// 可能是单个ID或以逗号分隔的多个ID
|
// 可能是单个ID或以逗号分隔的多个ID
|
||||||
const ids = knowledgeBaseId.split(',').map((id) => id.trim());
|
const ids = knowledgeBaseId.split(',').map((id) => id.trim());
|
||||||
console.log('从URL参数中获取知识库列表:', ids);
|
|
||||||
setSelectedKnowledgeBaseIds(ids);
|
setSelectedKnowledgeBaseIds(ids);
|
||||||
}
|
}
|
||||||
}, [conversation, knowledgeBaseId]);
|
}, [conversation, knowledgeBaseId]);
|
||||||
@ -83,7 +78,6 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
|
|
||||||
// 如果已经加载过这个chatId的详情,不再重复加载
|
// 如果已经加载过这个chatId的详情,不再重复加载
|
||||||
if (hasLoadedDetailRef.current[chatId]) {
|
if (hasLoadedDetailRef.current[chatId]) {
|
||||||
console.log('跳过已加载过的会话详情:', chatId);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,18 +86,15 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
|
|
||||||
// 如果是新创建的会话且已经有会话数据,则跳过详情获取
|
// 如果是新创建的会话且已经有会话数据,则跳过详情获取
|
||||||
if (isNewlyCreatedChat && conversation && conversation.conversation_id === chatId) {
|
if (isNewlyCreatedChat && conversation && conversation.conversation_id === chatId) {
|
||||||
console.log('跳过新创建会话的详情获取:', chatId);
|
|
||||||
hasLoadedDetailRef.current[chatId] = true;
|
hasLoadedDetailRef.current[chatId] = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('获取会话详情:', chatId);
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
dispatch(fetchConversationDetail(chatId))
|
dispatch(fetchConversationDetail(chatId))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
console.log('获取会话详情成功:', response);
|
|
||||||
// 标记为已加载
|
// 标记为已加载
|
||||||
hasLoadedDetailRef.current[chatId] = true;
|
hasLoadedDetailRef.current[chatId] = true;
|
||||||
})
|
})
|
||||||
@ -200,21 +191,17 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
if (selectedKnowledgeBaseIds.length > 0) {
|
if (selectedKnowledgeBaseIds.length > 0) {
|
||||||
// 使用已保存的知识库列表
|
// 使用已保存的知识库列表
|
||||||
dataset_id_list = selectedKnowledgeBaseIds.map((id) => id.replace(/-/g, ''));
|
dataset_id_list = selectedKnowledgeBaseIds.map((id) => id.replace(/-/g, ''));
|
||||||
console.log('使用组件状态中的知识库列表:', dataset_id_list);
|
|
||||||
} else if (conversation && conversation.datasets && conversation.datasets.length > 0) {
|
} else if (conversation && conversation.datasets && conversation.datasets.length > 0) {
|
||||||
// 如果已有会话,使用会话中的知识库
|
// 如果已有会话,使用会话中的知识库
|
||||||
dataset_id_list = conversation.datasets.map((ds) => ds.id.replace(/-/g, ''));
|
dataset_id_list = conversation.datasets.map((ds) => ds.id.replace(/-/g, ''));
|
||||||
console.log('使用会话中的知识库列表:', dataset_id_list);
|
|
||||||
} else if (knowledgeBaseId) {
|
} else if (knowledgeBaseId) {
|
||||||
// 如果是新会话,使用当前选择的知识库
|
// 如果是新会话,使用当前选择的知识库
|
||||||
// 可能是单个ID或以逗号分隔的多个ID
|
// 可能是单个ID或以逗号分隔的多个ID
|
||||||
const ids = knowledgeBaseId.split(',').map((id) => id.trim().replace(/-/g, ''));
|
const ids = knowledgeBaseId.split(',').map((id) => id.trim().replace(/-/g, ''));
|
||||||
dataset_id_list = ids;
|
dataset_id_list = ids;
|
||||||
console.log('使用URL参数中的知识库:', dataset_id_list);
|
|
||||||
} else if (availableDatasets.length > 0) {
|
} else if (availableDatasets.length > 0) {
|
||||||
// 如果都没有,尝试使用可用知识库列表中的第一个
|
// 如果都没有,尝试使用可用知识库列表中的第一个
|
||||||
dataset_id_list = [availableDatasets[0].id.replace(/-/g, '')];
|
dataset_id_list = [availableDatasets[0].id.replace(/-/g, '')];
|
||||||
console.log('使用可用知识库列表中的第一个:', dataset_id_list);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dataset_id_list.length === 0) {
|
if (dataset_id_list.length === 0) {
|
||||||
@ -227,35 +214,124 @@ export default function ChatWindow({ chatId, knowledgeBaseId }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('发送消息参数:', {
|
const requestBody = {
|
||||||
dataset_id_list,
|
dataset_id_list: dataset_id_list,
|
||||||
question: inputMessage,
|
question: inputMessage,
|
||||||
conversation_id: chatId,
|
conversation_id: chatId,
|
||||||
});
|
};
|
||||||
|
|
||||||
// 发送消息到服务器
|
console.log('发送消息参数:', requestBody);
|
||||||
|
|
||||||
|
// 同时通过WebSocket发送消息(测试)
|
||||||
|
// 添加用户消息
|
||||||
|
const userMessageId = Date.now().toString();
|
||||||
dispatch(
|
dispatch(
|
||||||
createChatRecord({
|
addMessage({
|
||||||
dataset_id_list: dataset_id_list,
|
id: userMessageId,
|
||||||
question: inputMessage,
|
role: 'user',
|
||||||
conversation_id: chatId,
|
content: inputMessage,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
.unwrap()
|
|
||||||
.then((response) => {
|
// 创建WebSocket测试的AI回复消息ID - 必须先初始化
|
||||||
// 成功发送后,可以执行任何需要的操作
|
const wsMessageId = `ws-${Date.now()}`;
|
||||||
console.log('消息发送成功:', response);
|
let wsMessageContent = '';
|
||||||
|
|
||||||
|
// 添加一个空白的临时消息用于WebSocket流式回复
|
||||||
|
dispatch(
|
||||||
|
addMessage({
|
||||||
|
id: wsMessageId,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '',
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
is_streaming: true,
|
||||||
|
is_websocket: true,
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
);
|
||||||
// 发送失败,显示错误信息
|
|
||||||
console.error('消息发送失败:', error);
|
sendChatMessageViaWebSocket(requestBody, (data) => {
|
||||||
|
try {
|
||||||
|
// 根据消息类型处理不同的响应
|
||||||
|
|
||||||
|
// 处理开始流式传输的消息
|
||||||
|
if (data.message === '开始流式传输') {
|
||||||
|
console.log('WebSocket开始流式传输');
|
||||||
|
// 消息已在上面创建,这里无需重复创建
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理部分内容
|
||||||
|
if (data.message === 'partial') {
|
||||||
|
const newText = data.data.content || '';
|
||||||
|
wsMessageContent += newText;
|
||||||
|
|
||||||
|
// 更新消息内容 - 使用完全替换而不是追加,确保React检测到变化
|
||||||
|
dispatch(
|
||||||
|
updateMessage({
|
||||||
|
id: wsMessageId,
|
||||||
|
content: wsMessageContent,
|
||||||
|
is_streaming: true,
|
||||||
|
updated_at: new Date().toISOString(), // 添加时间戳强制更新
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 触发重新渲染
|
||||||
|
setTimeout(() => {
|
||||||
|
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
}, 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理流结束
|
||||||
|
if (data.message === '完成') {
|
||||||
|
console.log('WebSocket流式传输结束,最终内容:', data.data.content);
|
||||||
|
|
||||||
|
// 使用完整内容替换消息
|
||||||
|
dispatch(
|
||||||
|
updateMessage({
|
||||||
|
id: wsMessageId,
|
||||||
|
content: data.data.content || wsMessageContent,
|
||||||
|
is_streaming: false,
|
||||||
|
updated_at: new Date().toISOString(), // 添加时间戳强制更新
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 触发重新渲染和滚动
|
||||||
|
setTimeout(() => {
|
||||||
|
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
}, 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理错误
|
||||||
|
if (data.code !== 200 && data.code !== 201) {
|
||||||
|
console.error('WebSocket错误:', data.message);
|
||||||
|
dispatch(
|
||||||
|
showNotification({
|
||||||
|
message: `WebSocket错误: ${data.message}`,
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 更新消息显示错误
|
||||||
|
dispatch(
|
||||||
|
updateMessage({
|
||||||
|
id: wsMessageId,
|
||||||
|
content: `Error: ${data.message}`,
|
||||||
|
is_streaming: false,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('处理WebSocket响应失败:', error);
|
||||||
|
// 更新消息显示错误
|
||||||
dispatch(
|
dispatch(
|
||||||
showNotification({
|
updateMessage({
|
||||||
message: `发送失败: ${error}`,
|
id: wsMessageId,
|
||||||
type: 'danger',
|
content: `处理WebSocket响应失败: ${error.message}`,
|
||||||
|
is_streaming: false,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 清空输入框
|
// 清空输入框
|
||||||
setInputMessage('');
|
setInputMessage('');
|
||||||
|
@ -100,7 +100,7 @@ const get = async (url, params = {}) => {
|
|||||||
console.log(`[MOCK MODE] GET ${url}`);
|
console.log(`[MOCK MODE] GET ${url}`);
|
||||||
return await mockGet(url, params);
|
return await mockGet(url, params);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await api.get(url, { ...params });
|
const res = await api.get(url, { ...params });
|
||||||
return res.data;
|
return res.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -12,8 +12,10 @@ const secretKey = import.meta.env.VITE_SECRETKEY;
|
|||||||
const API_URL = import.meta.env.VITE_API_URL || 'http://81.69.223.133:8008';
|
const API_URL = import.meta.env.VITE_API_URL || 'http://81.69.223.133:8008';
|
||||||
// 将 HTTP URL 转换为 WebSocket URL
|
// 将 HTTP URL 转换为 WebSocket URL
|
||||||
const WS_BASE_URL = API_URL.replace(/^http/, 'ws').replace(/\/api\/?$/, '');
|
const WS_BASE_URL = API_URL.replace(/^http/, 'ws').replace(/\/api\/?$/, '');
|
||||||
|
const WS_CHAT_URL = 'ws://81.69.223.133:8008/ws/chat/stream/';
|
||||||
|
|
||||||
let socket = null;
|
let socket = null;
|
||||||
|
let chatSocket = null;
|
||||||
let reconnectTimer = null;
|
let reconnectTimer = null;
|
||||||
let pingInterval = null;
|
let pingInterval = null;
|
||||||
let reconnectAttempts = 0; // 添加重连尝试计数器
|
let reconnectAttempts = 0; // 添加重连尝试计数器
|
||||||
@ -23,6 +25,9 @@ const PING_INTERVAL = 30000; // 30秒发送一次ping
|
|||||||
const MAX_RECONNECT_ATTEMPTS = 3; // 最大重连尝试次数
|
const MAX_RECONNECT_ATTEMPTS = 3; // 最大重连尝试次数
|
||||||
const MAX_GLOBAL_RECONNECT_ATTEMPTS = 3; // 单个会话中允许的总重连次数
|
const MAX_GLOBAL_RECONNECT_ATTEMPTS = 3; // 单个会话中允许的总重连次数
|
||||||
|
|
||||||
|
// 添加的聊天消息回调处理
|
||||||
|
let chatMessageCallback = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 初始化WebSocket连接
|
* 初始化WebSocket连接
|
||||||
* @returns {Promise<WebSocket>} WebSocket连接实例
|
* @returns {Promise<WebSocket>} WebSocket连接实例
|
||||||
@ -366,3 +371,182 @@ const processNotification = (data) => {
|
|||||||
metadata: notificationData.metadata || {},
|
metadata: notificationData.metadata || {},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化聊天WebSocket连接
|
||||||
|
* @returns {Promise<WebSocket>} WebSocket连接实例
|
||||||
|
*/
|
||||||
|
export const initChatWebSocket = () => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// 如果已经有一个连接,先关闭它
|
||||||
|
if (chatSocket && chatSocket.readyState !== WebSocket.CLOSED) {
|
||||||
|
console.log('关闭已有Chat WebSocket连接');
|
||||||
|
chatSocket.close(1000, 'Normal closure, reconnecting');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 从sessionStorage获取token
|
||||||
|
const encryptedToken = sessionStorage.getItem('token');
|
||||||
|
if (!encryptedToken) {
|
||||||
|
console.error('No token found, cannot connect to chat service');
|
||||||
|
reject(new Error('No token found'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let token = '';
|
||||||
|
try {
|
||||||
|
token = CryptoJS.AES.decrypt(encryptedToken, secretKey).toString(CryptoJS.enc.Utf8);
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('Token decryption resulted in empty string');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to decrypt token:', e);
|
||||||
|
reject(new Error('Invalid token'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建WebSocket URL
|
||||||
|
const wsUrl = `${WS_CHAT_URL}?token=${token}`;
|
||||||
|
console.log('正在连接Chat WebSocket...', wsUrl.substring(0, wsUrl.indexOf('?')));
|
||||||
|
|
||||||
|
// 创建WebSocket连接
|
||||||
|
chatSocket = new WebSocket(wsUrl);
|
||||||
|
|
||||||
|
// 设置超时
|
||||||
|
const connectionTimeout = setTimeout(() => {
|
||||||
|
if (chatSocket.readyState !== WebSocket.OPEN) {
|
||||||
|
console.error('Chat WebSocket连接超时');
|
||||||
|
chatSocket.close();
|
||||||
|
reject(new Error('Connection timeout'));
|
||||||
|
}
|
||||||
|
}, 10000); // 10秒超时
|
||||||
|
|
||||||
|
// 连接建立时的处理
|
||||||
|
chatSocket.onopen = () => {
|
||||||
|
console.log('Chat WebSocket 连接成功!');
|
||||||
|
clearTimeout(connectionTimeout);
|
||||||
|
resolve(chatSocket);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 接收消息的处理
|
||||||
|
chatSocket.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
// 解析消息并传递给回调
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
|
||||||
|
if (chatMessageCallback) {
|
||||||
|
chatMessageCallback(message);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('处理Chat WebSocket消息失败:', error, 'Raw message:', event.data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 错误处理
|
||||||
|
chatSocket.onerror = (error) => {
|
||||||
|
console.error('Chat WebSocket连接错误:', error);
|
||||||
|
clearTimeout(connectionTimeout);
|
||||||
|
reject(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 连接关闭时的处理
|
||||||
|
chatSocket.onclose = (event) => {
|
||||||
|
console.log(
|
||||||
|
`Chat WebSocket连接关闭: 代码=${event.code} 原因="${event.reason || '未知'}" 是否干净=${
|
||||||
|
event.wasClean
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
clearTimeout(connectionTimeout);
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error initializing Chat WebSocket:', error);
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过WebSocket发送聊天消息
|
||||||
|
* @param {Object} message 聊天消息
|
||||||
|
* @param {Function} callback 接收消息的回调函数
|
||||||
|
*/
|
||||||
|
export const sendChatMessageViaWebSocket = (message, callback) => {
|
||||||
|
// 保存回调函数
|
||||||
|
chatMessageCallback = callback;
|
||||||
|
|
||||||
|
// 确保WebSocket连接已建立
|
||||||
|
if (!chatSocket || chatSocket.readyState !== WebSocket.OPEN) {
|
||||||
|
console.log('WebSocket未连接,正在初始化连接...');
|
||||||
|
return initChatWebSocket()
|
||||||
|
.then(() => {
|
||||||
|
console.log('WebSocket连接已建立,发送消息:', message);
|
||||||
|
chatSocket.send(JSON.stringify(message));
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Chat WebSocket连接失败:', error);
|
||||||
|
// 如果连接失败,调用回调传递错误
|
||||||
|
if (callback) {
|
||||||
|
callback({
|
||||||
|
code: 500,
|
||||||
|
message: `WebSocket连接失败: ${error.message}`,
|
||||||
|
data: {
|
||||||
|
content: `连接失败: ${error.message}`,
|
||||||
|
is_end: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 如果连接已建立,直接发送消息
|
||||||
|
console.log('WebSocket已连接,直接发送消息:', message);
|
||||||
|
chatSocket.send(JSON.stringify(message));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理聊天WebSocket消息
|
||||||
|
* 流式内容结构类似于:
|
||||||
|
* {
|
||||||
|
* "code": 200,
|
||||||
|
* "message": "开始流式传输" | "partial" | "完成",
|
||||||
|
* "data": {
|
||||||
|
* "content": "消息内容",
|
||||||
|
* "is_end": true/false
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @param {string} data 原始消息数据
|
||||||
|
* @param {Function} callback 处理消息的回调函数
|
||||||
|
*/
|
||||||
|
export const processChatWebSocketMessage = (data, callback) => {
|
||||||
|
try {
|
||||||
|
const message = JSON.parse(data);
|
||||||
|
|
||||||
|
// 调用回调处理消息
|
||||||
|
if (callback) {
|
||||||
|
callback(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('解析Chat WebSocket消息失败:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭聊天WebSocket连接
|
||||||
|
*/
|
||||||
|
export const closeChatWebSocket = () => {
|
||||||
|
// 清除回调
|
||||||
|
chatMessageCallback = null;
|
||||||
|
|
||||||
|
// 关闭连接
|
||||||
|
if (chatSocket) {
|
||||||
|
if (chatSocket.readyState === WebSocket.OPEN || chatSocket.readyState === WebSocket.CONNECTING) {
|
||||||
|
console.log('手动关闭Chat WebSocket连接');
|
||||||
|
chatSocket.close(1000, '用户主动关闭');
|
||||||
|
}
|
||||||
|
chatSocket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Chat WebSocket连接已关闭');
|
||||||
|
};
|
||||||
|
@ -148,7 +148,12 @@ const chatSlice = createSlice({
|
|||||||
const messageIndex = state.list.items[chatIndex].messages.findIndex((msg) => msg.id === id);
|
const messageIndex = state.list.items[chatIndex].messages.findIndex((msg) => msg.id === id);
|
||||||
|
|
||||||
if (messageIndex !== -1) {
|
if (messageIndex !== -1) {
|
||||||
// 更新现有消息
|
// 更新现有消息 - 确保完全替换内容以触发React更新
|
||||||
|
if (updates.content !== undefined) {
|
||||||
|
state.list.items[chatIndex].messages[messageIndex].content = updates.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新其他字段
|
||||||
state.list.items[chatIndex].messages[messageIndex] = {
|
state.list.items[chatIndex].messages[messageIndex] = {
|
||||||
...state.list.items[chatIndex].messages[messageIndex],
|
...state.list.items[chatIndex].messages[messageIndex],
|
||||||
...updates,
|
...updates,
|
||||||
@ -158,6 +163,15 @@ const chatSlice = createSlice({
|
|||||||
if (updates.is_streaming === false) {
|
if (updates.is_streaming === false) {
|
||||||
state.sendMessage.status = 'succeeded';
|
state.sendMessage.status = 'succeeded';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果是最后一条消息且是助手消息,更新会话的last_message
|
||||||
|
if (state.list.items[chatIndex].messages[messageIndex].role === 'assistant') {
|
||||||
|
state.list.items[chatIndex].last_message =
|
||||||
|
updates.content || state.list.items[chatIndex].messages[messageIndex].content;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 如果找不到消息,尝试创建一个新消息
|
||||||
|
console.warn(`消息 ID ${id} 不存在,无法更新`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user