完善 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
+4 -21
View File
@@ -23,7 +23,6 @@ App({
onShow() { onShow() {
this.globalData.authReady = this.silentSignin() this.globalData.authReady = this.silentSignin()
this.initChatSocket()
}, },
// 启动期资源统一走 Promise;失败后清空 Promise,页面重试可重新发起请求。 // 启动期资源统一走 Promise;失败后清空 Promise,页面重试可重新发起请求。
@@ -118,28 +117,12 @@ App({
return this.signinPromise return this.signinPromise
}, },
// WebSocket 只服务 AI 页:这里仅懒创建,由页面发送前显式等待连接成功。
initChatSocket() { initChatSocket() {
if (this.globalData.chatSocket) return if (this.globalData.chatSocket) return this.globalData.chatSocket
const socket = new AIChatSocket() this.globalData.chatSocket = new AIChatSocket()
return this.globalData.chatSocket
socket.onOpen(() => {
console.log('[App] Chat WebSocket connected')
})
socket.onClose((res) => {
console.log('[App] Chat WebSocket closed', res)
})
socket.onError((err) => {
console.error('[App] Chat WebSocket error', err)
})
socket.connect().catch((err) => {
console.error('[App] Chat WebSocket connect failed', err)
})
this.globalData.chatSocket = socket
}, },
checkUpdate() { checkUpdate() {
+228 -99
View File
@@ -17,17 +17,22 @@ Page({
messageIdCounter: 0, messageIdCounter: 0,
onLoad() { onLoad() {
this.activeRequestId = ''
this.activeUserMessageId = ''
this.activeServerId = ''
this.activeRequestType = ''
this.historySaveTimer = null
this.loadChatHistory() this.loadChatHistory()
this.initSocketListeners() this.initSocketListeners()
}, },
onUnload() { onUnload() {
this.flushChatHistory()
this.removeSocketListeners() this.removeSocketListeners()
}, },
onShow() { onShow() {
this.getAiQuickQuestions() this.getAiQuickQuestions()
this.setData({ inputFocus: true })
// 同步自定义 tabBar 选中态(AI客服为第 1 项) // 同步自定义 tabBar 选中态(AI客服为第 1 项)
if (typeof this.getTabBar === 'function' && this.getTabBar()) { if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({ this.getTabBar().setData({
@@ -49,86 +54,158 @@ Page({
}, },
initSocketListeners() { initSocketListeners() {
const app = getApp() const socket = getApp().initChatSocket()
const socket = app.globalData.chatSocket
if (!socket) return
this._onSocketMessage = (data) => {
if (data && data.type === 'ai') {
this.handleAIReply(data)
}
}
this._onSocketMessage = (data) => this.handleSocketMessage(data)
this._onSocketError = (err) => { this._onSocketError = (err) => {
console.error('[AIChat] WebSocket error', err) console.error('[AIChat] WebSocket error', err)
this.handleAIError('网络连接失败,请检查网络设置') this.handleAIError('网络连接失败,请检查后重试')
}
this._onSocketClose = () => {
this.handleAIError('连接已断开,请点击失败消息重试')
} }
socket.onMessage(this._onSocketMessage) socket.onMessage(this._onSocketMessage)
socket.onError(this._onSocketError) socket.onError(this._onSocketError)
socket.onClose(this._onSocketClose)
}, },
removeSocketListeners() { removeSocketListeners() {
const app = getApp() const socket = getApp().globalData.chatSocket
const socket = app.globalData.chatSocket
if (!socket) return if (!socket) return
if (this._onSocketMessage) {
socket.onMessage(null) socket.onMessage(null)
}
if (this._onSocketError) {
socket.onError(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) { isCurrentRequest(requestId) {
let messages = null if (!this.activeRequestId) return false
if (this.data.messages.length > 0) { return !requestId || requestId === this.activeRequestId
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
}
}
if (!messages) { handleAIReply(data) {
const aiResponse = { if (!this.activeRequestId) return
id: `msg_${++this.messageIdCounter}`,
_serverId: data.id, 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', type: 'ai',
contentType: 'text', contentType: 'text',
content: data.content || '', content: data.content || '',
time: this.formatTime(new Date()) time: this.formatTime(new Date())
})
} }
if (data.sessionId) { this.activeServerId = serverId
wx.setStorageSync('ai_session_id', data.sessionId)
}
messages = [...this.data.messages, aiResponse]
}
this.setData({ this.setData({
messages: messages, messages,
// 正文出现后隐藏等待动画,activeRequestId 仍保留到 end,期间不允许并发提问。
isTyping: false isTyping: false
}) })
this.saveChatHistory(messages) this.scheduleHistorySave()
this.scrollToBottom() 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() { loadChatHistory() {
try { try {
const history = wx.getStorageSync('ai_chat_history') const history = wx.getStorageSync('ai_chat_history')
if (history && history.length > 0) { if (!Array.isArray(history) || history.length === 0) return
this.setData({ messages: history })
this.scrollToBottom() // 修复旧版本从 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) { } catch (e) {
console.log('加载聊天记录失败', e) console.log('加载聊天记录失败', e)
} }
}, },
saveChatHistory(messages) { saveChatHistory(messages = this.data.messages) {
try { try {
wx.setStorageSync('ai_chat_history', messages) wx.setStorageSync('ai_chat_history', messages)
} catch (e) { } 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) { onInputChange(e) {
this.setData({ inputValue: e.detail.value }) this.setData({ inputValue: e.detail.value })
}, },
@@ -152,7 +245,7 @@ Page({
if (!questions.length) return if (!questions.length) return
const questionMessage = { const questionMessage = {
id: `msg_${++this.messageIdCounter}`, id: this.createMessageId(),
type: 'ai', type: 'ai',
contentType: 'questions', contentType: 'questions',
content: questions, content: questions,
@@ -160,7 +253,7 @@ Page({
} }
const messages = [...this.data.messages, questionMessage] const messages = [...this.data.messages, questionMessage]
this.setData({ messages: messages }) this.setData({ messages })
this.saveChatHistory(messages) this.saveChatHistory(messages)
this.scrollToBottom() this.scrollToBottom()
}, },
@@ -168,67 +261,97 @@ Page({
sendMessage() { sendMessage() {
const content = this.data.inputValue.trim() const content = this.data.inputValue.trim()
if (!content) return if (!content) return
if (this.activeRequestId) {
const userMessage = { wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
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('网络连接失败,请检查网络设置')
return return
} }
if (!socket.isConnected) { const userMessage = {
socket.connect() 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({ this.beginRequest(requestId, userMessage.id)
type: type, this.setData({
content: content, messages,
// 身份以 token 为准,服务端不再接受凭 userId 明文接入 inputValue: '',
token: (user && user.security && user.security.token) || '', isTyping: true
appId: app.globalData.appId
}) })
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) { handleAIError(errorMessage) {
const errorResponse = { if (!this.activeRequestId) return
id: `msg_${++this.messageIdCounter}`,
type: 'ai', // 失败状态挂在原用户消息上,重试不会重复新增一条用户提问。
const messages = this.data.messages.map(item => (
item.id === this.activeUserMessageId ? { ...item, status: 'failed' } : item
))
messages.push({
id: this.createMessageId(),
type: 'system',
contentType: 'text', contentType: 'text',
content: errorMessage, content: errorMessage,
time: this.formatTime(new Date()) 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() this.scrollToBottom()
}, },
@@ -258,16 +381,22 @@ Page({
}, },
clearChat() { clearChat() {
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
wx.showModal({ wx.showModal({
title: '确认清空', title: '确认清空',
content: '确定要清空所有聊天记录吗?', content: '确定要清空所有聊天记录吗?',
success: (res) => { success: async (res) => {
if (res.confirm) { if (!res.confirm) return
this.sendToAI('clear', 'clear')
this.setData({ messages: [] }) const requestId = this.createMessageId('req')
wx.removeStorageSync('ai_chat_history') this.beginRequest(requestId, '', 'clear')
wx.removeStorageSync('ai_session_id') this.setData({ isTyping: true })
} // 等服务端 end 后再清本地历史,避免鉴权或处理失败时两边状态不一致。
await this.sendToAI('clear', 'clear', requestId)
} }
}) })
} }
+11 -3
View File
@@ -35,6 +35,9 @@
wx:key="id" wx:key="id"
id="msg-{{item.id}}" id="msg-{{item.id}}"
> >
<!-- 连接或服务错误是系统状态,不使用用户/AI 头像,也不带 AI 内容声明。 -->
<text wx:if="{{item.type === 'system'}}" class="system-message">{{item.content}}</text>
<block wx:else>
<view class="message-head"> <view class="message-head">
<!-- AI:品牌标记(暖墨线稿);底色与用户侧同构,身份只由图形区分 --> <!-- AI:品牌标记(暖墨线稿);底色与用户侧同构,身份只由图形区分 -->
<view wx:if="{{item.type === 'ai'}}" class="avatar"> <view wx:if="{{item.type === 'ai'}}" class="avatar">
@@ -79,14 +82,19 @@
<t-icon name="chevron-right" size="26rpx" color="#9B4508" /> <t-icon name="chevron-right" size="26rpx" color="#9B4508" />
</view> </view>
</view> </view>
<!-- AI 声明:挂在每条 AI 回复的气泡正下方,替掉原来页面底部那行常驻声明 <!-- AI 声明:本地问题清单和系统错误均不展示。 -->
(它太占底部空间)。放在 .message-content 内,与气泡同宽同左边缘。
问题清单由本地生成、非 AI 内容,故不挂声明 -->
<text <text
wx:if="{{item.type === 'ai' && item.contentType !== 'questions'}}" wx:if="{{item.type === 'ai' && item.contentType !== 'questions'}}"
class="message-note" class="message-note"
>内容由AI生成,仅供参考</text> >内容由AI生成,仅供参考</text>
<text
wx:if="{{item.type === 'user' && item.status === 'failed'}}"
class="message-retry"
bindtap="onRetryMessage"
data-id="{{item.id}}"
>发送失败,点击重试</text>
</view> </view>
</block>
</view> </view>
<!-- AI 正在输入 --> <!-- AI 正在输入 -->
+21
View File
@@ -161,6 +161,27 @@
align-items: flex-end; align-items: flex-end;
} }
/* 系统错误只承担状态提示,不伪装成任一会话角色。 */
.message-item.system {
align-items: center;
}
.system-message {
max-width: 90%;
padding: 8rpx 20rpx;
font-size: 24rpx;
line-height: 1.5;
color: var(--muted);
text-align: center;
}
.message-retry {
padding: 12rpx 0;
font-size: 24rpx;
line-height: 1.5;
color: var(--brand-strong);
}
/* 头像行:头像在左,时间紧跟其右 */ /* 头像行:头像在左,时间紧跟其右 */
.message-head { .message-head {
display: flex; display: flex;
+66 -90
View File
@@ -5,7 +5,6 @@ class AIChatSocket {
constructor(url = `${WS_BASE_URL}/chat`, options = {}) { constructor(url = `${WS_BASE_URL}/chat`, options = {}) {
this.url = url this.url = url
this.options = { this.options = {
timeout: 10000,
heartbeatInterval: 30000, heartbeatInterval: 30000,
autoReconnect: true, autoReconnect: true,
maxReconnectAttempts: 3, maxReconnectAttempts: 3,
@@ -16,7 +15,7 @@ class AIChatSocket {
this.socketTask = null this.socketTask = null
this.isConnected = false this.isConnected = false
this.isConnecting = false this.isConnecting = false
this.messageQueue = [] this.connectPromise = null
this.reconnectAttempts = 0 this.reconnectAttempts = 0
this._openCallback = null this._openCallback = null
@@ -26,15 +25,30 @@ class AIChatSocket {
this._heartbeatTimer = null this._heartbeatTimer = null
} }
// 连接 Promise 单飞:调用方必须 await 成功后再发送,避免断线后的首条消息竞态。
connect() { connect() {
if (this.isConnected || this.isConnecting) { if (this.isConnected) return Promise.resolve()
console.log('[AIChatSocket] Already connected or connecting') if (this.connectPromise) return this.connectPromise
return Promise.resolve()
}
this.isConnecting = true this.isConnecting = true
this.connectPromise = new Promise((resolve, reject) => {
let settled = false
const succeed = () => {
if (settled) return
settled = true
this.isConnecting = false
this.connectPromise = null
resolve()
}
const fail = (err) => {
if (settled) return
settled = true
this.isConnecting = false
this.connectPromise = null
reject(err instanceof Error ? err : new Error('WebSocket 连接失败'))
}
return new Promise((resolve, reject) => { try {
this.socketTask = wx.connectSocket({ this.socketTask = wx.connectSocket({
url: this.url, url: this.url,
header: { header: {
@@ -42,120 +56,93 @@ class AIChatSocket {
...this.options.header ...this.options.header
}, },
protocols: this.options.protocols || [], protocols: this.options.protocols || [],
success: () => { fail
console.log('[AIChatSocket] WebSocket connecting...')
},
fail: (err) => {
this.isConnecting = false
console.error('[AIChatSocket] Connect failed:', err)
reject(err)
}
}) })
} catch (err) {
fail(err)
return
}
if (!this.socketTask) { if (!this.socketTask) {
this.isConnecting = false fail(new Error('SocketTask creation failed'))
reject(new Error('SocketTask creation failed'))
return return
} }
this.socketTask.onOpen(() => { this.socketTask.onOpen(() => {
console.log('[AIChatSocket] Connection opened')
this.isConnected = true this.isConnected = true
this.isConnecting = false
this.reconnectAttempts = 0 this.reconnectAttempts = 0
this._startHeartbeat() this._startHeartbeat()
if (this._openCallback) this._openCallback()
this._flushMessageQueue() succeed()
if (this._openCallback) {
this._openCallback()
}
resolve()
}) })
this.socketTask.onClose((res) => { this.socketTask.onClose((res) => {
console.log('[AIChatSocket] Connection closed:', res)
this.isConnected = false this.isConnected = false
this.isConnecting = false
this._stopHeartbeat() this._stopHeartbeat()
fail(new Error(`WebSocket 已关闭:${res.code || 'unknown'}`))
if (this._closeCallback) { if (this._closeCallback) this._closeCallback(res)
this._closeCallback(res)
}
if (this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts) { if (this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts) {
this._reconnect() this._reconnect()
} }
}) })
this.socketTask.onError((err) => { this.socketTask.onError((err) => {
console.error('[AIChatSocket] WebSocket error:', err) if (this._errorCallback) this._errorCallback(err)
this.isConnected = false fail(new Error(err?.errMsg || 'WebSocket 连接错误'))
this.isConnecting = false
if (this._errorCallback) {
this._errorCallback(err)
}
}) })
this.socketTask.onMessage((res) => { this.socketTask.onMessage((res) => {
if (!this._messageCallback) return
try { try {
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
if (this._messageCallback) {
this._messageCallback(data) this._messageCallback(data)
} } catch (err) {
} catch (e) { this._messageCallback({
if (this._messageCallback) { source: 'system',
this._messageCallback(res.data) type: 'error',
} content: '收到无法解析的服务消息',
id: ''
})
} }
}) })
}) })
return this.connectPromise
} }
send(data) { send(data) {
const message = typeof data === 'string' ? data : JSON.stringify(data) const message = typeof data === 'string' ? data : JSON.stringify(data)
if (!this.isConnected || !this.socketTask) { if (!this.isConnected || !this.socketTask) {
console.log('[AIChatSocket] Not connected, queueing message') return Promise.reject(new Error('WebSocket 尚未连接'))
this.messageQueue.push(message)
return false
} }
return new Promise((resolve, reject) => {
try { try {
this.socketTask.send({ this.socketTask.send({
data: message, data: message,
fail: (err) => { success: resolve,
console.error('[AIChatSocket] Send failed:', err) fail: (err) => reject(new Error(err?.errMsg || '消息发送失败'))
this.messageQueue.push(message) })
} catch (err) {
reject(err)
} }
}) })
return true
} catch (err) {
console.error('[AIChatSocket] Send error:', err)
this.messageQueue.push(message)
return false
}
} }
close() { close() {
this._stopHeartbeat() this._stopHeartbeat()
this.options.autoReconnect = false this.options.autoReconnect = false
const task = this.socketTask
if (this.socketTask) {
this.socketTask.close({
code: 1000,
reason: 'User closed',
fail: (err) => {
console.error('[AIChatSocket] Close failed:', err)
}
})
this.socketTask = null this.socketTask = null
}
this.isConnected = false this.isConnected = false
this.isConnecting = false this.isConnecting = false
this.messageQueue = [] if (task) {
task.close({
code: 1000,
reason: 'User closed',
fail: (err) => console.error('[AIChatSocket] Close failed:', err)
})
}
} }
onOpen(callback) { onOpen(callback) {
@@ -174,21 +161,10 @@ class AIChatSocket {
this._messageCallback = callback this._messageCallback = callback
} }
_flushMessageQueue() {
if (this.messageQueue.length === 0) return
console.log(`[AIChatSocket] Flushing ${this.messageQueue.length} queued messages`)
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift()
this.send(message)
}
}
_reconnect() { _reconnect() {
this.reconnectAttempts++ this.reconnectAttempts++
console.log(`[AIChatSocket] Reconnecting... Attempt ${this.reconnectAttempts}/${this.options.maxReconnectAttempts}`)
setTimeout(() => { setTimeout(() => {
if (!this.options.autoReconnect || this.isConnected) return
this.connect().catch((err) => { this.connect().catch((err) => {
console.error('[AIChatSocket] Reconnect failed:', err) console.error('[AIChatSocket] Reconnect failed:', err)
}) })
@@ -197,17 +173,17 @@ class AIChatSocket {
_startHeartbeat() { _startHeartbeat() {
this._stopHeartbeat() this._stopHeartbeat()
this._heartbeatTimer = setInterval(() => { this._heartbeatTimer = setInterval(() => {
if (this.isConnected && this.socketTask) { if (!this.isConnected || !this.socketTask) return
this.socketTask.send({ this.send({
data: JSON.stringify({ type: 'ping' }), source: 'client',
fail: (err) => { type: 'ping',
content: '',
id: `heartbeat_${Date.now()}`
}).catch((err) => {
console.error('[AIChatSocket] Heartbeat failed:', err) console.error('[AIChatSocket] Heartbeat failed:', err)
this._stopHeartbeat() this._stopHeartbeat()
}
}) })
}
}, this.options.heartbeatInterval) }, this.options.heartbeatInterval)
} }