Merge branch 'main' of https://git.brother7.cn/zoujing/YGChatCS into order-729

This commit is contained in:
duanshuwen
2025-08-08 09:39:52 +08:00
6 changed files with 579 additions and 306 deletions

View File

@@ -0,0 +1,107 @@
<template>
<uni-popup position="center" :mask-click-able="false" ref="popupRef" type="center" :safe-area="false" :custom-style="{width: '100%', height: '100vh', borderRadius: 0, position: 'fixed', top: '0', left: '0', zIndex: 9999}">
<view class="recording-popup">
<view class="recording-wave">
<!-- 波形动画 -->
<view class="wave-animation"></view>
</view>
<view class="recording-text">
{{ isSlideToText ? '松开发送 转文字' : '松开发送' }}
</view>
<view class="recording-cancel" @click="handleCancel">
取消
</view>
</view>
</uni-popup>
</template>
<script setup>
import { ref } from 'vue'
const props = defineProps({
isSlideToText: Boolean
})
const emit = defineEmits(['cancel'])
const popupRef = ref(null)
// 打开弹窗
const open = () => {
if (popupRef.value) {
popupRef.value.open()
}
}
// 关闭弹窗
const close = () => {
if (popupRef.value) {
popupRef.value.close()
}
}
// 处理取消
const handleCancel = () => {
emit('cancel')
close()
}
// 暴露方法
defineExpose({
open,
close
})
</script>
<style scoped lang="scss">
/* 录音弹窗样式 */
.recording-popup {
width: 100% !important;
height: 100vh !important;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: white;
padding: 40px 0;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
}
.recording-wave {
width: 240px;
height: 240px;
border-radius: 50%;
background-color: rgba(76, 217, 100, 0.3);
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 40px;
}
.wave-animation {
width: 160px;
height: 160px;
/* 这里可以添加波形动画 */
background-image: url('/static/wave_icon.png');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.recording-text {
font-size: 20px;
margin-bottom: 40px;
}
.recording-cancel {
font-size: 18px;
color: #CCCCCC;
margin-top: 20px;
}
</style>

View File

@@ -0,0 +1,140 @@
<template>
<uni-popup position="center" :mask-click-able="false" ref="popupRef" type="center" :safe-area="false" :custom-style="{ width: '100%', maxWidth: '100vw', borderRadius: 0, position: 'fixed', top: '0', left: '0', zIndex: 9999 }">
<view class="voice-result-popup">
<view class="voice-result-bubble">
<textarea v-model="editedVoiceText" class="editable-textarea" placeholder="语音转换结果"></textarea>
</view>
<view class="voice-result-actions">
<view class="action-button cancel" @click="handleCancel">取消</view>
<view class="action-button send" @click="handleSendText">发送</view>
</view>
</view>
</uni-popup>
</template>
<script setup>
import { ref, watch } from 'vue'
const props = defineProps({
voiceText: String
})
const emit = defineEmits(['cancel', 'sendText'])
const popupRef = ref(null)
const editedVoiceText = ref(props.voiceText || '')
// 监听props变化更新编辑框内容
watch(() => props.voiceText,
(newValue) => {
editedVoiceText.value = newValue || ''
}
)
// 打开弹窗
const open = () => {
if (popupRef.value) {
popupRef.value.open()
}
}
// 关闭弹窗
const close = () => {
if (popupRef.value) {
popupRef.value.close()
}
}
// 处理取消
const handleCancel = () => {
emit('cancel')
close()
}
// 处理发送文本
const handleSendText = () => {
emit('sendText', { text: editedVoiceText.value })
close()
}
// 暴露方法
defineExpose({
open,
close
})
</script>
<style scoped lang="scss">
/* 语音结果弹窗样式 */
.voice-result-popup {
width: 100% !important;
height: 100vh;
background-color: rgba(0, 0, 0, 0.7);
padding: 40px 20px;
display: flex;
flex-direction: column;
justify-content: flex-end;
box-sizing: border-box;
}
.voice-result-bubble {
background-color: #00A6FF;
color: white;
box-sizing: border-box;
width: 100%;
padding: 16px;
border-radius: 10px;
margin-bottom: 40px;
min-height: 120px;
max-height: 400px;
font-size: 16px;
overflow-y: auto;
box-shadow: 2px 2px 6px 0px rgba(0,0,0,0.1);
border-radius: 20px 4px 20px 20px;
border: 1px solid;
border-color: #FFFFFF;
}
.editable-textarea {
width: 100%;
height: 100%;
background: transparent;
color: white;
font-size: 16px;
}
.editable-textarea:focus {
outline: none;
}
.voice-result-actions {
display: flex;
justify-content: center;
gap: 20px;
width: 100%;
max-width: 600px;
margin-top: 20px;
padding-bottom: 20px;
}
.action-button {
padding: 12px 24px;
border-radius: 30px;
font-size: 18px;
min-width: 120px;
text-align: center;
}
.cancel {
color: #F5F5F5;
border: 1px solid;
border-color: #F5F5F5;
}
.send {
color: #333;
background-color: #F5F5F5;
}
</style>

View File

@@ -8,28 +8,12 @@
<!-- 输入框/语音按钮容器 -->
<view class="input-button-container">
<textarea
ref="textareaRef"
class="textarea"
type="text"
:placeholder="placeholder"
cursor-spacing="65"
confirm-type='done'
v-model="inputMessage"
@confirm="sendMessage"
@focus="handleFocus"
@blur="handleBlur"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
:confirm-hold="true"
auto-height
:show-confirm-bar='false'
:hold-keyboard="holdKeyboard"
:adjust-position="true"
maxlength="300"
/>
<textarea ref="textareaRef" class="textarea" type="text" :placeholder="placeholder" cursor-spacing="65"
confirm-type='done' v-model="inputMessage" @confirm="sendMessage" @focus="handleFocus" @blur="handleBlur"
@touchstart="handleTouchStart" @touchend="handleTouchEnd" :confirm-hold="true" auto-height
:show-confirm-bar='false' :hold-keyboard="holdKeyboard" :adjust-position="true" maxlength="300" />
<view
<!-- <view
v-if="isVoiceMode"
class="hold-to-talk-button"
@touchstart.stop="startRecording"
@@ -37,11 +21,14 @@
@touchmove.stop="handleTouchMove"
>
按住说话
</view> -->
<view v-if="isVoiceMode" class="hold-to-talk-button" @click.stop="startRecording">
按住说话
</view>
</view>
<view class="input-container-send">
<view v-if="!isVoiceMode" class="input-container-send-btn" @click="sendMessage">
<view class="input-container-send-btn" @click="sendMessage">
<image v-if="props.isSessionActive" src='/static/input_stop_icon.png'></image>
<image v-else src='/static/input_send_icon.png'></image>
</view>
@@ -49,40 +36,18 @@
</view>
<!-- 录音界面 -->
<uni-popup v-model:show="isRecording" position="center" :mask-click-able="false">
<view class="recording-popup">
<view class="recording-wave">
<!-- 波形动画 -->
<view class="wave-animation"></view>
</view>
<view class="recording-text">
{{ isSlideToText ? '松开发送 转文字' : '松开发送' }}
</view>
<view class="recording-cancel">
取消
</view>
</view>
</uni-popup>
<!-- 使用封装的弹窗组件 -->
<RecordingPopup ref="recordingPopupRef" :is-slide-to-text="isSlideToText" @cancel="handleRecordingCancel" />
<VoiceResultPopup ref="voiceResultPopupRef" :voice-text="voiceText" @cancel="cancelVoice" @sendVoice="handleSendVoice"
@sendText="handleSendText" />
<!-- 语音结果界面 -->
<uni-popup v-model:show="showVoiceResult" position="center" :mask-click-able="false">
<view class="voice-result-popup">
<view class="voice-result-bubble">
{{ voiceText }}
</view>
<view class="voice-result-actions">
<view class="action-button cancel" @click="cancelVoice">取消</view>
<view class="action-button voice">发送原语音</view>
<view class="action-button send" @click="sendVoiceMessage">发送</view>
</view>
</view>
</uni-popup>
</template>
<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ref, watch, nextTick, onMounted } from 'vue'
import RecordingPopup from '@/components/Speech/RecordingPopup.vue'
import VoiceResultPopup from '@/components/Speech/VoiceResultPopup.vue'
const props = defineProps({
modelValue: String,
@@ -104,6 +69,8 @@ const recordingTimer = ref(null)
const voiceText = ref('')
const showVoiceResult = ref(false)
const isSlideToText = ref(false)
const recordingPopupRef = ref(null)
const voiceResultPopupRef = ref(null)
// 保持和父组件同步
@@ -126,15 +93,19 @@ const toggleVoiceMode = () => {
// 开始录音
const startRecording = () => {
console.log('startRecording')
isRecording.value = true
return
recordingTime.value = 0
// 启动录音计时器
recordingTimer.value = setInterval(() => {
recordingTime.value += 1
}, 1000)
// 打开录音弹窗
if (recordingPopupRef.value) {
recordingPopupRef.value.open()
}
// 调用uni-app录音API
uni.startRecord({
success: (res) => {
@@ -145,23 +116,40 @@ const startRecording = () => {
setTimeout(() => {
voiceText.value = '这是语音转文字的结果'
showVoiceResult.value = true
// 打开语音结果弹窗
if (voiceResultPopupRef.value) {
voiceResultPopupRef.value.open()
}
}, 1000)
},
fail: (err) => {
console.error('录音失败:', err)
isRecording.value = false
clearInterval(recordingTimer.value)
if (recordingPopupRef.value) {
recordingPopupRef.value.close()
}
}
})
}
// 处理录音弹窗取消
const handleRecordingCancel = () => {
isRecording.value = false
clearInterval(recordingTimer.value)
uni.stopRecord()
}
// 结束录音
const stopRecording = () => {
isRecording.value = false
return
clearInterval(recordingTimer.value)
// 关闭录音弹窗
if (recordingPopupRef.value) {
recordingPopupRef.value.close()
}
// 如果录音时间小于1秒取消录音
if (recordingTime.value < 1) {
uni.stopRecord()
@@ -172,6 +160,28 @@ const stopRecording = () => {
uni.stopRecord()
}
// 处理发送原语音
const handleSendVoice = (data) => {
// 发送语音逻辑
emit('sendVoice', {
text: data.text,
// 可以添加语音文件路径等信息
})
showVoiceResult.value = false
isVoiceMode.value = false
}
// 处理发送文本
const handleSendText = (data) => {
// 发送文本逻辑
emit('sendVoice', {
text: data.text,
// 可以添加语音文件路径等信息
})
showVoiceResult.value = false
isVoiceMode.value = false
}
// 处理滑动事件
const handleTouchMove = (e) => {
// 检测滑动位置,判断是否需要转文字
@@ -181,23 +191,39 @@ const handleTouchMove = (e) => {
isSlideToText.value = touchY < 200
}
// 发送语音
const sendVoiceMessage = () => {
// 发送语音逻辑
emit('sendVoice', {
text: voiceText.value,
// 可以添加语音文件路径等信息
})
showVoiceResult.value = false
isVoiceMode.value = false
}
// 取消语音
const cancelVoice = () => {
showVoiceResult.value = false
isVoiceMode.value = false
}
// 测试弹窗方法
const testPopup = () => {
// 模拟开始录音,打开录音弹窗
isRecording.value = true
console.log("===========1")
if (recordingPopupRef.value) {
console.log("===========2")
recordingPopupRef.value.open()
}
// 2秒后关闭录音弹窗打开语音结果弹窗
setTimeout(() => {
if (recordingPopupRef.value) {
recordingPopupRef.value.close()
}
voiceText.value = '测试语音转文字结果'
showVoiceResult.value = true
if (voiceResultPopupRef.value) {
voiceResultPopupRef.value.open()
}
}, 3000)
}
// 监听键盘高度变化
onMounted(() => {
// 监听键盘弹起
@@ -212,6 +238,11 @@ onMounted(() => {
})
const sendMessage = () => {
if (isVoiceMode.value) {
testPopup()
return
}
if (props.isSessionActive) {
// 如果会话进行中,调用停止请求函数
if (props.stopRequest) {
@@ -362,97 +393,9 @@ defineExpose({
.textarea::-webkit-input-placeholder {
color: #CCCCCC;
}
.textarea:focus {
outline: none;
}
}
/* 录音弹窗样式 */
.recording-popup {
width: 280px;
height: 280px;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: white;
}
.recording-wave {
width: 160px;
height: 160px;
border-radius: 50%;
background-color: rgba(76, 217, 100, 0.3);
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.wave-animation {
width: 100px;
height: 100px;
/* 这里可以添加波形动画 */
background-image: url('/static/wave_icon.png');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.recording-text {
font-size: 16px;
margin-bottom: 20px;
}
.recording-cancel {
font-size: 14px;
color: #CCCCCC;
}
/* 语音结果弹窗样式 */
.voice-result-popup {
width: 300px;
background-color: white;
border-radius: 16px;
padding: 20px;
}
.voice-result-bubble {
background-color: #4CD964;
color: white;
padding: 15px;
border-radius: 18px;
border-top-left-radius: 4px;
margin-bottom: 20px;
min-height: 60px;
font-size: 16px;
}
.voice-result-actions {
display: flex;
justify-content: space-between;
}
.action-button {
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
}
.cancel {
color: #666666;
background-color: #F5F5F5;
}
.voice {
color: #007AFF;
background-color: #E8F0FE;
}
.send {
color: white;
background-color: #007AFF;
}
</style>

View File

@@ -103,7 +103,7 @@
import CreateServiceOrder from '@/components/CreateServiceOrder/index.vue'
import { agentChatStream } from '@/request/api/AgentChatStream';
import { agentChatStream, stopAbortTask } from '@/request/api/AgentChatStream';
import { mainPageData } from '@/request/api/MainPageDataApi';
import { conversationMsgList, recentConversation } from '@/request/api/ConversationApi';
@@ -145,8 +145,6 @@
// 会话进行中标志
const isSessionActive = ref(false);
// 请求任务引用
const requestTaskRef = ref(null);
/// 指令
let commonType = ''
@@ -357,7 +355,8 @@
conversationId: conversationId.value,
agentId: agentId.value,
messageType: isInstruct ? 1 : 0,
messageContent: isInstruct ? commonType : message
messageContent: isInstruct ? commonType : message,
messageId: 'mid' + new Date().getTime()
}
// 插入AI消息
@@ -390,8 +389,8 @@
}
// 流式接收内容
const { promise, requestTask } = agentChatStream(args, (chunk) => {
console.log('分段内容:', chunk)
const promise = agentChatStream(args, (chunk) => {
// console.log('分段内容:', chunk)
if (chunk && chunk.error) {
chatMsgList.value[aiMsgIndex].msg = '请求错误,请重试';
clearInterval(loadingTimer);
@@ -456,8 +455,6 @@
}
})
// 存储请求任务
requestTaskRef.value = requestTask;
// 可选处理Promise完成/失败, 已经在回调中处理数据,此处无需再处理
promise.then(data => {
@@ -487,11 +484,7 @@
// 停止请求函数
const stopRequest = () => {
if (requestTaskRef.value && requestTaskRef.value.abort) {
// 标记请求已中止,用于过滤后续可能到达的数据
requestTaskRef.value.isAborted = true;
// 中止请求
requestTaskRef.value.abort();
stopAbortTask()
// 重置状态
isSessionActive.value = false;
const msg = chatMsgList.value[currentAIMsgIndex].msg;
@@ -508,9 +501,6 @@
typeWriterTimer = null;
}
setTimeoutScrollToBottom()
// 清空请求引用
requestTaskRef.value = null;
}
}
</script>

View File

@@ -88,8 +88,8 @@
z-index: 1;
transition: padding-bottom 0.3s ease;
/* 确保输入区域始终可见 */
transform: translateZ(0);
-webkit-transform: translateZ(0);
// transform: translateZ(0);
// -webkit-transform: translateZ(0);
}
.area-input {

View File

@@ -9,13 +9,72 @@ const API = '/agent/assistant/chat';
* @param {Function} onChunk 回调,每收到一段数据触发
* @returns {Object} 包含Promise和requestTask的对象
*/
function agentChatStream(params, onChunk) {
let requestTask;
let requestTask = null;
let isAborted = false; // 添加终止状态标志
let currentPromiseReject = null; // 保存当前Promise的reject函数
let requestId = 0; // 请求ID用于区分不同的请求
const stopAbortTask = () => {
console.log('🛑 开始强制终止请求...');
isAborted = true; // 立即设置终止标志
// 立即拒绝当前Promise最强制的终止
if (currentPromiseReject) {
console.log('🛑 立即拒绝Promise');
currentPromiseReject(new Error('请求已被用户终止'));
currentPromiseReject = null;
}
if (requestTask) {
// 先取消所有监听器关键必须在abort之前
try {
if (requestTask.offChunkReceived) {
requestTask.offChunkReceived();
console.log('🛑 已取消 ChunkReceived 监听');
}
} catch (e) {
console.log('🛑 取消 ChunkReceived 监听失败:', e);
}
try {
if (requestTask.offHeadersReceived) {
requestTask.offHeadersReceived();
console.log('🛑 已取消 HeadersReceived 监听');
}
} catch (e) {
console.log('🛑 取消 HeadersReceived 监听失败:', e);
}
// 然后终止网络请求
try {
if (requestTask.abort) {
requestTask.abort();
console.log('🛑 已终止网络请求');
}
} catch (e) {
console.log('🛑 终止网络请求失败:', e);
}
requestTask = null;
}
// 递增请求ID使旧请求的数据无效
requestId++;
console.log('🛑 请求强制终止完成新请求ID:', requestId);
}
const agentChatStream = (params, onChunk) => {
const promise = new Promise((resolve, reject) => {
const token = uni.getStorageSync('token');
let hasError = false;
isAborted = false; // 重置终止状态
console.log("发送请求内容: ", params)
// 保存当前Promise的reject函数用于强制终止
currentPromiseReject = reject;
// 为当前请求分配ID
const currentRequestId = ++requestId;
console.log("🚀 发送请求内容: ", params, "请求ID:", currentRequestId)
// #ifdef MP-WEIXIN
requestTask = uni.request({
url: BASE_URL + API, // 替换为你的接口地址
@@ -29,38 +88,62 @@ function agentChatStream(params, onChunk) {
},
responseType: 'arraybuffer',
success(res) {
if (!isAborted && requestId === currentRequestId) {
console.log("✅ 请求成功ID:", currentRequestId);
resolve(res.data);
} else {
console.log("❌ 请求已过期或终止忽略success回调当前ID:", requestId, "请求ID:", currentRequestId);
}
},
fail(err) {
console.log("====> ", JSON.stringify(err))
if (!isAborted && requestId === currentRequestId) {
console.log("❌ 请求失败ID:", currentRequestId, "错误:", JSON.stringify(err));
reject(err);
} else {
console.log("❌ 请求已过期或终止忽略fail回调当前ID:", requestId, "请求ID:", currentRequestId);
}
},
complete(res) {
if(res.statusCode !== 200) {
console.log("====> ", JSON.stringify(res))
if (!isAborted && requestId === currentRequestId && res.statusCode !== 200) {
console.log("❌ 请求完成但状态错误ID:", currentRequestId, "状态:", res.statusCode);
if (onChunk) {
onChunk({ error: true, message: '服务器错误', detail: res });
}
reject(res);
} else if (requestId !== currentRequestId) {
console.log("❌ 请求已过期或终止忽略complete回调当前ID:", requestId, "请求ID:", currentRequestId);
}
}
});
requestTask.onHeadersReceived(res => {
console.log('onHeadersReceived', res);
// 检查请求是否已终止或过期
if (isAborted || requestId !== currentRequestId) {
console.log('🚫 Headers已终止或过期忽略当前ID:', requestId, '请求ID:', currentRequestId);
return;
}
console.log('📡 onHeadersReceivedID:', currentRequestId, res);
const status = res.statusCode || (res.header && res.header.statusCode);
if (status && status !== 200) {
hasError = true;
if (onChunk) {
if (onChunk && !isAborted && requestId === currentRequestId) {
onChunk({ error: true, message: `服务器错误(${status})`, detail: res });
}
requestTask.abort && requestTask.abort();
if (requestTask && requestTask.abort) {
requestTask.abort();
}
}
});
requestTask.onChunkReceived(res => {
// 检查请求是否已被中止
if (hasError || requestTask.isAborted) return;
// 第一道防线立即检查请求ID和终止状态
if (isAborted || hasError || requestTask === null || requestId !== currentRequestId) {
console.log('🚫 数据块已终止或过期,忽略 - 第一道检查当前ID:', requestId, '请求ID:', currentRequestId);
return;
}
console.log("📦 onChunkReceivedID:", currentRequestId, res)
const base64 = uni.arrayBufferToBase64(res.data);
let data = '';
try {
@@ -69,18 +152,28 @@ function agentChatStream(params, onChunk) {
// 某些平台可能不支持 atob可以直接用 base64
data = base64;
}
// 第二道防线:解析前再次检查
if (isAborted || hasError || requestTask === null || requestId !== currentRequestId) {
console.log('🚫 数据块已终止或过期,忽略 - 第二道检查当前ID:', requestId, '请求ID:', currentRequestId);
return;
}
const messages = parseSSEChunk(data);
messages.forEach(msg => {
if (onChunk) onChunk(msg);
// 第三道防线:每个消息处理前都检查
if (onChunk && !isAborted && !hasError && requestTask !== null && requestId === currentRequestId) {
console.log(`parseSSEChunk ${currentRequestId}:`, msg)
onChunk(msg);
} else {
console.log('🚫 消息已终止或过期忽略处理当前ID:', requestId, '请求ID:', currentRequestId);
}
});
});
// #endif
});
return {
promise,
requestTask
};
return promise
}
// window.atob兼容性处理
@@ -152,4 +245,4 @@ function parseSSEChunk(raw) {
return results;
}
export { agentChatStream }
export { agentChatStream, stopAbortTask }