Files
wxapp_escort/pages/ai/aichat.js
T
liktrae-solo-agentKimi-K3.1-Pro noreply@anthropic.com
d731fc1da3 完善 AI 消息通信与失败恢复
Co-Authored-By: Kimi-K3.1-Pro noreply@anthropic.com
2026-10-24 18:31:46 +08:00

404 lines
11 KiB
JavaScript

const API = require('../../utils/api.js')
Page({
data: {
messages: [],
inputValue: '',
inputFocus: false,
isTyping: false,
scrollToMessage: '',
quickQuestions: [
'陪诊服务的流程是什么?',
'如何预约陪诊服务?',
'陪诊服务收费标准?'
]
},
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()
// 同步自定义 tabBar 选中态(AI客服为第 1 项)
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 1
})
}
},
// 获取陪诊服务问题
async getAiQuickQuestions() {
try {
const res = await API.resource.getAiQuickQuestions()
if (res.code === 0) {
this.setData({ quickQuestions: res.data.aiquick_questions })
}
} catch (err) {
console.error('获取陪诊服务问题失败', err)
}
},
initSocketListeners() {
const socket = getApp().initChatSocket()
this._onSocketMessage = (data) => this.handleSocketMessage(data)
this._onSocketError = (err) => {
console.error('[AIChat] WebSocket error', err)
this.handleAIError('网络连接失败,请检查后重试')
}
this._onSocketClose = () => {
this.handleAIError('连接已断开,请点击失败消息重试')
}
socket.onMessage(this._onSocketMessage)
socket.onError(this._onSocketError)
socket.onClose(this._onSocketClose)
},
removeSocketListeners() {
const socket = getApp().globalData.chatSocket
if (!socket) return
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)
}
},
isCurrentRequest(requestId) {
if (!this.activeRequestId) return false
return !requestId || requestId === this.activeRequestId
},
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())
})
}
this.activeServerId = serverId
this.setData({
messages,
// 正文出现后隐藏等待动画,activeRequestId 仍保留到 end,期间不允许并发提问。
isTyping: false
})
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 (!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 = this.data.messages) {
try {
wx.setStorageSync('ai_chat_history', messages)
} catch (e) {
console.log('保存聊天记录失败', e)
}
},
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 })
},
onQuickQuestionTap(e) {
const question = e.currentTarget.dataset.question
this.setData({ inputValue: question })
this.sendMessage()
},
// 把常见问题清单作为一条 AI 消息铺进会话流(可随时唤起、可重复点选)
showQuickQuestions() {
const questions = this.data.quickQuestions || []
if (!questions.length) return
const questionMessage = {
id: this.createMessageId(),
type: 'ai',
contentType: 'questions',
content: questions,
time: this.formatTime(new Date())
}
const messages = [...this.data.messages, questionMessage]
this.setData({ messages })
this.saveChatHistory(messages)
this.scrollToBottom()
},
sendMessage() {
const content = this.data.inputValue.trim()
if (!content) return
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
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]
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) {
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())
})
this.resetActiveRequest()
this.setData({ messages, isTyping: false })
this.flushChatHistory()
this.scrollToBottom()
},
scrollToBottom() {
setTimeout(() => {
const lastMessage = this.data.messages[this.data.messages.length - 1]
if (lastMessage) {
this.setData({
scrollToMessage: `msg-${lastMessage.id}`
})
}
}, 100)
},
previewImage(e) {
const src = e.currentTarget.dataset.src
wx.previewImage({
urls: [src],
current: src
})
},
formatTime(date) {
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${hours}:${minutes}`
},
clearChat() {
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
wx.showModal({
title: '确认清空',
content: '确定要清空所有聊天记录吗?',
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)
}
})
}
})