diff --git a/app.json b/app.json index 25c9f39..ed7f20c 100644 --- a/app.json +++ b/app.json @@ -22,6 +22,11 @@ "navigationBarTitleText": "暖橙陪诊", "navigationBarTextStyle": "black" }, + "permission": { + "scope.record": { + "desc": "用于语音输入陪诊问题,录音仅用于本次转写,不会保存" + } + }, "tabBar": { "custom": true, "color": "#6F655C", diff --git a/pages/ai/aichat.js b/pages/ai/aichat.js index 75364bb..8ca0828 100644 --- a/pages/ai/aichat.js +++ b/pages/ai/aichat.js @@ -1,5 +1,30 @@ 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 + Page({ data: { messages: [], @@ -10,6 +35,15 @@ Page({ authChecked: false, isLoggedIn: false, scrollToMessage: '', + // 语音识别:点麦克风开录、图标转为录音态,识别文本实时回填输入框; + // 再点一次结束,定稿后直接发送(语音场景不需要用户再点一次发送键)。 + // 图片走另一条路:选完即上屏,识别结果直接作为 AI 回复 + recording: false, + recordTime: '00:00', + isRecognizing: false, + // 实时链路不可用(供应商失败 / 分片格式无法解码)时置 true: + // 状态条补一句「结束后整段转写」,避免用户以为没有识别 + voiceRealtimeOff: false, quickQuestions: [ { id: '陪诊服务的流程是什么?', text: '陪诊服务的流程是什么?' }, { id: '如何预约陪诊服务?', text: '如何预约陪诊服务?' }, @@ -25,13 +59,37 @@ Page({ this.activeServerId = '' this.activeRequestType = '' this.historySaveTimer = null + this.recordTimer = null + // 本轮语音:流式会话、已收分片、录音文件(分片缺失时的整段兜底)、 + // 开录前输入框里已有的文字(识别结果只追加在它后面,不覆盖用户手打的字) + this.voiceStream = null + this.voiceFrames = [] + this.voiceStopFile = '' + this.voiceBaseText = '' 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() { @@ -101,9 +159,21 @@ Page({ 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('连接已断开,请点击失败消息重试') } @@ -132,6 +202,16 @@ Page({ 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)) { @@ -242,6 +322,10 @@ Page({ 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() } @@ -259,7 +343,11 @@ Page({ saveChatHistory(messages = this.data.messages) { try { - wx.setStorageSync('ai_chat_history', messages) + // 图片气泡里是本地临时路径,小程序重启后必然失效:只存占位,不写路径 + const persisted = messages.map(item => ( + item.contentType === 'image' ? { ...item, content: '' } : item + )) + wx.setStorageSync('ai_chat_history', persisted) } catch (e) { console.log('保存聊天记录失败', e) } @@ -286,6 +374,11 @@ Page({ }, 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() @@ -310,10 +403,859 @@ Page({ 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) { + 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('语音识别连接中断,请重试')) + }, + + // 再次点麦克风 = 结束录音:停止采集并让服务端定稿,定稿后直接发出 + stopVoiceInput() { + if (!this.data.recording) return + + this.clearRecordTimer() + this.setData({ recording: false, recordTime: '00:00', isRecognizing: true }) + + 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() { + 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(false) + }, + + 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 }) + + 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) + }, + + // 流式失败(配置缺失 / 供应商异常 / 断流):不再中途弹错,悄悄降级 + 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) + this.setData({ isLoggedIn: false }) + 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, + 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 等待动画, + // 而不是一层盖住会话的 loading + sendImageMessage(file) { + const userMessage = { + id: this.createMessageId(), + type: 'user', + contentType: 'image', + content: file.tempFilePath, + status: '', + time: this.formatTime(new Date()) + } + const requestId = this.createMessageId('req') + const messages = [...this.data.messages, userMessage] + + this.beginRequest(requestId, userMessage.id, 'image') + this.setData({ + messages, + isTyping: true, + isRecognizing: 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) + } + }, + + // 识别成功:文本作为 AI 消息落在图片下方;图片提问不走 WS,这里直接收尾本轮 + handleImageReply(reply) { + if (!reply || reply.code !== 0) { + // request 层已尝试静默重登,仍回 401 说明本地 token 确实失效: + // 走登录提示(图片消息置为 blocked,不挂重试,避免反复失败) + if (reply && reply.code === 401) { + this.setData({ isLoggedIn: false, isRecognizing: 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 + } + + const messages = this.data.messages.slice() + messages.push({ + id: this.createMessageId(), + type: 'ai', + contentType: 'text', + content: text, + time: this.formatTime(new Date()) + }) + this.resetActiveRequest() + this.setData({ messages, isTyping: false, isRecognizing: false }) + this.flushChatHistory() + this.scrollToBottom() + }, + + // 失败复用聊天失败态:标记挂在图片气泡上,点「重试」重走识别 + 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({ isRecognizing: false, 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) { + wx.showToast({ title: '正在录音,再点麦克风即可结束', icon: 'none' }) + 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 } @@ -347,6 +1289,12 @@ Page({ 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 @@ -357,6 +1305,33 @@ Page({ 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, isRecognizing: 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() @@ -464,6 +1439,10 @@ Page({ }, clearChat() { + if (this.data.recording || this.data.isRecognizing) { + wx.showToast({ title: '请先结束语音输入', icon: 'none' }) + return + } if (this.activeRequestId) { wx.showToast({ title: '请等待当前回复完成', icon: 'none' }) return diff --git a/pages/ai/aichat.wxml b/pages/ai/aichat.wxml index 51df491..5fcecb4 100644 --- a/pages/ai/aichat.wxml +++ b/pages/ai/aichat.wxml @@ -75,13 +75,15 @@ /> {{item.content}} + + [图片] @@ -135,37 +137,78 @@ - + + + + 正在录音 {{recordTime}},再次点击麦克风结束并发送 + 正在识别并发送… + 结束后整段转写 + + + - - - + + - - - - 常见问题 + 左端是会话级动作(常见问题 / 清空聊天),只在有消息时出现,做成只描边不填充的 + 暖橙小按钮(圆角与输入框同为 20rpx),与输入区右侧浅橙底的发送键区分开; + 靠左与上方输入框、消息气泡同一条左边线。 + 右端两个只留图标的入口是语音 / 图片:空会话也要能点,故常驻,不做成描边按钮。 + 麦克风在录音中转为实心暖橙底的白图标,本身就是「再点一次结束」的入口。 + 清空聊天是破坏性动作,放在左组最右端(不顶到整行最右)、右侧留给输入入口 --> + + + + + 常见问题 + + + + 清空聊天 + - - - 清空聊天 + + + + + + + \ No newline at end of file diff --git a/pages/ai/aichat.wxss b/pages/ai/aichat.wxss index 70fa7bd..92cbeb1 100644 --- a/pages/ai/aichat.wxss +++ b/pages/ai/aichat.wxss @@ -10,11 +10,10 @@ overflow: hidden 是兜底,避免任何子项溢出到视口外变成"看得见滑不到" */ overflow: hidden; /* 给 fixed 的自定义 tabBar 留位;安全区由这里统一承担,输入区不再重复加。 - tabBar 实测高度 = 12+12 内距 + 44 图标 + 6 间距 + 24 文字 + 2 边框 = 100rpx(+安全区)。 - 140 → 120 → 112rpx:按钮下边只剩 12rpx(6px) 空隙,已贴近下限—— - 再往下(<100rpx)胶囊就会被 tabBar 盖住;这 12rpx 同时是防微信字体放大 - 把 tabBar 撑高的缓冲,不宜再压 */ - padding-bottom: calc(112rpx + env(safe-area-inset-bottom)); + tabBar 总高 100rpx(12+12 内距 + 44 图标 + 6 间距 + 24 文字 + 2 边框), + 页面占位与它同用 rpx 体系:tabBar 高度 + 2px 恒定缓冲, + 任何屏幕宽度上工具条与 tabBar 的间隙都一致,不会大屏贴住、小屏偏空 */ + padding-bottom: calc(100rpx + 2px + env(safe-area-inset-bottom)); background-color: var(--paper); } @@ -55,20 +54,38 @@ opacity: 0.6; } -/* ===== 辅助入口(在输入区下方:常见问题 + 清空聊天)===== */ -/* 空心描边小按钮:2rpx 暖橙描边、无填充。 - 两者都是低频辅助动作,用"只描边"与输入区右侧那个浅橙底发送键区分开; +/* ===== 辅助入口(在输入区下方:常见问题 + 清空聊天 + 语音/图片)===== */ +/* 左端是空心描边小按钮:2rpx 暖橙描边、无填充。 + 会话动作(常见问题 / 清空聊天)用"只描边"与输入区右侧那个浅橙底发送键区分开; 描边在纸面上 4.66:1、文字 6.10:1,均过线。 圆角 20rpx 与输入框、发送键、气泡同档——全页统一为圆角矩形,不再有胶囊。 - 容器是 column,靠 align-self: flex-end 把整行右对齐 */ + 右端的语音/图片入口与头像同构(浅橙衬底 + 描边),比左侧描边小按钮多一层衬底, + 靠"只留图形"与带文字的会话动作分层。 + 整行不再 shrink 到内容宽度:铺满后左组贴左、右组贴右, + 左右 24rpx 与输入区、消息气泡同一条边线,不再内缩 8rpx */ .tool-bar { - align-self: flex-end; + align-self: stretch; display: flex; align-items: center; gap: 16rpx; flex-shrink: 0; - /* 上 12 贴住输入区,右 32 对齐页面页边距;下不留边距,底部空气统一交给容器 */ - margin: 12rpx 32rpx 0; + /* 上 6 贴住输入区(输入区底部内距 8rpx,合计 14rpx);下不留边距, + 底部空气统一交给容器(容器 padding-bottom 已按 tabBar 覆盖下限预留) */ + margin: 6rpx 24rpx 0; +} + +/* 两组内部各用 gap 排布;右组 margin-left:auto 兜住"左组不存在"的空会话状态, + 此时两个图标仍贴右,不会因为只剩一组就滑到左边 */ +.tool-group, +.media-group { + display: flex; + align-items: center; + gap: 16rpx; +} + +.media-group { + margin-left: auto; + flex-shrink: 0; } .tool-btn { @@ -392,6 +409,13 @@ border-radius: 12rpx; } +/* 历史里的图片只剩占位(临时路径不落 storage),用一行弱化的说明撑住上下文 */ +.message-image-placeholder { + font-size: 28rpx; + line-height: 1.6; + color: var(--muted); +} + /* ===== 正在输入 ===== */ .typing-bubble { padding: 24rpx 32rpx; @@ -437,28 +461,155 @@ gap: 16rpx; /* 钉在容器底部,不被消息区挤压 */ flex-shrink: 0; - padding: 16rpx 24rpx; + /* 底部内距收窄到 8rpx:与下方工具条合计 14rpx 间隙, + 给语音/图片按钮省出竖向空间 */ + padding: 16rpx 24rpx 8rpx; background: var(--white); border-top: 2rpx solid var(--line); } +/* 输入框改为自增高 textarea:语音识别结果通常是一整句话, + 单行 input 会把内容截断,导致用户看不到自己说了什么。 + 默认高度按 2 行撑起(28rpx 字号 × 1.5 行高 × 2 行 + 上下 18rpx 内距 = 120rpx), + 一眼可见多行输入的体量,长问题也不用先挤在一行里; + 内容再长继续随 auto-height 增长,最多约 4 行,不把消息区挤没 */ .message-input { flex: 1; - height: 76rpx; - padding: 0 28rpx; + width: auto; + min-height: 120rpx; + max-height: 220rpx; + padding: 18rpx 28rpx; + box-sizing: border-box; background: var(--paper); border: 2rpx solid var(--line); /* 20rpx = 10px:与气泡、常见问题卡、用户徽记的统一圆角档, 比原 999rpx 胶囊更贴合"输入条"的体量(76rpx 高≈38px,10px 圆角约占四分之一) */ border-radius: 20rpx; font-size: 28rpx; + line-height: 1.5; color: var(--ink); } +/* 录音/识别中只读:内容仍要清楚可读,不能被原生 disabled 灰掉 */ +.message-input.is-readonly { + opacity: 1; + -webkit-text-fill-color: var(--ink); +} + .input-placeholder { color: var(--muted); } +/* 语音/图片入口:与辅助动作同一行,收在「清空聊天」右侧。 + 原为裸图标(无底无描边),视觉上悬空、热区不明确;现改为与头像、 + 欢迎区图标同构的"浅橙衬底 + 2rpx --brand-line 描边"小方块, + 既是明确可点的按钮,又与全页浅橙家族同一语言。 + 72rpx(36px)满足最小触控热区,比图标图形大出一圈,方便点击; + 圆角 20rpx 与输入框、发送键、气泡统一为同档圆角矩形。 + 录音中麦克风转成实心暖橙底 + 白色图标:同一位置、同一热区,用户再点一次即结束, + 不额外长出第二个按钮 */ +.media-btn { + width: 72rpx; + height: 72rpx; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + border-radius: 20rpx; + background: var(--brand-soft); + border: 2rpx solid var(--brand-line); + transition: opacity 0.15s ease, transform 0.15s ease, + background 0.15s ease, border-color 0.15s ease; +} + +.media-btn:active { + opacity: 0.7; + transform: scale(0.92); +} + +.media-btn.active { + background: var(--brand-strong); + border-color: var(--brand-strong); + /* 录音态加一层外发光,让"正在采集"在输入区下方也一眼可见 */ + box-shadow: 0 0 0 6rpx var(--brand-soft); + animation: voice-breathe 1.6s ease-in-out infinite; +} + +@keyframes voice-breathe { + 0%, 100% { + box-shadow: 0 0 0 6rpx var(--brand-soft); + } + 50% { + box-shadow: 0 0 0 12rpx var(--brand-soft); + } +} + +/* ===== 语音 / 识别状态条 ===== */ +/* 一行内联提示,贴在输入区上沿:不盖住输入框、不替换输入框, + 录音与识别阶段都在这里说明"现在处于什么状态、下一步做什么" */ +.voice-status { + display: flex; + align-items: center; + gap: 12rpx; + flex-shrink: 0; + margin: 8rpx 24rpx 0; + padding: 10rpx 20rpx; + border-radius: 16rpx; + background: var(--brand-soft); + border: 2rpx solid var(--brand-line); +} + +.voice-dot { + width: 14rpx; + height: 14rpx; + border-radius: 50%; + flex-shrink: 0; + background: var(--brand-strong); +} + +.voice-dot.recording { + animation: record-pulse 1.2s infinite ease-in-out; +} + +/* 识别阶段不是采集,用慢速呼吸代替录音的脉冲,避免误以为还在录 */ +.voice-dot.recognizing { + animation: voice-dot-soft 1.6s infinite ease-in-out; +} + +.voice-status-text { + font-size: 24rpx; + line-height: 1.5; + color: var(--ink-2); +} + +/* 实时链路不可用时的补充说明:不是错误,只是告知「结束后出字」 */ +.voice-status-sub { + margin-left: auto; + flex-shrink: 0; + font-size: 22rpx; + color: var(--muted); +} + +@keyframes record-pulse { + 0%, 100% { + transform: scale(0.7); + opacity: 0.4; + } + 50% { + transform: scale(1); + opacity: 1; + } +} + +@keyframes voice-dot-soft { + 0%, 100% { + opacity: 0.35; + } + 50% { + opacity: 1; + } +} + /* 发送按钮:默认浅橙底 + 描边,有内容时转实心暖橙(全页唯一的实心橙块)。 默认态落在白面输入区上,浅橙底同样靠 --brand-line 描边托形。 圆角由正圆(50%)改为 20rpx,与左侧输入框、上方气泡同档,成对出现 */