committed by
trae-solo-agent
co-authored by
Kimi-K3.1-Pro noreply@anthropic.com
parent
d3f399d1ad
commit
d731fc1da3
+232
-103
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+58
-50
@@ -35,58 +35,66 @@
|
||||
wx:key="id"
|
||||
id="msg-{{item.id}}"
|
||||
>
|
||||
<view class="message-head">
|
||||
<!-- AI:品牌标记(暖墨线稿);底色与用户侧同构,身份只由图形区分 -->
|
||||
<view wx:if="{{item.type === 'ai'}}" class="avatar">
|
||||
<image class="avatar-img" src="/images/home-ink.png" mode="aspectFit" />
|
||||
</view>
|
||||
<!-- 用户:人像图标(暖陶土) -->
|
||||
<view wx:else class="avatar">
|
||||
<t-icon name="user-1" size="36rpx" color="#9B4508" />
|
||||
</view>
|
||||
<text class="message-time">{{item.time}}</text>
|
||||
</view>
|
||||
|
||||
<view class="message-content">
|
||||
<view class="message-bubble" wx:if="{{item.contentType !== 'questions'}}">
|
||||
<t-chat-markdown
|
||||
wx:if="{{item.type === 'ai' && item.contentType === 'text'}}"
|
||||
class="message-markdown"
|
||||
content="{{item.content}}"
|
||||
/>
|
||||
<text wx:elif="{{item.contentType === 'text'}}" class="message-text">{{item.content}}</text>
|
||||
<image
|
||||
wx:if="{{item.contentType === 'image'}}"
|
||||
class="message-image"
|
||||
src="{{item.content}}"
|
||||
mode="widthFix"
|
||||
bindtap="previewImage"
|
||||
data-src="{{item.content}}"
|
||||
/>
|
||||
</view>
|
||||
<!-- 常见问题:由「常见问题」按钮触发,把问题清单直接铺进会话流里。
|
||||
复用欢迎区的白卡 + chevron 语言,点一下即发送该问题 -->
|
||||
<view wx:else class="question-list">
|
||||
<view
|
||||
class="quick-item"
|
||||
wx:for="{{item.content}}"
|
||||
wx:for-item="question"
|
||||
wx:key="*this"
|
||||
bindtap="onQuickQuestionTap"
|
||||
data-question="{{question}}"
|
||||
>
|
||||
<text>{{question}}</text>
|
||||
<t-icon name="chevron-right" size="26rpx" color="#9B4508" />
|
||||
<!-- 连接或服务错误是系统状态,不使用用户/AI 头像,也不带 AI 内容声明。 -->
|
||||
<text wx:if="{{item.type === 'system'}}" class="system-message">{{item.content}}</text>
|
||||
<block wx:else>
|
||||
<view class="message-head">
|
||||
<!-- AI:品牌标记(暖墨线稿);底色与用户侧同构,身份只由图形区分 -->
|
||||
<view wx:if="{{item.type === 'ai'}}" class="avatar">
|
||||
<image class="avatar-img" src="/images/home-ink.png" mode="aspectFit" />
|
||||
</view>
|
||||
<!-- 用户:人像图标(暖陶土) -->
|
||||
<view wx:else class="avatar">
|
||||
<t-icon name="user-1" size="36rpx" color="#9B4508" />
|
||||
</view>
|
||||
<text class="message-time">{{item.time}}</text>
|
||||
</view>
|
||||
<!-- AI 声明:挂在每条 AI 回复的气泡正下方,替掉原来页面底部那行常驻声明
|
||||
(它太占底部空间)。放在 .message-content 内,与气泡同宽同左边缘。
|
||||
问题清单由本地生成、非 AI 内容,故不挂声明 -->
|
||||
<text
|
||||
wx:if="{{item.type === 'ai' && item.contentType !== 'questions'}}"
|
||||
class="message-note"
|
||||
>内容由AI生成,仅供参考</text>
|
||||
</view>
|
||||
|
||||
<view class="message-content">
|
||||
<view class="message-bubble" wx:if="{{item.contentType !== 'questions'}}">
|
||||
<t-chat-markdown
|
||||
wx:if="{{item.type === 'ai' && item.contentType === 'text'}}"
|
||||
class="message-markdown"
|
||||
content="{{item.content}}"
|
||||
/>
|
||||
<text wx:elif="{{item.contentType === 'text'}}" class="message-text">{{item.content}}</text>
|
||||
<image
|
||||
wx:if="{{item.contentType === 'image'}}"
|
||||
class="message-image"
|
||||
src="{{item.content}}"
|
||||
mode="widthFix"
|
||||
bindtap="previewImage"
|
||||
data-src="{{item.content}}"
|
||||
/>
|
||||
</view>
|
||||
<!-- 常见问题:由「常见问题」按钮触发,把问题清单直接铺进会话流里。
|
||||
复用欢迎区的白卡 + chevron 语言,点一下即发送该问题 -->
|
||||
<view wx:else class="question-list">
|
||||
<view
|
||||
class="quick-item"
|
||||
wx:for="{{item.content}}"
|
||||
wx:for-item="question"
|
||||
wx:key="*this"
|
||||
bindtap="onQuickQuestionTap"
|
||||
data-question="{{question}}"
|
||||
>
|
||||
<text>{{question}}</text>
|
||||
<t-icon name="chevron-right" size="26rpx" color="#9B4508" />
|
||||
</view>
|
||||
</view>
|
||||
<!-- AI 声明:本地问题清单和系统错误均不展示。 -->
|
||||
<text
|
||||
wx:if="{{item.type === 'ai' && item.contentType !== 'questions'}}"
|
||||
class="message-note"
|
||||
>内容由AI生成,仅供参考</text>
|
||||
<text
|
||||
wx:if="{{item.type === 'user' && item.status === 'failed'}}"
|
||||
class="message-retry"
|
||||
bindtap="onRetryMessage"
|
||||
data-id="{{item.id}}"
|
||||
>发送失败,点击重试</text>
|
||||
</view>
|
||||
</block>
|
||||
</view>
|
||||
|
||||
<!-- AI 正在输入 -->
|
||||
|
||||
@@ -161,6 +161,27 @@
|
||||
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 {
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user