committed by
trae-solo-agent
co-authored by
Kimi-K3.1-Pro noreply@anthropic.com
parent
d3f399d1ad
commit
d731fc1da3
@@ -23,7 +23,6 @@ App({
|
||||
|
||||
onShow() {
|
||||
this.globalData.authReady = this.silentSignin()
|
||||
this.initChatSocket()
|
||||
},
|
||||
|
||||
// 启动期资源统一走 Promise;失败后清空 Promise,页面重试可重新发起请求。
|
||||
@@ -118,28 +117,12 @@ App({
|
||||
return this.signinPromise
|
||||
},
|
||||
|
||||
// WebSocket 只服务 AI 页:这里仅懒创建,由页面发送前显式等待连接成功。
|
||||
initChatSocket() {
|
||||
if (this.globalData.chatSocket) return
|
||||
if (this.globalData.chatSocket) return this.globalData.chatSocket
|
||||
|
||||
const socket = new AIChatSocket()
|
||||
|
||||
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
|
||||
this.globalData.chatSocket = new AIChatSocket()
|
||||
return this.globalData.chatSocket
|
||||
},
|
||||
|
||||
checkUpdate() {
|
||||
|
||||
+228
-99
@@ -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.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,16 +381,22 @@ 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+11
-3
@@ -35,6 +35,9 @@
|
||||
wx:key="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">
|
||||
<!-- AI:品牌标记(暖墨线稿);底色与用户侧同构,身份只由图形区分 -->
|
||||
<view wx:if="{{item.type === 'ai'}}" class="avatar">
|
||||
@@ -79,14 +82,19 @@
|
||||
<t-icon name="chevron-right" size="26rpx" color="#9B4508" />
|
||||
</view>
|
||||
</view>
|
||||
<!-- AI 声明:挂在每条 AI 回复的气泡正下方,替掉原来页面底部那行常驻声明
|
||||
(它太占底部空间)。放在 .message-content 内,与气泡同宽同左边缘。
|
||||
问题清单由本地生成、非 AI 内容,故不挂声明 -->
|
||||
<!-- 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;
|
||||
|
||||
+67
-91
@@ -1,11 +1,10 @@
|
||||
const WS_BASE_URL = 'wss://api.huashengtec.com/health-ws'
|
||||
//const WS_BASE_URL = 'ws://127.0.0.1:9005'
|
||||
// const WS_BASE_URL = 'ws://127.0.0.1:9005'
|
||||
|
||||
class AIChatSocket {
|
||||
constructor(url = `${WS_BASE_URL}/chat`, options = {}) {
|
||||
this.url = url
|
||||
this.options = {
|
||||
timeout: 10000,
|
||||
heartbeatInterval: 30000,
|
||||
autoReconnect: true,
|
||||
maxReconnectAttempts: 3,
|
||||
@@ -16,7 +15,7 @@ class AIChatSocket {
|
||||
this.socketTask = null
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
this.messageQueue = []
|
||||
this.connectPromise = null
|
||||
this.reconnectAttempts = 0
|
||||
|
||||
this._openCallback = null
|
||||
@@ -26,15 +25,30 @@ class AIChatSocket {
|
||||
this._heartbeatTimer = null
|
||||
}
|
||||
|
||||
// 连接 Promise 单飞:调用方必须 await 成功后再发送,避免断线后的首条消息竞态。
|
||||
connect() {
|
||||
if (this.isConnected || this.isConnecting) {
|
||||
console.log('[AIChatSocket] Already connected or connecting')
|
||||
return Promise.resolve()
|
||||
}
|
||||
if (this.isConnected) return Promise.resolve()
|
||||
if (this.connectPromise) return this.connectPromise
|
||||
|
||||
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({
|
||||
url: this.url,
|
||||
header: {
|
||||
@@ -42,120 +56,93 @@ class AIChatSocket {
|
||||
...this.options.header
|
||||
},
|
||||
protocols: this.options.protocols || [],
|
||||
success: () => {
|
||||
console.log('[AIChatSocket] WebSocket connecting...')
|
||||
},
|
||||
fail: (err) => {
|
||||
this.isConnecting = false
|
||||
console.error('[AIChatSocket] Connect failed:', err)
|
||||
reject(err)
|
||||
}
|
||||
fail
|
||||
})
|
||||
} catch (err) {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.socketTask) {
|
||||
this.isConnecting = false
|
||||
reject(new Error('SocketTask creation failed'))
|
||||
fail(new Error('SocketTask creation failed'))
|
||||
return
|
||||
}
|
||||
|
||||
this.socketTask.onOpen(() => {
|
||||
console.log('[AIChatSocket] Connection opened')
|
||||
this.isConnected = true
|
||||
this.isConnecting = false
|
||||
this.reconnectAttempts = 0
|
||||
this._startHeartbeat()
|
||||
|
||||
this._flushMessageQueue()
|
||||
|
||||
if (this._openCallback) {
|
||||
this._openCallback()
|
||||
}
|
||||
resolve()
|
||||
if (this._openCallback) this._openCallback()
|
||||
succeed()
|
||||
})
|
||||
|
||||
this.socketTask.onClose((res) => {
|
||||
console.log('[AIChatSocket] Connection closed:', res)
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
this._stopHeartbeat()
|
||||
|
||||
if (this._closeCallback) {
|
||||
this._closeCallback(res)
|
||||
}
|
||||
|
||||
fail(new Error(`WebSocket 已关闭:${res.code || 'unknown'}`))
|
||||
if (this._closeCallback) this._closeCallback(res)
|
||||
if (this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts) {
|
||||
this._reconnect()
|
||||
}
|
||||
})
|
||||
|
||||
this.socketTask.onError((err) => {
|
||||
console.error('[AIChatSocket] WebSocket error:', err)
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
|
||||
if (this._errorCallback) {
|
||||
this._errorCallback(err)
|
||||
}
|
||||
if (this._errorCallback) this._errorCallback(err)
|
||||
fail(new Error(err?.errMsg || 'WebSocket 连接错误'))
|
||||
})
|
||||
|
||||
this.socketTask.onMessage((res) => {
|
||||
if (!this._messageCallback) return
|
||||
try {
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
if (this._messageCallback) {
|
||||
this._messageCallback(data)
|
||||
}
|
||||
} catch (e) {
|
||||
if (this._messageCallback) {
|
||||
this._messageCallback(res.data)
|
||||
}
|
||||
} catch (err) {
|
||||
this._messageCallback({
|
||||
source: 'system',
|
||||
type: 'error',
|
||||
content: '收到无法解析的服务消息',
|
||||
id: ''
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return this.connectPromise
|
||||
}
|
||||
|
||||
send(data) {
|
||||
const message = typeof data === 'string' ? data : JSON.stringify(data)
|
||||
|
||||
if (!this.isConnected || !this.socketTask) {
|
||||
console.log('[AIChatSocket] Not connected, queueing message')
|
||||
this.messageQueue.push(message)
|
||||
return false
|
||||
return Promise.reject(new Error('WebSocket 尚未连接'))
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
this.socketTask.send({
|
||||
data: message,
|
||||
fail: (err) => {
|
||||
console.error('[AIChatSocket] Send failed:', err)
|
||||
this.messageQueue.push(message)
|
||||
success: resolve,
|
||||
fail: (err) => reject(new Error(err?.errMsg || '消息发送失败'))
|
||||
})
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('[AIChatSocket] Send error:', err)
|
||||
this.messageQueue.push(message)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this._stopHeartbeat()
|
||||
this.options.autoReconnect = false
|
||||
|
||||
if (this.socketTask) {
|
||||
this.socketTask.close({
|
||||
code: 1000,
|
||||
reason: 'User closed',
|
||||
fail: (err) => {
|
||||
console.error('[AIChatSocket] Close failed:', err)
|
||||
}
|
||||
})
|
||||
const task = this.socketTask
|
||||
this.socketTask = null
|
||||
}
|
||||
|
||||
this.isConnected = 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) {
|
||||
@@ -174,21 +161,10 @@ class AIChatSocket {
|
||||
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() {
|
||||
this.reconnectAttempts++
|
||||
console.log(`[AIChatSocket] Reconnecting... Attempt ${this.reconnectAttempts}/${this.options.maxReconnectAttempts}`)
|
||||
|
||||
setTimeout(() => {
|
||||
if (!this.options.autoReconnect || this.isConnected) return
|
||||
this.connect().catch((err) => {
|
||||
console.error('[AIChatSocket] Reconnect failed:', err)
|
||||
})
|
||||
@@ -197,17 +173,17 @@ class AIChatSocket {
|
||||
|
||||
_startHeartbeat() {
|
||||
this._stopHeartbeat()
|
||||
|
||||
this._heartbeatTimer = setInterval(() => {
|
||||
if (this.isConnected && this.socketTask) {
|
||||
this.socketTask.send({
|
||||
data: JSON.stringify({ type: 'ping' }),
|
||||
fail: (err) => {
|
||||
if (!this.isConnected || !this.socketTask) return
|
||||
this.send({
|
||||
source: 'client',
|
||||
type: 'ping',
|
||||
content: '',
|
||||
id: `heartbeat_${Date.now()}`
|
||||
}).catch((err) => {
|
||||
console.error('[AIChatSocket] Heartbeat failed:', err)
|
||||
this._stopHeartbeat()
|
||||
}
|
||||
})
|
||||
}
|
||||
}, this.options.heartbeatInterval)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user