Files
wxapp_companion/pages/ai/index.js
T
lik 6da802cff9 feat(ai): 对话页接入实时语音、图片识别与失败重试
- 聊天 WebSocket 提到 app 级,语音分片与对话共用连接,补齐心跳、重连与连接单飞
- 语音输入走 asr_start/asr_chunk/asr_stop,中间结果实时回填,链路异常退回整段转写
- 图片选完先上屏再 OCR,识别原文以 format 消息并入对话
- 失败状态挂在原提问上可点击重试,401 静默重登后原样重发
- 消息区改为暖白纸面与头像+时间布局,常见问题与清空收进更多菜单
2026-11-18 22:34:17 +08:00

1543 lines
50 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 秒一片;分片缺失或链路失败时退回整段 base64 上传。
// 开发者工具的录音实际是 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
const HISTORY_KEY = 'admin_ai_chat_history'
const SESSION_KEY = 'admin_ai_session_id'
Page({
data: {
messages: [],
inputValue: '',
inputFocus: false,
// 「更多」菜单:常见问题与清空聊天收进同一个低频入口
showMoreMenu: false,
isTyping: false,
scrollToMessage: '',
// 语音识别:点麦克风开录,中间结果实时回填输入框,定稿后直接发送
recording: false,
recordTime: '00:00',
// 语音定稿期间的互斥状态:阻止再次录音/发送
isRecognizing: false,
// 实时链路不可用时置 true:状态条补一句「结束后整段转写」
voiceRealtimeOff: false,
// 等回复期间只展示计时,思考过程与流式中间内容都不上屏
processingSeconds: 0,
// 等待气泡的第二行:用已有的工具/子代理帧推断后台在做什么
progressLabel: '',
progressStep: 0,
quickQuestions: [
{ id: '今天有哪些待处理订单?', text: '今天有哪些待处理订单?' },
{ 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 = ''
// 本轮待上屏的最终回答:流式分片先攒着,end 帧到达后一次性显示
this.pendingReplies = null
this.processingTimer = null
this.processingStartedAt = 0
// 本轮已计入步骤的帧 id:流式分片会复用同一 id,不能重复计数
this.progressStepIds = new Set()
this.loadChatHistory()
this.initSocketListeners()
this.initRecorder()
},
onHide() {
// 切到后台/别的页还在录音会继续占用麦克风并产生一段无意义音频,直接丢弃
if (this.data.recording) this.cancelVoiceInput()
},
onUnload() {
this.stopProcessingTimer()
// 未结束的语音轮次要主动取消,否则服务端会话会一直挂到超时
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()
},
/* ===== WebSocket:与语音识别共用一条连接 ===== */
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 已不可用,
// 先静默重登并原样重发,重登失败才提示用户
if (content.includes('请先登录')) {
this.handleAuthExpired()
} else {
this.handleAIError(content)
}
}
break
case 'reasoning':
this.noteProgress('reasoning', data)
break
case 'tool':
this.noteProgress('tool', data)
break
case 'connected':
case 'pong':
break
default:
console.warn('[AIChat] Unknown message type:', data.type)
}
},
isCurrentRequest(requestId) {
if (!this.activeRequestId) return false
return !requestId || requestId === this.activeRequestId
},
// 只收主回答的分片:子代理(思考过程)一律丢弃,等 end 帧再一次性上屏
handleAIReply(data) {
if (!this.activeRequestId) return
if (data.sessionId) {
wx.setStorageSync(SESSION_KEY, data.sessionId)
}
// 子代理负责实际查询:原文不上屏,只让等待气泡显示「正在处理子任务…」并累加步数
if ((data.source || 'main') !== 'main') {
this.noteProgress('subagent', data)
return
}
// 主回答开始生成:气泡继续留着到 end,提示改为「正在整理回答…」
this.noteProgress('answer', data)
const serverId = data.id || this.activeRequestId
const list = this.pendingReplies || (this.pendingReplies = [])
const last = list[list.length - 1]
if (last && last.serverId === serverId) {
last.content += data.content || ''
} else if (data.content) {
list.push({ serverId, content: data.content })
}
this.activeServerId = serverId
this.scrollToBottom()
},
// 把攒下的流式内容合并成一条 AI 消息;没有正文则返回 null
buildPendingReply() {
const list = this.pendingReplies || []
this.pendingReplies = null
const content = list.map(item => item.content).join('\n\n').trim()
if (!content) return null
return {
id: this.createMessageId(),
_serverId: list[list.length - 1].serverId,
type: 'ai',
source: 'main',
contentType: 'text',
content,
ts: Date.now(),
time: this.formatTime(new Date())
}
},
finishAIResponse() {
const isClearRequest = this.activeRequestType === 'clear'
// 最终回答在 end 帧才上屏;思考过程不进消息列表
const replyMessage = this.buildPendingReply()
this.resetActiveRequest()
if (isClearRequest) {
// 清空请求只保留服务端可能下发的确认语,其余历史随清空一起丢弃
const messages = replyMessage ? [replyMessage] : []
this.setData({ messages, isTyping: false })
if (messages.length) {
this.saveChatHistory(messages)
} else {
wx.removeStorageSync(HISTORY_KEY)
}
wx.removeStorageSync(SESSION_KEY)
return
}
const messages = replyMessage
? this.stampMessageTimes([...this.data.messages, replyMessage])
: this.data.messages
this.setData({ messages, isTyping: false })
this.flushChatHistory()
this.scrollToBottom()
},
resetActiveRequest() {
this.activeRequestId = ''
this.activeUserMessageId = ''
this.activeServerId = ''
this.activeRequestType = ''
// 请求已结束,不再保留提问现场(图片原文可能很大)
this.activePayload = null
// 失败/登录失效等收尾路径丢弃未上屏内容,并停掉计时
this.pendingReplies = null
this.progressStepIds = new Set()
this.setData({ progressLabel: '', progressStep: 0 })
this.stopProcessingTimer()
},
// 等待期间只显示「正在处理...N秒」
startProcessingTimer() {
if (this.processingTimer) return
this.processingStartedAt = Date.now()
this.setData({ processingSeconds: 0 })
this.processingTimer = setInterval(() => {
this.setData({
processingSeconds: Math.floor((Date.now() - this.processingStartedAt) / 1000)
})
}, 1000)
},
stopProcessingTimer() {
if (this.processingTimer) {
clearInterval(this.processingTimer)
this.processingTimer = null
}
this.processingStartedAt = 0
},
beginRequest(requestId, userMessageId = '', type = 'chat') {
this.activeRequestId = requestId
this.activeUserMessageId = userMessageId
this.activeServerId = ''
this.activeRequestType = type
this.resetProgress(type)
this.startProcessingTimer()
},
// 等待态进度:后端没有独立的进度帧,用已有的 tool / subagent / reasoning 帧
// 推断当前阶段;图片/语音识别有自己的文案,不在这里抢提示
resetProgress(type = 'chat') {
this.progressStepIds = new Set()
this.setData({
progressLabel: type === 'chat' ? '正在理解您的问题' : '',
progressStep: 0
})
},
noteProgress(kind, data) {
if (!this.activeRequestId) return
const labels = {
reasoning: '正在分析…',
tool: '正在查询资料…',
subagent: '正在处理子任务…',
answer: '正在整理回答…'
}
const label = labels[kind]
if (!label) return
// 工具结果与子代理消息都按 id 计一步,主代理自己调工具也算
let step = this.data.progressStep
const id = data && data.id
if (id && (kind === 'tool' || kind === 'subagent') && !this.progressStepIds.has(id)) {
this.progressStepIds.add(id)
step += 1
}
if (label === this.data.progressLabel && step === this.data.progressStep) return
this.setData({ progressLabel: label, progressStep: step })
},
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(HISTORY_KEY)
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) && item.source !== 'subagent')
.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(HISTORY_KEY, 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()
},
// 「更多」菜单:语音/图片之外的低频动作统一收在这里
toggleMoreMenu() {
this.setData({ showMoreMenu: !this.data.showMoreMenu })
},
onCloseMoreMenu() {
if (this.data.showMoreMenu) {
this.setData({ showMoreMenu: false })
}
},
onMoreQuickQuestions() {
this.setData({ showMoreMenu: false })
this.showQuickQuestions()
},
onMoreClearChat() {
this.setData({ showMoreMenu: false })
this.clearChat()
},
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
}, [])
},
// 把常见问题清单作为一条 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 是全局单例:监听器挂在页面实例上,卸载时必须摘掉
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()
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 (!getApp().globalData.user?._id) {
wx.showToast({ title: '请先登录后再使用语音和图片输入', icon: 'none' })
return false
}
return true
},
// 首次使用弹微信授权;已被拒绝过则只能引导去设置页
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,
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('语音识别连接失败,请稍后重试'))
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 秒后仍无分片就在状态条提示
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)
},
// 每一帧先落本地再上传:流式链路失败时还能拿已采集的音频整段兜底
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 && this.data.voiceRealtimeOff) {
// 分片已到 = 实时链路具备回显条件:撤掉误报提示
this.setData({ voiceRealtimeOff: false })
}
if (!uploading) return
stream.chunkBytes += bytes
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('语音识别连接中断,请重试'))
},
// 录音中直接发出:点麦克风或发送键共用
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)
},
// 没有回显文字时再点麦克风 = 结束录音:停止采集并让服务端定稿
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
}
// 实时链路已被关闭:直接走整段转写
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)
},
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 分片 / 供应商失败 / 超时 / 空定稿)时的兜底
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('录音过大,请缩短语音后重试')
}
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) return
// 已经结束录音(正在定稿)就不再覆盖输入框
if (!this.data.recording) return
const partial = String(data.content || '')
if (!partial) return
stream.partialCount += 1
stream.partialSeen = true
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()
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,只会多花一次上传
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,
// 识别失败/取消时收起等待气泡;正常定稿会紧接着走 dispatchMessage
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 回复 =====
图片路径只存在页面内存里(不写 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 回复区的等待动画
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)
// 压缩后是一条新文件:气泡换成本次真正送去识别的图,重试也从这条路径走
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 原文以 format 类型投递给聊天 WS,服务端并入上下文并回显
handleImageReply(reply) {
if (!reply || reply.code !== 0) {
if (reply && reply.code === 401) {
this.handleLoginRequired('登录状态已失效,请重新进入小程序后再试')
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
}
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,
showMoreMenu: false
})
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 }
// 登录是发消息的前置条件,不是网络/服务故障
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(),
// 陪诊师端固定走管理/员工 agent,权限由服务端按员工档案收敛
agent: 'escort-admin'
})
return true
} catch (err) {
this.handleAIError(err.message || '消息发送失败,请稍后重试')
return false
}
},
// 服务端只认 token:本地仍是登录态但 token 已被作废时,先静默重登再原样重发
async reauthSilently() {
const app = getApp()
try {
const ok = await app.silentSignin()
if (ok && app.globalData.user?.security?.token) {
return true
}
} catch (err) {
console.log('静默重登失败', err)
}
return false
},
// 聊天 WS 回「请先登录」:静默重登后把同一问原样重发,同一条请求只重试一次
async handleAuthExpired() {
const payload = this.activePayload
if (!payload || this.authRetriedRequestId === payload.requestId) {
this.handleLoginRequired('登录状态已失效,请重新进入小程序后再试')
return
}
this.authRetriedRequestId = payload.requestId
if (!(await this.reauthSilently())) {
this.handleLoginRequired('登录状态已失效,请重新进入小程序后再试')
return
}
// requestId 保持不变:重发的流式回复仍落在这条提问下
await this.sendToAI(payload.content, payload.type, payload.requestId)
},
// 未登录/登录失效:给一条说得清的提示;原消息标为 blocked,不挂「点击重试」
handleLoginRequired(content = '尚未登录,无法与陪诊助手对话') {
const messages = this.data.messages.map(item => (
item.id === this.activeUserMessageId ? { ...item, status: 'blocked' } : item
))
messages.push({
id: this.createMessageId(),
type: 'system',
contentType: 'text',
content,
ts: Date.now(),
time: this.formatTime(new Date())
})
this.resetActiveRequest()
this.setData({ messages: this.stampMessageTimes(messages), 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)
}
})
}
})