完善 AI 消息通信与失败恢复

Co-Authored-By: Kimi-K3.1-Pro noreply@anthropic.com
This commit is contained in:
lik
2026-10-24 18:31:46 +08:00
committed by trae-solo-agent
co-authored by Kimi-K3.1-Pro noreply@anthropic.com
parent d3f399d1ad
commit d731fc1da3
5 changed files with 401 additions and 284 deletions
+232 -103
View File
@@ -17,17 +17,22 @@ Page({
messageIdCounter: 0,
onLoad() {
this.activeRequestId = ''
this.activeUserMessageId = ''
this.activeServerId = ''
this.activeRequestType = ''
this.historySaveTimer = null
this.loadChatHistory()
this.initSocketListeners()
},
onUnload() {
this.flushChatHistory()
this.removeSocketListeners()
},
onShow() {
this.getAiQuickQuestions()
this.setData({ inputFocus: true })
// 同步自定义 tabBar 选中态(AI客服为第 1 项)
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
@@ -49,86 +54,158 @@ Page({
},
initSocketListeners() {
const app = getApp()
const socket = app.globalData.chatSocket
if (!socket) return
this._onSocketMessage = (data) => {
if (data && data.type === 'ai') {
this.handleAIReply(data)
}
}
const socket = getApp().initChatSocket()
this._onSocketMessage = (data) => this.handleSocketMessage(data)
this._onSocketError = (err) => {
console.error('[AIChat] WebSocket error', err)
this.handleAIError('网络连接失败,请检查网络设置')
this.handleAIError('网络连接失败,请检查后重试')
}
this._onSocketClose = () => {
this.handleAIError('连接已断开,请点击失败消息重试')
}
socket.onMessage(this._onSocketMessage)
socket.onError(this._onSocketError)
socket.onClose(this._onSocketClose)
},
removeSocketListeners() {
const app = getApp()
const socket = app.globalData.chatSocket
const socket = getApp().globalData.chatSocket
if (!socket) return
if (this._onSocketMessage) {
socket.onMessage(null)
}
if (this._onSocketError) {
socket.onError(null)
socket.onMessage(null)
socket.onError(null)
socket.onClose(null)
},
// 所有服务帧在这里集中分发;内部推理和工具帧不展示为医疗建议或 AI 正文。
handleSocketMessage(data) {
if (!data || !data.type) return
switch (data.type) {
case 'ai':
this.handleAIReply(data)
break
case 'end':
if (this.isCurrentRequest(data.id)) this.finishAIResponse()
break
case 'error':
case 'system':
if (this.isCurrentRequest(data.id)) {
this.handleAIError(data.content || '服务处理失败,请稍后重试')
}
break
case 'connected':
case 'pong':
case 'reasoning':
case 'tool':
break
default:
console.warn('[AIChat] Unknown message type:', data.type)
}
},
handleAIReply(data) {
let messages = null
if (this.data.messages.length > 0) {
let lastMessage = this.data.messages[this.data.messages.length - 1]
if (lastMessage.type === 'ai' && lastMessage._serverId === data.id) {
lastMessage.content += data.content || ''
messages = this.data.messages
}
}
isCurrentRequest(requestId) {
if (!this.activeRequestId) return false
return !requestId || requestId === this.activeRequestId
},
if (!messages) {
const aiResponse = {
id: `msg_${++this.messageIdCounter}`,
_serverId: data.id,
handleAIReply(data) {
if (!this.activeRequestId) return
const serverId = data.id || this.activeRequestId
const messages = this.data.messages.slice()
const lastMessage = messages[messages.length - 1]
if (lastMessage?.type === 'ai' && lastMessage._serverId === serverId) {
messages[messages.length - 1] = {
...lastMessage,
content: lastMessage.content + (data.content || '')
}
} else {
messages.push({
id: this.createMessageId(),
_serverId: serverId,
type: 'ai',
contentType: 'text',
content: data.content || '',
time: this.formatTime(new Date())
}
if (data.sessionId) {
wx.setStorageSync('ai_session_id', data.sessionId)
}
messages = [...this.data.messages, aiResponse]
})
}
this.activeServerId = serverId
this.setData({
messages: messages,
messages,
// 正文出现后隐藏等待动画,activeRequestId 仍保留到 end,期间不允许并发提问。
isTyping: false
})
this.saveChatHistory(messages)
this.scheduleHistorySave()
this.scrollToBottom()
},
finishAIResponse() {
const isClearRequest = this.activeRequestType === 'clear'
this.resetActiveRequest()
if (isClearRequest) {
this.setData({ messages: [], isTyping: false })
wx.removeStorageSync('ai_chat_history')
wx.removeStorageSync('ai_session_id')
return
}
this.setData({ isTyping: false })
this.flushChatHistory()
},
resetActiveRequest() {
this.activeRequestId = ''
this.activeUserMessageId = ''
this.activeServerId = ''
this.activeRequestType = ''
},
beginRequest(requestId, userMessageId = '', type = 'chat') {
this.activeRequestId = requestId
this.activeUserMessageId = userMessageId
this.activeServerId = ''
this.activeRequestType = type
},
createMessageId(prefix = 'msg') {
const time = Date.now().toString(36)
const random = Math.random().toString(36).slice(2, 8)
return `${prefix}_${time}_${random}_${++this.messageIdCounter}`
},
loadChatHistory() {
try {
const history = wx.getStorageSync('ai_chat_history')
if (history && history.length > 0) {
this.setData({ messages: history })
this.scrollToBottom()
}
if (!Array.isArray(history) || history.length === 0) return
// 修复旧版本从 0 重新编号造成的缺失或重复键,避免重进后滚动锚点冲突。
const usedIds = new Set()
const messages = history
.filter(item => item && ['ai', 'user', 'system'].includes(item.type))
.map((item) => {
const message = { ...item }
if (!message.id || usedIds.has(message.id)) {
message.id = this.createMessageId()
}
usedIds.add(message.id)
return message
})
this.setData({ messages })
this.saveChatHistory(messages)
this.scrollToBottom()
} catch (e) {
console.log('加载聊天记录失败', e)
}
},
saveChatHistory(messages) {
saveChatHistory(messages = this.data.messages) {
try {
wx.setStorageSync('ai_chat_history', messages)
} catch (e) {
@@ -136,6 +213,22 @@ Page({
}
},
scheduleHistorySave() {
if (this.historySaveTimer) return
this.historySaveTimer = setTimeout(() => {
this.historySaveTimer = null
this.saveChatHistory()
}, 500)
},
flushChatHistory() {
if (this.historySaveTimer) {
clearTimeout(this.historySaveTimer)
this.historySaveTimer = null
}
this.saveChatHistory()
},
onInputChange(e) {
this.setData({ inputValue: e.detail.value })
},
@@ -152,7 +245,7 @@ Page({
if (!questions.length) return
const questionMessage = {
id: `msg_${++this.messageIdCounter}`,
id: this.createMessageId(),
type: 'ai',
contentType: 'questions',
content: questions,
@@ -160,7 +253,7 @@ Page({
}
const messages = [...this.data.messages, questionMessage]
this.setData({ messages: messages })
this.setData({ messages })
this.saveChatHistory(messages)
this.scrollToBottom()
},
@@ -168,67 +261,97 @@ Page({
sendMessage() {
const content = this.data.inputValue.trim()
if (!content) return
const userMessage = {
id: `msg_${++this.messageIdCounter}`,
type: 'user',
contentType: 'text',
content: content,
time: this.formatTime(new Date())
}
const messages = [...this.data.messages, userMessage]
this.setData({
messages: messages,
inputValue: '',
isTyping: true
})
this.saveChatHistory(messages)
this.scrollToBottom()
this.sendToAI(content)
},
sendToAI(content, type = 'chat') {
const app = getApp()
const user = app.globalData.user
const socket = app.globalData.chatSocket
// 先判空再判连接状态,避免 socket 不存在时读取 isConnected 报错
if (!socket) {
this.handleAIError('网络连接失败,请检查网络设置')
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
if (!socket.isConnected) {
socket.connect()
const userMessage = {
id: this.createMessageId(),
type: 'user',
contentType: 'text',
content,
status: '',
time: this.formatTime(new Date())
}
const requestId = this.createMessageId('req')
const messages = [...this.data.messages, userMessage]
socket.send({
type: type,
content: content,
// 身份以 token 为准,服务端不再接受凭 userId 明文接入
token: (user && user.security && user.security.token) || '',
appId: app.globalData.appId
this.beginRequest(requestId, userMessage.id)
this.setData({
messages,
inputValue: '',
isTyping: true
})
this.saveChatHistory(messages)
this.scrollToBottom()
this.sendToAI(content, 'chat', requestId)
},
onRetryMessage(e) {
if (this.activeRequestId) return
const messageId = e.currentTarget.dataset.id
const message = this.data.messages.find(item => item.id === messageId)
if (!message || message.type !== 'user' || message.status !== 'failed') return
const requestId = this.createMessageId('req')
const messages = this.data.messages.map(item => (
item.id === messageId ? { ...item, status: '' } : item
))
this.beginRequest(requestId, messageId)
this.setData({ messages, isTyping: true })
this.saveChatHistory(messages)
this.sendToAI(message.content, 'chat', requestId)
},
async sendToAI(content, type, requestId) {
const app = getApp()
try {
const authenticated = await app.waitForAuth()
if (!authenticated) throw new Error('请先登录')
const user = app.globalData.user
const token = user?.security?.token || ''
if (!token) throw new Error('请先登录')
const socket = app.initChatSocket()
await socket.connect()
await socket.send({
source: 'user',
type,
content,
id: requestId,
token,
appId: app.globalData.appId,
ts: new Date().toISOString()
})
return true
} catch (err) {
this.handleAIError(err.message || '消息发送失败,请稍后重试')
return false
}
},
handleAIError(errorMessage) {
const errorResponse = {
id: `msg_${++this.messageIdCounter}`,
type: 'ai',
if (!this.activeRequestId) return
// 失败状态挂在原用户消息上,重试不会重复新增一条用户提问。
const messages = this.data.messages.map(item => (
item.id === this.activeUserMessageId ? { ...item, status: 'failed' } : item
))
messages.push({
id: this.createMessageId(),
type: 'system',
contentType: 'text',
content: errorMessage,
time: this.formatTime(new Date())
}
const messages = [...this.data.messages, errorResponse]
this.setData({
messages: messages,
isTyping: false
})
this.saveChatHistory(messages)
this.resetActiveRequest()
this.setData({ messages, isTyping: false })
this.flushChatHistory()
this.scrollToBottom()
},
@@ -258,17 +381,23 @@ Page({
},
clearChat() {
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
wx.showModal({
title: '确认清空',
content: '确定要清空所有聊天记录吗?',
success: (res) => {
if (res.confirm) {
this.sendToAI('clear', 'clear')
this.setData({ messages: [] })
wx.removeStorageSync('ai_chat_history')
wx.removeStorageSync('ai_session_id')
}
success: async (res) => {
if (!res.confirm) return
const requestId = this.createMessageId('req')
this.beginRequest(requestId, '', 'clear')
this.setData({ isTyping: true })
// 等服务端 end 后再清本地历史,避免鉴权或处理失败时两边状态不一致。
await this.sendToAI('clear', 'clear', requestId)
}
})
}
})
})