fix(ai-chat): 修复历史记录加载、WebSocket长连接、服务端消息格式兼容
- 修复 WebSocket message_end 未收到问题:兼容 data.event === 'done' + data.data.conversation_id 嵌套格式 - 修复子组件 onShow/onUnload 不触发:移到页面 index.vue 的页面生命周期中 - 修复 loadHistoryIfNeeded 被重复 methods 块覆盖:合并到同一 methods 块 - 修复历史消息映射字段:msg.query → msg.content,添加 type:'text' - 去掉所有有帮助/没帮助按钮 - CONVERSATION_KEY 改为统一导出常量 - WebSocket 长连接重构 + #ifdef 环境隔离
This commit is contained in:
@@ -3,7 +3,7 @@ import http from './http.js'
|
||||
import store from '@/store/index.js'
|
||||
|
||||
let currentConversationId = null;
|
||||
const CONVERSATION_KEY = 'ai_conversation_id';
|
||||
export const CONVERSATION_KEY = 'ai_conversation_id';
|
||||
|
||||
/**
|
||||
* 获取域名配置参数(避免重复代码)
|
||||
@@ -111,16 +111,24 @@ function ensureWebSocketConnected() {
|
||||
|
||||
if (data.event === 'message') {
|
||||
var text = data.answer || data.content || data.text || '';
|
||||
// 兼容嵌套 data.data.content 格式
|
||||
if (!text && data.data) {
|
||||
text = data.data.content || data.data.answer || '';
|
||||
}
|
||||
wsMessageContent += text;
|
||||
if (wsMessageOnChunk) wsMessageOnChunk(text);
|
||||
} else if (data.event === 'message_end') {
|
||||
var conversationId = data.conversation_id || '';
|
||||
} else if (data.event === 'message_end' || data.event === 'done') {
|
||||
// 兼容两种结束信号:message_end(流结束)或 done(服务端完成)
|
||||
// 兼容两种数据层级:conversation_id 可能在顶层或 data.data 中
|
||||
var conversationId = data.conversation_id || (data.data && data.data.conversation_id) || '';
|
||||
console.log('[AI WS] 流结束信号, event:', data.event, 'type:', data.type, 'conversationId:', conversationId, '当前内存:', currentConversationId);
|
||||
// 保存会话ID(独立函数,不使用 this)
|
||||
if (conversationId) {
|
||||
if (conversationId !== currentConversationId) {
|
||||
currentConversationId = conversationId;
|
||||
try {
|
||||
uni.setStorageSync(CONVERSATION_KEY, conversationId);
|
||||
console.log('[AI WS] 会话ID已持久化到 storage:', conversationId);
|
||||
} catch (e) {
|
||||
console.error('保存会话ID失败:', e);
|
||||
}
|
||||
@@ -133,6 +141,9 @@ function ensureWebSocketConnected() {
|
||||
wsMessageContent = '';
|
||||
if (wsMessageOnComplete) wsMessageOnComplete({ content: content, conversation_id: convId });
|
||||
if (wsMessageResolve) wsMessageResolve({ content: content, conversation_id: convId });
|
||||
} else {
|
||||
// 兜底日志:打印所有未识别的消息类型
|
||||
console.log('[AI WS] 未识别的消息:', JSON.stringify(data).substring(0, 200));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('WebSocket 消息解析失败:', e, '原始数据:', res.data);
|
||||
@@ -507,6 +518,7 @@ export default {
|
||||
if (!params.conversation_id) {
|
||||
throw new Error('会话ID(conversation_id)是必填参数');
|
||||
}
|
||||
console.log('[AI History] 请求历史, conversation_id:', params.conversation_id, 'limit:', params.limit);
|
||||
const requestData = {
|
||||
uniacid: params.uniacid || this.getUniacid(),
|
||||
conversation_id: params.conversation_id,
|
||||
|
||||
Reference in New Issue
Block a user