Files
wxapp_escort/pages/ai/aichat.js
T
lik 17a64f10bc style(ui): 统一页首/字号/圆角档位并收口状态色令牌
- 页首:itemorder / guide / contact / attendants 删除与导航栏重复的大标题,统一为「短横 + 一句导语」
- 字号:页面主标题 44、区块标题 34、卡内标题 32;卡片圆角 28;容器内距 32(DESIGN.md 新增 §九)
- 状态色:utils/order.js 只产出语气档,两页胶囊改 .chip-tone-* 读 --status-* 令牌,删除内联 style 与 JS 色值
- 下单:字段标签去浅橙药丸改裸字,医院选择组件同步;搜索/手填输入框去掉旧绿底
- 文案:清除英文大写小标、粘字箭头与中点串,统一细竖线/留白分隔
- 修复:预约记录空值整行剔除、陪诊师卡片与重试态补按下反馈、三处无限动画补减动效回退
- aichat:消息时间改为距上条满 5 分钟才显示
2026-11-13 17:10:55 +08:00

1612 lines
56 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const API = require('../../utils/api.js')
// 录音与识别参数:实时链路按分片上传(frameSize 单位 KB)。
// mp3 48kbps 下 1KB ≈ 0.17 秒一片,接近 arch 文档的 200ms 节奏;
// 分片缺失或链路失败时退回整段 base64 上传,与后端 /health/ai/asr 的白名单一致。
// 注意:开发者工具的录音实际是 WebM/Opus(扩展名仍是 .mp3);真机才是真正的 mp3,
// 两条链路的真实格式都由后端按文件头识别,客户端不需要改上传参数。
const RECORD_FORMAT = {
duration: 60000,
format: 'mp3',
sampleRate: 16000,
numberOfChannels: 1,
encodeBitRate: 48000,
frameSize: 1
}
// 结束录音后等待定稿的上限:超时改走整段兜底,避免界面一直停在「正在识别」
const VOICE_FINISH_TIMEOUT = 15000
// wx.request 请求体约 10MB 上限,base64 膨胀 4/3:
// 音频按后端 10MB 上限收到 7MB,图片按后端 8MB 上限收到 6MB
const MAX_AUDIO_CLIENT_BYTES = 7 * 1024 * 1024
const MAX_IMAGE_CLIENT_BYTES = 6 * 1024 * 1024
// 微信相册/相机原图常有好几兆,超过这个体积先压一档再转 base64
const IMAGE_COMPRESS_THRESHOLD = 2 * 1024 * 1024
// 消息时间的显示间隔:首条必显示,之后只有与上一条相隔 ≥5 分钟才再挂一行时间。
// 每条都挂时间会把气泡读成「日志」,这是聊天界面最常见的噪音来源之一
const MESSAGE_TIME_GAP = 5 * 60 * 1000
// OCR 返回的原文已是 markdown(表格、分段由服务端按原图排版)。
// 这里不再让 agent 二次整理:咨询提示词会把它压缩成 1-3 句,服务端输出护栏还有字符上限,
// 长报告必然丢行;原文直接作为这一轮 AI 回复投递,既完整也少一次生成。
// 指令只作为请求内容发给服务端,不进入本地 messages / 聊天记录。
Page({
data: {
messages: [],
inputValue: '',
inputFocus: false,
isTyping: false,
// 登录态:先判完再渲染提示条,避免静默登录成功前闪一下「未登录」
authChecked: false,
isLoggedIn: false,
scrollToMessage: '',
// 语音识别:点麦克风开录、图标转为录音态,识别文本实时回填输入框;
// 有回显后点麦克风或发送键都能直接发出;还没有回显时再点麦克风则结束录音,
// 等定稿后发送(语音场景不需要用户再点一次发送键)。
// 图片走另一条路:选完即上屏,OCR 原文(已排版为 markdown)直接作为 AI 回复展示。
// 图片与语音的识别/等待阶段都用 isTyping 在 AI 回复区给出等待气泡。
recording: false,
recordTime: '00:00',
// 语音定稿期间的互斥状态:阻止再次录音/发送,底部状态条只在 recording 时显示
isRecognizing: false,
// 实时链路不可用(供应商失败 / 分片格式无法解码)时置 true:
// 状态条补一句「结束后整段转写」,避免用户以为没有识别
voiceRealtimeOff: false,
quickQuestions: [
{ id: '陪诊服务的流程是什么?', text: '陪诊服务的流程是什么?' },
{ id: '如何预约陪诊服务?', text: '如何预约陪诊服务?' },
{ id: '陪诊服务收费标准?', text: '陪诊服务收费标准?' }
]
},
messageIdCounter: 0,
onLoad() {
this.activeRequestId = ''
this.activeUserMessageId = ''
this.activeServerId = ''
this.activeRequestType = ''
this.historySaveTimer = null
this.recordTimer = null
// 本轮语音:流式会话、已收分片、录音文件(分片缺失时的整段兜底)、
// 开录前输入框里已有的文字(识别结果只追加在它后面,不覆盖用户手打的字)
this.voiceStream = null
this.voiceFrames = []
this.voiceStopFile = ''
this.voiceBaseText = ''
// 本轮请求现场与「已为重登重试过」的请求 id:服务端回「请先登录」时原样重发
this.activePayload = null
this.authRetriedRequestId = ''
this.loadChatHistory()
this.initSocketListeners()
this.initRecorder()
},
onHide() {
// 切到后台/别的页还在录音会继续占用麦克风并产生一段无意义音频,直接丢弃
if (this.data.recording) this.cancelVoiceInput()
},
onUnload() {
// 未结束的语音轮次要主动取消,否则服务端会话会一直挂到超时
if (this.voiceStream) {
const stream = this.voiceStream
stream.settled = true
if (!stream.stopSent) {
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
}
this.voiceStream = null
this.clearVoiceFinishTimer()
}
this.flushChatHistory()
this.removeSocketListeners()
this.releaseRecorder()
},
onShow() {
this.getAiQuickQuestions()
this.syncLoginState()
// 同步自定义 tabBar 选中态(陪诊助手为第 1 项)
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 1
})
}
},
// 每次回到本页都重新对齐登录态:「我的」页登录成功、退出登录都会改变它
async syncLoginState() {
const app = getApp()
if (app.globalData.user?._id) {
this.setData({ authChecked: true, isLoggedIn: true })
this.clearStaleLoginMessages()
return
}
try {
await app.waitForAuth()
} catch (e) {
// 静默登录失败按未登录处理,由提示条给出登录入口
}
const loggedIn = !!app.globalData.user?._id
this.setData({
authChecked: true,
isLoggedIn: loggedIn
})
if (loggedIn) this.clearStaleLoginMessages()
},
// 登录恢复后清掉历史里残留的「登录状态已失效」系统提示:
// 它会随聊天记录一起持久化,再次进入时回放出来,看起来像现在仍要重新登录
clearStaleLoginMessages() {
const messages = this.data.messages || []
const next = messages.filter(item => !(item.type === 'system' && item.contentType === 'login'))
if (next.length === messages.length) return
this.setData({ messages: next })
this.saveChatHistory(next)
},
// 登录入口在「我的」页(手机号授权按钮),这里只负责把用户送过去
goLogin() {
wx.switchTab({ url: '/pages/mine/mine' })
},
// 获取陪诊服务问题
async getAiQuickQuestions() {
try {
const res = await API.resource.getAiQuickQuestions()
if (res.code === 0) {
this.setData({
quickQuestions: this.createQuestionItems(res.data.aiquick_questions)
})
}
} catch (err) {
console.error('获取陪诊服务问题失败', err)
}
},
// 问题文本即稳定键;重复问题只保留一项,避免服务端清单造成重复 key。
createQuestionItems(questions) {
const seen = new Set()
return (Array.isArray(questions) ? questions : []).reduce((list, item) => {
const text = typeof item === 'string' ? item : item?.text
if (!text || seen.has(text)) return list
seen.add(text)
list.push({ id: text, text })
return list
}, [])
},
initSocketListeners() {
const socket = getApp().initChatSocket()
this._onSocketMessage = (data) => this.handleSocketMessage(data)
this._onSocketError = (err) => {
console.error('[AIChat] WebSocket error', err)
// 语音识别是另一条链路:连接抖动不该弹「发送失败」的系统消息,交给语音兜底
if (this.voiceStream) {
this.failVoiceStream('网络连接失败,请稍后重试')
return
}
// 图片提问走 HTTP 识别,不依赖聊天 WS:连接抖动不该把正在识别的图片判成失败
if (this.activeRequestType === 'image') return
this.handleAIError('网络连接失败,请检查后重试')
}
this._onSocketClose = () => {
if (this.voiceStream) {
this.failVoiceStream('网络连接已断开,请重试')
return
}
if (this.activeRequestType === 'image') return
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 'asr_partial':
this.handleAsrPartial(data)
break
case 'asr_final':
this.handleAsrFinal(data)
break
case 'asr_error':
this.handleAsrError(data)
break
case 'error':
case 'system':
if (this.isCurrentRequest(data.id)) {
const content = data.content || '服务处理失败,请稍后重试'
// 服务端只认 token:回「请先登录」说明本地这枚 token 已不可用,
// 先静默重登并原样重发(后端重启后旧 token 作废是常见场景),
// 重登失败才落带登录入口的提示
if (content.includes('请先登录')) {
this.handleAuthExpired()
} else {
this.handleAIError(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 || '',
ts: Date.now(),
time: this.formatTime(new Date())
})
}
this.activeServerId = serverId
this.setData({
messages: this.stampMessageTimes(messages),
// 正文出现后隐藏等待动画,activeRequestId 仍保留到 end,期间不允许并发提问。
isTyping: false
})
this.scheduleHistorySave()
this.scrollToBottom()
},
finishAIResponse() {
const isClearRequest = this.activeRequestType === 'clear'
// 清空请求的确认语由服务端下发:只保留这条确认,其余历史随清空一起丢弃
const clearReplyId = isClearRequest ? this.activeServerId : ''
this.resetActiveRequest()
if (isClearRequest) {
const messages = clearReplyId
? this.data.messages.filter(item => item.type === 'ai' && item._serverId === clearReplyId)
: []
this.setData({ messages, isTyping: false })
if (messages.length) {
this.saveChatHistory(messages)
} else {
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 = ''
// 请求已结束,不再保留提问现场(图片原文可能很大)
this.activePayload = null
},
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}`
},
// 给消息补上「这一条要不要显示时间」:首条显示,之后按与上一条的时间差判断。
// ts 缺失的是本改动之前存下的历史,无法判断间隔,沿用原行为显示时间。
stampMessageTimes(list = []) {
let prevTs = 0
return list.map((item) => {
const ts = Number(item.ts) || 0
const showTime = !prevTs || !ts || ts - prevTs >= MESSAGE_TIME_GAP
if (ts) prevTs = ts
return { ...item, showTime }
})
},
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.contentType === 'questions') {
message.content = this.createQuestionItems(message.content)
}
// 旧版本把图片临时路径也存进了历史,这里一并清掉,避免渲染一张失效的图
if (message.contentType === 'image') {
message.content = ''
}
if (!message.id || usedIds.has(message.id)) {
message.id = this.createMessageId()
}
usedIds.add(message.id)
return message
})
this.setData({ messages: this.stampMessageTimes(messages) })
this.saveChatHistory(messages)
this.scrollToBottom()
} catch (e) {
console.log('加载聊天记录失败', e)
}
},
saveChatHistory(messages = this.data.messages) {
try {
// 图片气泡里是本地临时路径,小程序重启后必然失效:只存占位,不写路径
const persisted = messages.map(item => (
item.contentType === 'image' ? { ...item, content: '' } : item
))
wx.setStorageSync('ai_chat_history', persisted)
} 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) {
// 录音/识别中不要覆盖实时结果或抢发半句话
if (this.data.recording || this.data.isRecognizing) {
wx.showToast({ title: '请先结束语音输入', icon: 'none' })
return
}
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: this.createQuestionItems(questions.map(item => item.text)),
ts: Date.now(),
time: this.formatTime(new Date())
}
const messages = this.stampMessageTimes([...this.data.messages, questionMessage])
this.setData({ messages })
this.saveChatHistory(messages)
this.scrollToBottom()
},
/* ===== 语音输入:点麦克风开录,再点一次结束 =====
录音期间不弹任何浮层,输入区始终可见:识别中间结果实时回填输入框,
定稿后也留在输入框,由用户点发送键走聊天 WS。
实时链路走 /chat 的 asr_start / asr_chunk / asr_stop 帧;
分片缺失(如开发者工具)或链路失败时退回整段 base64 识别(/health/ai/asr),
两种环境下都能完成一次转写。 */
// RecorderManager 是全局单例:监听器挂在页面实例上,卸载时必须摘掉,
// 否则回到旧页面实例后 onStop / onFrameRecorded 仍会触发,把音频发给已经销毁的页面
initRecorder() {
if (!wx.getRecorderManager) return
const manager = wx.getRecorderManager()
this.recorderManager = manager
this._onRecorderStop = (res) => this.handleRecorderStop(res)
this._onRecorderError = (err) => this.handleRecorderError(err)
this._onRecorderFrame = (res) => this.handleRecorderFrame(res)
manager.onStop(this._onRecorderStop)
manager.onError(this._onRecorderError)
if (typeof manager.onFrameRecorded === 'function') {
manager.onFrameRecorded(this._onRecorderFrame)
}
},
releaseRecorder() {
const manager = this.recorderManager
if (!manager) return
this.clearRecordTimer()
this.clearVoiceFinishTimer()
// 先摘监听再停止:卸载过程中的 onStop 已经没有接收方,避免误发识别请求
if (typeof manager.offStop === 'function') manager.offStop(this._onRecorderStop)
if (typeof manager.offError === 'function') manager.offError(this._onRecorderError)
if (typeof manager.offFrameRecorded === 'function') {
manager.offFrameRecorded(this._onRecorderFrame)
}
if (this.data.recording) {
try {
manager.stop()
} catch (e) {
// 停止失败无需处理
}
}
this.recorderManager = null
},
// 识别要走鉴权接口且按次计费:未登录、正在回复、正在识别三种情况先挡掉
canUseRecognition() {
if (this.data.isRecognizing) {
wx.showToast({ title: '正在识别,请稍候', icon: 'none' })
return false
}
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return false
}
if (!this.data.isLoggedIn) {
wx.showToast({ title: '请先登录后再使用语音和图片输入', icon: 'none' })
return false
}
return true
},
// 首次使用弹微信授权;已被拒绝过则只能引导去设置页,直接 authorize 不会再弹窗
ensureRecordPermission() {
return new Promise((resolve) => {
if (!wx.getSetting) {
resolve(true)
return
}
wx.getSetting({
success: (res) => {
const granted = res.authSetting ? res.authSetting['scope.record'] : undefined
if (granted) {
resolve(true)
return
}
if (granted === false) {
wx.showModal({
title: '需要麦克风权限',
content: '开启后可以用语音提问,录音只用于本次转写,不会保存',
confirmText: '去设置',
cancelText: '暂不',
success: (modalRes) => {
if (!modalRes.confirm) {
resolve(false)
return
}
wx.openSetting({
success: (setting) => resolve(!!setting.authSetting['scope.record']),
fail: () => resolve(false)
})
},
fail: () => resolve(false)
})
return
}
wx.authorize({
scope: 'scope.record',
success: () => resolve(true),
fail: () => resolve(false)
})
},
fail: () => resolve(false)
})
})
},
// 同一个麦克风入口承担开录、发送与结束:录音中已有回显文字时直接发出
// (与发送键行为一致);还没有回显时再点则结束录音,等定稿后发送
async onMicTap() {
if (this.data.recording) {
const content = String(this.data.inputValue || '').trim()
if (content) {
this.sendVoiceText(content)
} else {
this.stopVoiceInput()
}
return
}
// 授权与服务端建连都是异步的:先挡掉连点,避免启动两段录音
if (this._startingRecord) return
if (!this.canUseRecognition()) return
this._startingRecord = true
try {
const permitted = await this.ensureRecordPermission()
if (!permitted) {
wx.showToast({ title: '未获得麦克风权限', icon: 'none' })
return
}
await this.startVoiceInput()
} finally {
this._startingRecord = false
}
},
async startVoiceInput() {
if (!this.recorderManager) this.initRecorder()
if (!this.recorderManager) {
wx.showToast({ title: '当前微信版本不支持录音', icon: 'none' })
return
}
// 实时识别共用聊天 WS:先确认登录并连上,再开录音,
// 避免用户说完才发现连不上,白白占用一次麦克风
const app = getApp()
let authenticated = false
try {
authenticated = await app.waitForAuth()
} catch (e) {
authenticated = false
}
const token = app.globalData.user?.security?.token || ''
if (!authenticated || !token) {
wx.showToast({ title: '请先登录后再使用语音输入', icon: 'none' })
return
}
const socket = app.initChatSocket()
try {
await socket.connect()
} catch (err) {
wx.showToast({ title: '网络连接失败,请稍后重试', icon: 'none' })
return
}
const streamId = this.createMessageId('asr')
const stream = {
id: streamId,
socket,
// 实时链路不可用时置位(服务端回了 asr_error):录制继续,结束统一整段转写
streamingDisabled: false,
stopSent: false,
settled: false,
failed: false,
// 已上传的分片数 / 是否收到过中间结果:用于判断实时回显是否真的在跑
chunkCount: 0,
partialSeen: false,
// 调试用:分片累计字节、已回显的中间结果条数、开录时间
chunkBytes: 0,
partialCount: 0,
startedAt: Date.now()
}
this.voiceStream = stream
this.voiceFrames = []
this.voiceStopFile = ''
// 识别结果只追加在开录前已经打好的文字后面,不覆盖用户手打的内容
this.voiceBaseText = String(this.data.inputValue || '').trim()
this.setData({
recording: true,
recordTime: '00:00',
isRecognizing: false,
voiceRealtimeOff: false,
inputFocus: false
})
wx.hideKeyboard()
// 先声明本轮,再推分片;服务端按 id 关联并实时回 partial
socket.send({
type: 'asr_start',
id: streamId,
token,
format: RECORD_FORMAT.format,
sampleRate: RECORD_FORMAT.sampleRate,
channels: RECORD_FORMAT.numberOfChannels
}).catch(() => this.failVoiceStream('语音识别连接失败,请稍后重试'))
console.info('[AIChat] 语音流开始', {
id: streamId,
format: RECORD_FORMAT.format,
sampleRate: RECORD_FORMAT.sampleRate,
channels: RECORD_FORMAT.numberOfChannels,
encodeBitRate: RECORD_FORMAT.encodeBitRate,
// frameSize 单位 KB:按码率折算每片时长,便于核对是否接近 200ms
frameSizeKB: RECORD_FORMAT.frameSize,
frameMs: Math.round(RECORD_FORMAT.frameSize * 1024 * 8 / RECORD_FORMAT.encodeBitRate * 1000)
})
const startedAt = Date.now()
this.clearRecordTimer()
this.recordTimer = setInterval(() => {
const elapsed = Date.now() - startedAt
this.setData({ recordTime: this.formatDuration(elapsed) })
// 到 60 秒自动收口,不依赖用户记得再点一次
if (elapsed >= RECORD_FORMAT.duration) this.stopVoiceInput()
}, 1000)
try {
this.recorderManager.start(RECORD_FORMAT)
} catch (err) {
this.failVoiceStream('录音启动失败,请重试')
return
}
// 分片回调没有触发时不可能实时回显:2.5 秒后仍无分片就在状态条提示。
// 开发者工具的首帧通常要 1.2s 左右才到,窗口太短会误报「结束后整段转写」
setTimeout(() => {
const current = this.voiceStream
if (!current || current !== stream || !this.data.recording) return
if (current.chunkCount > 0) return
console.warn('[AIChat] 录音分片回调没有触发,实时转写不可用;请确认已用最新代码重新编译')
this.setData({ voiceRealtimeOff: true })
}, 2500)
},
// 每一帧先落本地再上传:流式链路失败时还能拿已采集的音频整段兜底。
// 客户端不再判断容器:真机 mp3 分片由供应商直接识别,开发者工具的 WebM 分片
// 由服务端边收边解码成 PCM,两种格式都能实时出中间结果。
handleRecorderFrame(res = {}) {
const stream = this.voiceStream
if (!this.data.recording || !stream || stream.settled) return
const frame = res.frameBuffer
if (!frame || !frame.byteLength) return
const bytes = frame.byteLength || frame.length || 0
this.voiceFrames.push(frame)
stream.chunkCount += 1
const uploading = !(stream.streamingDisabled || stream.failed)
if (stream.chunkCount === 1) {
// 首帧前 16 字节十六进制:确认分片是完整容器(WebM/mp3)还是裸编码帧
let firstBytes = ''
try {
const view = new Uint8Array(frame, 0, Math.min(frame.byteLength, 16))
firstBytes = Array.from(view)
.map((b) => b.toString(16).padStart(2, '0'))
.join(' ')
} catch (e) {
firstBytes = 'unavailable'
}
console.info('[AIChat] 收到首个录音分片', {
bytes,
firstBytes,
elapsedMs: Date.now() - stream.startedAt,
uploading
})
// 分片已到 = 实时链路具备回显条件:撤掉「结束后整段转写」的误报提示
if (this.data.voiceRealtimeOff) this.setData({ voiceRealtimeOff: false })
}
if (!uploading) {
if (stream.chunkCount === 1) {
console.warn('[AIChat] 实时链路已关闭,分片只落本地用于整段兜底')
}
return
}
stream.chunkBytes += bytes
if (stream.chunkCount % 5 === 0) {
console.info('[AIChat] 分片已上传', {
count: stream.chunkCount,
totalBytes: stream.chunkBytes
})
}
const base64 = wx.arrayBufferToBase64 ? wx.arrayBufferToBase64(frame) : ''
if (!base64) {
this.failVoiceStream('当前微信版本不支持实时语音识别')
return
}
stream.socket.send({
type: 'asr_chunk',
id: stream.id,
audio: base64
}).catch(() => this.failVoiceStream('语音识别连接中断,请重试'))
},
// 录音中直接发出:点麦克风或发送键共用。
// 以输入框当前回显为准,不再等服务端定稿;本轮语音会话随即取消,
// 稍后即便还有 asr_final 到达,也会因为 voiceStream 已摘掉而被忽略。
// 发送后录音态、计时与状态条统一复位,语音键回到普通态
sendVoiceText(content) {
const stream = this.voiceStream
if (stream && !stream.settled) {
stream.settled = true
stream.stopSent = true
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
}
this.stopRecorderSilently()
this.resetVoiceState(true)
this.dispatchMessage(content)
},
// 没有回显文字时再点麦克风 = 结束录音:停止采集并让服务端定稿,定稿后直接发出。
// 识别期间不再显示底部状态条,改用 AI 回复区的等待气泡(isTyping)
stopVoiceInput() {
if (!this.data.recording) return
this.clearRecordTimer()
this.setData({ recording: false, recordTime: '00:00', isRecognizing: true, isTyping: true })
this.scrollToBottom()
try {
this.recorderManager.stop()
} catch (e) {
// 停止失败时仍按已收分片/录音文件收尾
}
const stream = this.voiceStream
if (!stream) {
this.resetVoiceState(true)
return
}
// 实时链路已被关闭(WebM 分片或供应商失败):直接走整段转写
if (stream.streamingDisabled) {
this.transcribeVoiceBatch('语音识别失败,请稍后重试')
return
}
// 一帧都没上传:实时链路根本没有数据,直接走整段,避免一次空定稿往返
if (!stream.chunkCount) {
console.warn('[AIChat] 本轮没有可上传的录音分片,直接走整段转写')
this.setData({ voiceRealtimeOff: true })
this.transcribeVoiceBatch('未收到录音分片')
return
}
if (stream.stopSent) return
stream.stopSent = true
stream.socket.send({ type: 'asr_stop', id: stream.id })
.catch(() => this.transcribeVoiceBatch('语音识别连接中断,请重试'))
// 供应商迟迟不回定稿时改走整段兜底,界面不能一直停在「正在识别」
this.voiceFinishTimer = setTimeout(() => {
this.transcribeVoiceBatch('语音识别超时,请重试')
}, VOICE_FINISH_TIMEOUT)
},
// 状态条里的主动取消入口;页面隐藏时直接调用 cancelVoiceInput,不额外弹提示
onCancelVoiceTap() {
if (!this.data.recording) return
this.cancelVoiceInput()
wx.showToast({ title: '已取消语音输入', icon: 'none' })
},
// 页面隐藏 / 主动放弃:中止本轮,保留输入框当前文字,便于修改后继续发送
cancelVoiceInput() {
const stream = this.voiceStream
if (stream && !stream.stopSent) {
stream.stopSent = true
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
}
this.stopRecorderSilently()
this.resetVoiceState(true)
},
clearRecordTimer() {
if (this.recordTimer) {
clearInterval(this.recordTimer)
this.recordTimer = null
}
},
clearVoiceFinishTimer() {
if (this.voiceFinishTimer) {
clearTimeout(this.voiceFinishTimer)
this.voiceFinishTimer = null
}
},
// 停采但不改输入框内容:失败分支要靠已回填的中间结果让用户自己决定是否重录
stopRecorderSilently() {
this.clearRecordTimer()
if (this.recorderManager) {
try {
this.recorderManager.stop()
} catch (e) {
// 停止失败无需处理
}
}
if (this.data.recording) this.setData({ recording: false, recordTime: '00:00' })
},
// 录音异常(权限被系统拒绝、被来电打断等):中止本轮并给出可操作的提示
handleRecorderError(err) {
const message = String(err && err.errMsg ? err.errMsg : '')
const denied = /auth|permission|denied/i.test(message)
const title = denied ? '未获得麦克风权限,请在设置中开启' : '录音失败,请重试'
if (this.data.recording && this.voiceStream) {
this.failVoiceStream(title)
return
}
this.resetVoiceState(true)
wx.showToast({ title, icon: 'none' })
},
// 整段转写:实时链路不可用(WebM 分片 / 供应商失败 / 超时 / 空定稿)时的兜底。
// 优先用 onStop 的完整录音文件,失败场景下的分片往往只是半句话的前缀;
// 文件由录音器一次性封装(真机 mp3、工具 WebM),后端按文件头识别并转码
async transcribeVoiceBatch(message) {
const stream = this.voiceStream
if (!stream || stream.settled) return
stream.settled = true
this.clearVoiceFinishTimer()
if (this.data.recording) this.stopRecorderSilently()
// 服务端这一轮不再需要定稿:直接取消,避免供应商继续处理半截音频
stream.stopSent = true
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
this.setData({ recording: false, recordTime: '00:00', isRecognizing: true, isTyping: true })
this.scrollToBottom()
try {
const filePath = await this.waitRecordFile(2500)
let audio = ''
if (filePath) {
audio = await this.readFileBase64(filePath)
} else if (this.voiceFrames.length) {
// 极少数平台 onStop 不给文件:退而用已收分片拼回原始字节流
audio = wx.arrayBufferToBase64(this.mergeFrames(this.voiceFrames))
}
this.voiceFrames = []
if (!audio) throw new Error(message)
if (this.estimateBytes(audio) > MAX_AUDIO_CLIENT_BYTES) {
throw new Error('录音过大,请缩短语音后重试')
}
// 后端按文件头识别真实容器(工具里的 WebM 也能转),这里仍声明录制参数
const reply = await API.ai.asr({
audio,
format: RECORD_FORMAT.format,
sampleRate: RECORD_FORMAT.sampleRate,
channels: RECORD_FORMAT.numberOfChannels
})
if (!reply || reply.code !== 0) {
throw new Error((reply && reply.msg) || message)
}
const text = String((reply.data && reply.data.text) || '').trim()
if (!text) throw new Error('未识别到语音内容,请再说一次')
this.finishVoiceInput(text)
} catch (err) {
this.resetVoiceState(true)
this.toastRecognitionError(err, '语音')
}
},
waitRecordFile(timeout = 2500) {
if (this.voiceStopFile) return Promise.resolve(this.voiceStopFile)
return new Promise((resolve) => {
const startedAt = Date.now()
const check = () => {
if (this.voiceStopFile || Date.now() - startedAt >= timeout) {
resolve(this.voiceStopFile || '')
return
}
setTimeout(check, 100)
}
check()
})
},
mergeFrames(frames) {
const total = frames.reduce((sum, frame) => sum + frame.byteLength, 0)
const merged = new Uint8Array(total)
let offset = 0
frames.forEach((frame) => {
merged.set(new Uint8Array(frame), offset)
offset += frame.byteLength
})
return merged.buffer
},
// 流式中间结果:逐字回填输入框,前缀保留用户开录前手打的内容
handleAsrPartial(data) {
const stream = this.voiceStream
if (!stream || stream.settled || !data || data.id !== stream.id) {
// 关联不上就丢弃:多端/上一轮的中间结果不能污染当前输入框
if (data && data.id) {
console.info('[AIChat] 丢弃无关的中间结果', { id: data.id, current: stream && stream.id })
}
return
}
// 已经结束录音(正在定稿)就不再覆盖输入框,避免干扰用户此刻的编辑
if (!this.data.recording) {
console.info('[AIChat] 已结束录音,忽略中间结果', { chars: String(data.content || '').length })
return
}
const partial = String(data.content || '')
if (!partial) return
stream.partialCount += 1
const isFirst = !stream.partialSeen
stream.partialSeen = true
console.info(isFirst ? '[AIChat] 实时识别首条中间结果(开始逐字回填)' : '[AIChat] 实时回显中间结果', {
seq: stream.partialCount,
elapsedMs: Date.now() - stream.startedAt,
chars: partial.length,
text: partial
})
this.setData({
inputValue: this.voiceBaseText ? `${this.voiceBaseText}${partial}` : partial,
// 中间结果已到:清掉「结束后整段转写」的兜底提示
voiceRealtimeOff: false
})
},
// 流式定稿:回填输入框后直接发送,不再弹确认面板
handleAsrFinal(data) {
const stream = this.voiceStream
if (!stream || stream.settled || !data || data.id !== stream.id) return
this.clearVoiceFinishTimer()
const text = String(data.content || '').trim()
console.info('[AIChat] 实时识别定稿', {
elapsedMs: Date.now() - stream.startedAt,
chunks: stream.chunkCount,
uploadedBytes: stream.chunkBytes,
partialCount: stream.partialCount,
chars: text.length,
text
})
if (!text) {
this.transcribeVoiceBatch('未识别到语音内容,请再说一次')
return
}
this.finishVoiceInput(text)
},
// 流式失败(配置缺失 / 供应商异常 / 断流):不再中途弹错,悄悄降级
async handleAsrError(data) {
const stream = this.voiceStream
if (!stream || stream.settled || !data || data.id !== stream.id) return
this.clearVoiceFinishTimer()
const message = String(data.content || '语音识别失败,请稍后重试')
// 登录失效不再走兜底:整段接口同样会 401,只会多花一次上传。
// 先静默重登(后端重启后旧 token 会整体作废),恢复后提示用户重新录音
if (/请先登录/.test(message)) {
this.stopRecorderSilently()
this.resetVoiceState(true)
if (await this.reauthSilently()) {
wx.showToast({ title: '登录已恢复,请重新录音', icon: 'none' })
} else {
wx.showToast({ title: '登录状态已失效,请重新登录', icon: 'none' })
}
return
}
// 用户还在说:关闭实时链路、保留已回填的中间结果,继续录完整句,
// 结束时统一走整段转写。中途弹「识别失败」会打断说话,也会丢弃后半句
if (this.data.recording) {
console.warn('[AIChat] 实时识别中断,改为结束后整段转写:', message)
stream.failed = true
stream.streamingDisabled = true
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
this.setData({ voiceRealtimeOff: true })
return
}
// 已经结束录音、正在等待定稿:直接整段兜底
this.transcribeVoiceBatch(message)
},
// 识别结束:结果与开录前的文字合并后落到输入框,并立即发送出去。
// 语音是一句话说完就发,不再让用户为同一句话再点一次发送键。
finishVoiceInput(text) {
const base = this.voiceBaseText || ''
this.resetVoiceState(true)
const content = `${base}${text}`.trim()
if (!content) return
this.dispatchMessage(content)
},
// 收尾:清掉本轮会话与缓冲;keepText=false 时把输入框还原成开录前的内容
resetVoiceState(keepText = true) {
this.clearVoiceFinishTimer()
this.clearRecordTimer()
const stream = this.voiceStream
this.voiceStream = null
if (stream) stream.settled = true
this.voiceFrames = []
this.voiceStopFile = ''
const base = this.voiceBaseText
this.voiceBaseText = ''
this.setData({
recording: false,
recordTime: '00:00',
isRecognizing: false,
// 识别失败/取消时收起 AI 回复区的等待气泡;
// 正常定稿会紧接着走 dispatchMessage,那里会重新置为 true
isTyping: false,
voiceRealtimeOff: false,
...(keepText ? {} : { inputValue: base })
})
},
// 连接类失败发生在录音途中:停采、中止会话,已回填的中间结果保留给用户修改或重录
failVoiceStream(message) {
const stream = this.voiceStream
if (!stream || stream.settled) return
stream.failed = true
stream.settled = true
this.stopRecorderSilently()
stream.socket.send({ type: 'asr_cancel', id: stream.id }).catch(() => {})
this.resetVoiceState(true)
wx.showToast({ title: message, icon: 'none' })
},
// 流式路径下 onStop 只留文件:分片齐全时用不到,分片缺失时才拿来做整段兜底
handleRecorderStop(res = {}) {
this.clearRecordTimer()
if (this.voiceStream) {
this.voiceStopFile = res.tempFilePath || ''
}
},
/* ===== 图片输入:选完即上屏,识别结果直接作为 AI 回复 =====
与语音不同,这里没有「确认再发送」:图片本身就是用户的原话,
先用图片气泡把这一轮坐实,等 OCR 返回文本后直接落成一条 AI 消息。
图片路径只存在页面内存里(不写 storage),重启后历史里只留 [图片] 占位。 */
onImageTap() {
// 录音中不打开相册/相机:同时采集会让两路输入互相抢占,也会打断本轮识别
if (this.data.recording) {
wx.showToast({ title: '请先结束语音输入', icon: 'none' })
return
}
if (!this.canUseRecognition()) return
wx.chooseMedia({
count: 1,
mediaType: ['image'],
// 同时给出「拍照」和「从相册选择」,避免多一层自绘菜单
sourceType: ['album', 'camera'],
sizeType: ['compressed'],
camera: 'back',
success: (res) => {
const file = res.tempFiles ? res.tempFiles[0] : null
if (file) this.sendImageMessage(file)
},
fail: (err) => {
// 用户主动取消不是错误,不弹提示
if (err && /cancel/i.test(err.errMsg || '')) return
wx.showToast({ title: '打开相册或相机失败,请重试', icon: 'none' })
}
})
},
// 先上屏再识别:识别期间只保留 AI 回复区的等待动画(isTyping),
// 不再额外弹「正在识别并发送…」的状态条,避免同一件事出现两个提示
sendImageMessage(file) {
const userMessage = {
id: this.createMessageId(),
type: 'user',
contentType: 'image',
content: file.tempFilePath,
status: '',
ts: Date.now(),
time: this.formatTime(new Date())
}
const requestId = this.createMessageId('req')
const messages = this.stampMessageTimes([...this.data.messages, userMessage])
this.beginRequest(requestId, userMessage.id, 'image')
this.setData({
messages,
isTyping: true
})
this.saveChatHistory(messages)
this.scrollToBottom()
this.runImageRecognition({
messageId: userMessage.id,
file
})
},
// 首次发送与失败重试共用这一段:唯一差别是重试时文件信息从消息上取
async runImageRecognition({ messageId, file }) {
try {
const imagePath = await this.resolveImageFile(file)
// 压缩后是一条新文件:气泡换成本次真正送去识别的图,重试也从这条路径走。
// 已压过一档的图把 size 归零,避免重试时再压一次
this.patchMessage(messageId, {
content: imagePath,
_imageSize: imagePath === file.tempFilePath ? (file.size || 0) : 0,
_imageWidth: file.width || 0,
_imageHeight: file.height || 0
})
const base64 = await this.readFileBase64(imagePath)
if (this.estimateBytes(base64) > MAX_IMAGE_CLIENT_BYTES) {
throw new Error('图片过大,请压缩或重新拍摄')
}
const reply = await API.ai.ocr({
image: base64,
mime: this.resolveImageMime(imagePath),
width: file.width || 0,
height: file.height || 0,
kind: 'auto'
})
this.handleImageReply(reply)
} catch (err) {
this.handleImageError(err)
}
},
// 识别成功:OCR 原文(服务端已排版为 markdown)直接作为 AI 回复落在图片下方。
// 以独立的 format 类型投递,服务端只把原文并入会话上下文并原样回显,
// 既保证长报告不被提示词压缩 / 护栏截断,也方便用户接着追问报告里的指标。
handleImageReply(reply) {
if (!reply || reply.code !== 0) {
// request 层已尝试静默重登,仍回 401 说明本地 token 确实失效:
// 走登录提示(图片消息置为 blocked,不挂重试,避免反复失败)
if (reply && reply.code === 401) {
this.setData({ isLoggedIn: false })
this.handleLoginRequired('登录状态已失效,请重新登录后再试', false)
return
}
this.handleImageError(new Error((reply && reply.msg) || '图片识别失败,请稍后重试'))
return
}
const text = String((reply.data && reply.data.text) || '').trim()
if (!text) {
this.handleImageError(new Error('未识别到图片内容,请换个角度拍摄或上传更清晰的图片'))
return
}
// OCR 已完成,原文交给聊天 WS 回显;activeRequestType 用 format,
// 连接失败才会走 handleAIError,而不是被图片链路直接吞掉。
const imageMessageId = this.activeUserMessageId
const requestId = this.createMessageId('req')
this.beginRequest(requestId, imageMessageId, 'format')
this.setData({ isTyping: true })
this.scrollToBottom()
this.sendToAI(text, 'format', requestId)
},
// 失败复用聊天失败态:标记挂在图片气泡上,点「重试」重走识别
handleImageError(err) {
const raw = String((err && err.message) || (err && err.errMsg) || '')
const friendly = /request:fail|timeout|network|HTTP|abort/i.test(raw)
? '图片识别失败,请检查网络后重试'
: (raw || '图片识别失败,请稍后重试')
this.setData({ isTyping: false })
this.handleAIError(friendly)
},
patchMessage(messageId, patch) {
const messages = this.data.messages.map(item => (
item.id === messageId ? { ...item, ...patch } : item
))
this.setData({ messages })
this.saveChatHistory(messages)
},
// 相册/相机原图可能好几兆,超过阈值先压一档;压缩失败则用原图(后面还有大小兜底)
async resolveImageFile(file) {
if (!file.size || file.size <= IMAGE_COMPRESS_THRESHOLD) return file.tempFilePath
const compressed = await this.compressImage(file.tempFilePath, 70)
return compressed || file.tempFilePath
},
compressImage(src, quality) {
return new Promise((resolve) => {
if (!wx.compressImage) {
resolve('')
return
}
wx.compressImage({
src,
quality,
success: (res) => resolve(res.tempFilePath || ''),
fail: () => resolve('')
})
})
},
resolveImageMime(filePath) {
const ext = String(filePath || '').split('.').pop().toLowerCase()
if (ext === 'png') return 'image/png'
if (ext === 'webp') return 'image/webp'
return 'image/jpeg'
},
readFileBase64(filePath) {
return new Promise((resolve, reject) => {
wx.getFileSystemManager().readFile({
filePath,
encoding: 'base64',
success: (res) => resolve(res.data),
fail: () => reject(new Error('读取文件失败,请重试'))
})
})
},
// base64 每 4 个字符对应 3 字节,先估体积再发请求,避免超限被后端直接拒掉
estimateBytes(base64) {
return Math.round(String(base64 || '').length * 3 / 4)
},
// 供应商失败、断网、超限等统一收成一句可重试的提示;服务端给的业务文案原样保留
toastRecognitionError(err, label) {
const message = String(
(err && err.message) || (err && err.errMsg) || ''
)
const friendly = /request:fail|timeout|network|HTTP|abort/i.test(message)
? `${label}识别失败,请检查网络后重试`
: (message || `${label}识别失败,请稍后重试`)
wx.showToast({ title: friendly, icon: 'none' })
},
formatDuration(ms) {
const seconds = Math.max(0, Math.floor(ms / 1000))
const mm = String(Math.floor(seconds / 60)).padStart(2, '0')
const ss = String(seconds % 60).padStart(2, '0')
return `${mm}:${ss}`
},
sendMessage() {
// 录音中:输入框已有回显文字时,发送键与语音键一样直接发出当前文字
if (this.data.recording) {
const content = String(this.data.inputValue || '').trim()
if (!content) {
wx.showToast({ title: '还没有识别到文字,请继续说话', icon: 'none' })
return
}
this.sendVoiceText(content)
return
}
if (this.data.isRecognizing) {
wx.showToast({ title: '正在识别,请稍候', icon: 'none' })
return
}
const content = this.data.inputValue.trim()
if (!content) return
this.dispatchMessage(content)
},
// 真正的发送出口:手动点发送与语音定稿都走这里,
// 保证上屏、清空输入框、发起聊天请求的步骤完全一致
dispatchMessage(content) {
if (this.activeRequestId) {
// 正在等上一条回复:把内容留在输入框,回复结束后用户可直接发送,不丢识别结果
this.setData({ inputValue: content })
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
const userMessage = {
id: this.createMessageId(),
type: 'user',
contentType: 'text',
content,
status: '',
ts: Date.now(),
time: this.formatTime(new Date())
}
const requestId = this.createMessageId('req')
const messages = this.stampMessageTimes([...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
// 图片提问重试要重走识别,不能把本地路径当问题文本塞进聊天 WS
if (message.contentType === 'image') {
this.retryImageMessage(message)
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)
},
retryImageMessage(message) {
// 历史里的图片只剩占位:临时路径已被清理,只能重新选图
if (!message.content) {
wx.showToast({ title: '图片已不可用,请重新选择图片', icon: 'none' })
return
}
const requestId = this.createMessageId('req')
const messages = this.data.messages.map(item => (
item.id === message.id ? { ...item, status: '' } : item
))
this.beginRequest(requestId, message.id, 'image')
this.setData({ messages, isTyping: true })
this.saveChatHistory(messages)
this.scrollToBottom()
this.runImageRecognition({
messageId: message.id,
file: {
tempFilePath: message.content,
size: message._imageSize || 0,
width: message._imageWidth || 0,
height: message._imageHeight || 0
}
})
},
async sendToAI(content, type, requestId) {
const app = getApp()
// 留一份本轮请求现场:服务端回「请先登录」时用它换新 token 原样重发
this.activePayload = { content, type, requestId }
// 登录是发消息的前置条件,不是网络/服务故障:单独判定,
// 否则会落进 handleAIError,让用户误以为是「发送失败,点击重试」能解决的问题
let authenticated = false
try {
authenticated = await app.waitForAuth()
} catch (e) {
authenticated = false
}
const token = app.globalData.user?.security?.token || ''
if (!authenticated || !app.globalData.user?._id || !token) {
this.handleLoginRequired()
return false
}
try {
const socket = app.initChatSocket()
await socket.connect()
await socket.send({
source: 'user',
type,
content,
id: requestId,
token,
ts: new Date().toISOString()
})
return true
} catch (err) {
this.handleAIError(err.message || '消息发送失败,请稍后重试')
return false
}
},
// 服务端只认 token(api/health/websocket.js):本地 globalData 还是登录态、
// 但这枚 token 已被服务端作废时(后端重启/换库后旧 token 全部失效),
// app.onShow 因 user 仍在而不会重签,WS 也没有 HTTP 那层 401 兜底。
// 这里统一补一次静默重登,成功返回 true 并同步顶部提示条
async reauthSilently() {
const app = getApp()
try {
const ok = await app.silentSignin()
if (ok && app.globalData.user?.security?.token) {
this.setData({ authChecked: true, isLoggedIn: true })
this.clearStaleLoginMessages()
return true
}
} catch (err) {
console.log('静默重登失败', err)
}
this.setData({ isLoggedIn: false })
return false
},
// 聊天 WS 回「请先登录」:先静默重登换新 token,再把同一问原样重发,
// 用户无感;重登失败(或重发后仍被拒)才落登录提示。
// 同一条请求只重试一次,避免服务端持续判未登录时死循环
async handleAuthExpired() {
const payload = this.activePayload
if (!payload || this.authRetriedRequestId === payload.requestId) {
this.handleLoginRequired('登录状态已失效,请重新登录后再试', false)
return
}
this.authRetriedRequestId = payload.requestId
if (!(await this.reauthSilently())) {
this.handleLoginRequired('登录状态已失效,请重新登录后再试', false)
return
}
// requestId 保持不变:重发的流式回复仍落在这条提问下
await this.sendToAI(payload.content, payload.type, payload.requestId)
},
// 未登录/登录失效:给一条说得清的提示并附登录入口,原消息不标成 failed
// (标 failed 会挂上「点击重试」,而这种失败重试必然再失败一次)
// markLoggedOut:本地已确认未登录时同步顶部提示条;服务端判定失效时不动本地会话,
// 避免把网络抖动导致的「查不到人」误当成退出登录
handleLoginRequired(content = '尚未登录,无法与陪诊助手对话', markLoggedOut = true) {
const messages = this.data.messages.map(item => (
item.id === this.activeUserMessageId ? { ...item, status: 'blocked' } : item
))
messages.push({
id: this.createMessageId(),
type: 'system',
contentType: 'login',
content,
ts: Date.now(),
time: this.formatTime(new Date())
})
const nextMessages = this.stampMessageTimes(messages)
this.resetActiveRequest()
this.setData(markLoggedOut
? { messages: nextMessages, isTyping: false, authChecked: true, isLoggedIn: false }
: { messages: nextMessages, isTyping: false })
this.flushChatHistory()
this.scrollToBottom()
},
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,
ts: Date.now(),
time: this.formatTime(new Date())
})
this.resetActiveRequest()
this.setData({ messages: this.stampMessageTimes(messages), isTyping: false })
this.flushChatHistory()
this.scrollToBottom()
},
scrollToBottom() {
setTimeout(() => {
const lastMessage = this.data.messages[this.data.messages.length - 1]
if (!lastMessage) return
this.setData({
// 等待动画在消息列表之后,正在等待时直接滚到它,避免长会话里看不到反馈
scrollToMessage: this.data.isTyping ? 'msg-typing' : `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.data.recording || this.data.isRecognizing) {
wx.showToast({ title: '请先结束语音输入', icon: 'none' })
return
}
if (this.activeRequestId) {
wx.showToast({ title: '请等待当前回复完成', icon: 'none' })
return
}
if (!this.data.messages.length) {
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)
}
})
}
})