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,40 +8,27 @@
<!-- 输入框/语音按钮容器 --> <!-- 输入框/语音按钮容器 -->
<view class="input-button-container"> <view class="input-button-container">
<textarea <textarea ref="textareaRef" class="textarea" type="text" :placeholder="placeholder" cursor-spacing="65"
ref="textareaRef" confirm-type='done' v-model="inputMessage" @confirm="sendMessage" @focus="handleFocus" @blur="handleBlur"
class="textarea" @touchstart="handleTouchStart" @touchend="handleTouchEnd" :confirm-hold="true" auto-height
type="text" :show-confirm-bar='false' :hold-keyboard="holdKeyboard" :adjust-position="true" maxlength="300" />
: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" v-if="isVoiceMode"
class="hold-to-talk-button" class="hold-to-talk-button"
@touchstart.stop="startRecording" @touchstart.stop="startRecording"
@touchend.stop="stopRecording" @touchend.stop="stopRecording"
@touchmove.stop="handleTouchMove" @touchmove.stop="handleTouchMove"
> >
按住说话 按住说话
</view> </view> -->
<view v-if="isVoiceMode" class="hold-to-talk-button" @click.stop="startRecording">
按住说话
</view>
</view> </view>
<view class="input-container-send"> <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-if="props.isSessionActive" src='/static/input_stop_icon.png'></image>
<image v-else src='/static/input_send_icon.png'></image> <image v-else src='/static/input_send_icon.png'></image>
</view> </view>
@@ -49,40 +36,18 @@
</view> </view>
<!-- 录音界面 --> <!-- 使用封装的弹窗组件 -->
<uni-popup v-model:show="isRecording" position="center" :mask-click-able="false"> <RecordingPopup ref="recordingPopupRef" :is-slide-to-text="isSlideToText" @cancel="handleRecordingCancel" />
<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>
<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> </template>
<script setup> <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({ const props = defineProps({
modelValue: String, modelValue: String,
@@ -104,6 +69,8 @@ const recordingTimer = ref(null)
const voiceText = ref('') const voiceText = ref('')
const showVoiceResult = ref(false) const showVoiceResult = ref(false)
const isSlideToText = ref(false) const isSlideToText = ref(false)
const recordingPopupRef = ref(null)
const voiceResultPopupRef = ref(null)
// 保持和父组件同步 // 保持和父组件同步
@@ -126,15 +93,19 @@ const toggleVoiceMode = () => {
// 开始录音 // 开始录音
const startRecording = () => { const startRecording = () => {
console.log('startRecording')
isRecording.value = true isRecording.value = true
return
recordingTime.value = 0 recordingTime.value = 0
// 启动录音计时器 // 启动录音计时器
recordingTimer.value = setInterval(() => { recordingTimer.value = setInterval(() => {
recordingTime.value += 1 recordingTime.value += 1
}, 1000) }, 1000)
// 打开录音弹窗
if (recordingPopupRef.value) {
recordingPopupRef.value.open()
}
// 调用uni-app录音API // 调用uni-app录音API
uni.startRecord({ uni.startRecord({
success: (res) => { success: (res) => {
@@ -145,23 +116,40 @@ const startRecording = () => {
setTimeout(() => { setTimeout(() => {
voiceText.value = '这是语音转文字的结果' voiceText.value = '这是语音转文字的结果'
showVoiceResult.value = true showVoiceResult.value = true
// 打开语音结果弹窗
if (voiceResultPopupRef.value) {
voiceResultPopupRef.value.open()
}
}, 1000) }, 1000)
}, },
fail: (err) => { fail: (err) => {
console.error('录音失败:', err) console.error('录音失败:', err)
isRecording.value = false isRecording.value = false
clearInterval(recordingTimer.value) clearInterval(recordingTimer.value)
if (recordingPopupRef.value) {
recordingPopupRef.value.close()
}
} }
}) })
} }
// 处理录音弹窗取消
const handleRecordingCancel = () => {
isRecording.value = false
clearInterval(recordingTimer.value)
uni.stopRecord()
}
// 结束录音 // 结束录音
const stopRecording = () => { const stopRecording = () => {
isRecording.value = false isRecording.value = false
return
clearInterval(recordingTimer.value) clearInterval(recordingTimer.value)
// 关闭录音弹窗
if (recordingPopupRef.value) {
recordingPopupRef.value.close()
}
// 如果录音时间小于1秒取消录音 // 如果录音时间小于1秒取消录音
if (recordingTime.value < 1) { if (recordingTime.value < 1) {
uni.stopRecord() uni.stopRecord()
@@ -172,6 +160,28 @@ const stopRecording = () => {
uni.stopRecord() 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) => { const handleTouchMove = (e) => {
// 检测滑动位置,判断是否需要转文字 // 检测滑动位置,判断是否需要转文字
@@ -181,23 +191,39 @@ const handleTouchMove = (e) => {
isSlideToText.value = touchY < 200 isSlideToText.value = touchY < 200
} }
// 发送语音
const sendVoiceMessage = () => {
// 发送语音逻辑
emit('sendVoice', {
text: voiceText.value,
// 可以添加语音文件路径等信息
})
showVoiceResult.value = false
isVoiceMode.value = false
}
// 取消语音 // 取消语音
const cancelVoice = () => { const cancelVoice = () => {
showVoiceResult.value = false showVoiceResult.value = false
isVoiceMode.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(() => { onMounted(() => {
// 监听键盘弹起 // 监听键盘弹起
@@ -212,10 +238,15 @@ onMounted(() => {
}) })
const sendMessage = () => { const sendMessage = () => {
if (isVoiceMode.value) {
testPopup()
return
}
if (props.isSessionActive) { if (props.isSessionActive) {
// 如果会话进行中,调用停止请求函数 // 如果会话进行中,调用停止请求函数
if (props.stopRequest) { if (props.stopRequest) {
props.stopRequest(); props.stopRequest();
} }
} else { } else {
// 否则发送新消息 // 否则发送新消息
@@ -273,186 +304,98 @@ defineExpose({
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.area-input { .area-input {
display: flex; display: flex;
align-items: center; align-items: center;
border-radius: 22px; border-radius: 22px;
background-color: #FFFFFF; background-color: #FFFFFF;
box-shadow: 0px 0px 20px 0px rgba(52,25,204,0.05); box-shadow: 0px 0px 20px 0px rgba(52, 25, 204, 0.05);
margin: 0 12px; margin: 0 12px;
/* 确保输入框在安全区域内 */ /* 确保输入框在安全区域内 */
margin-bottom: 8px; margin-bottom: 8px;
.input-container-voice { .input-container-voice {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 44px; width: 44px;
height: 44px; height: 44px;
flex-shrink: 0; flex-shrink: 0;
align-self: flex-end; align-self: flex-end;
cursor: pointer; cursor: pointer;
image { image {
width: 22px; width: 22px;
height: 22px; height: 22px;
} }
} }
.input-button-container { .input-button-container {
flex: 1; flex: 1;
position: relative; position: relative;
height: 44px; height: 44px;
} }
.hold-to-talk-button { .hold-to-talk-button {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
color: #333333; color: #333333;
font-size: 16px; font-size: 16px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: #FFFFFF; background-color: #FFFFFF;
} }
.input-container-send { .input-container-send {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 44px; width: 44px;
height: 44px; height: 44px;
flex-shrink: 0; flex-shrink: 0;
align-self: flex-end; align-self: flex-end;
.input-container-send-btn { .input-container-send-btn {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
image {
width: 28px;
height: 28px;
}
}
.textarea {
flex: 1;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
max-height: 92px;
min-height: 44px;
font-size: 16px;
line-height: 22px;
padding: 3px 0 0;
align-items: center;
justify-content: center; justify-content: center;
} width: 100%;
height: 100%;
}
/* 确保textarea在iOS上的样式正常 */ image {
.textarea::-webkit-input-placeholder { width: 28px;
color: #CCCCCC; height: 28px;
} }
.textarea:focus { }
outline: none;
}
}
/* 录音弹窗样式 */ .textarea {
.recording-popup { flex: 1;
width: 280px; position: absolute;
height: 280px; top: 0;
background-color: rgba(0, 0, 0, 0.7); left: 0;
border-radius: 20px; width: 100%;
display: flex; height: 100%;
flex-direction: column; max-height: 92px;
justify-content: center; min-height: 44px;
align-items: center; font-size: 16px;
color: white; line-height: 22px;
} padding: 3px 0 0;
align-items: center;
justify-content: center;
}
.recording-wave { /* 确保textarea在iOS上的样式正常 */
width: 160px; .textarea::-webkit-input-placeholder {
height: 160px; color: #CCCCCC;
border-radius: 50%; }
background-color: rgba(76, 217, 100, 0.3);
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.wave-animation { .textarea:focus {
width: 100px; outline: none;
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> </style>

View File

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

View File

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

View File

@@ -9,13 +9,72 @@ const API = '/agent/assistant/chat';
* @param {Function} onChunk 回调,每收到一段数据触发 * @param {Function} onChunk 回调,每收到一段数据触发
* @returns {Object} 包含Promise和requestTask的对象 * @returns {Object} 包含Promise和requestTask的对象
*/ */
function agentChatStream(params, onChunk) { let requestTask = null;
let requestTask; 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 promise = new Promise((resolve, reject) => {
const token = uni.getStorageSync('token'); const token = uni.getStorageSync('token');
let hasError = false; let hasError = false;
isAborted = false; // 重置终止状态
console.log("发送请求内容: ", params)
// 保存当前Promise的reject函数用于强制终止
currentPromiseReject = reject;
// 为当前请求分配ID
const currentRequestId = ++requestId;
console.log("🚀 发送请求内容: ", params, "请求ID:", currentRequestId)
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
requestTask = uni.request({ requestTask = uni.request({
url: BASE_URL + API, // 替换为你的接口地址 url: BASE_URL + API, // 替换为你的接口地址
@@ -29,38 +88,62 @@ function agentChatStream(params, onChunk) {
}, },
responseType: 'arraybuffer', responseType: 'arraybuffer',
success(res) { success(res) {
resolve(res.data); if (!isAborted && requestId === currentRequestId) {
console.log("✅ 请求成功ID:", currentRequestId);
resolve(res.data);
} else {
console.log("❌ 请求已过期或终止忽略success回调当前ID:", requestId, "请求ID:", currentRequestId);
}
}, },
fail(err) { fail(err) {
console.log("====> ", JSON.stringify(err)) if (!isAborted && requestId === currentRequestId) {
reject(err); console.log("❌ 请求失败ID:", currentRequestId, "错误:", JSON.stringify(err));
reject(err);
} else {
console.log("❌ 请求已过期或终止忽略fail回调当前ID:", requestId, "请求ID:", currentRequestId);
}
}, },
complete(res) { complete(res) {
if(res.statusCode !== 200) { if (!isAborted && requestId === currentRequestId && res.statusCode !== 200) {
console.log("====> ", JSON.stringify(res)) console.log("❌ 请求完成但状态错误ID:", currentRequestId, "状态:", res.statusCode);
if (onChunk) { if (onChunk) {
onChunk({ error: true, message: '服务器错误', detail: res }); onChunk({ error: true, message: '服务器错误', detail: res });
} }
reject(res); reject(res);
} } else if (requestId !== currentRequestId) {
console.log("❌ 请求已过期或终止忽略complete回调当前ID:", requestId, "请求ID:", currentRequestId);
}
} }
}); });
requestTask.onHeadersReceived(res => { 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); const status = res.statusCode || (res.header && res.header.statusCode);
if (status && status !== 200) { if (status && status !== 200) {
hasError = true; hasError = true;
if (onChunk) { if (onChunk && !isAborted && requestId === currentRequestId) {
onChunk({ error: true, message: `服务器错误(${status})`, detail: res }); onChunk({ error: true, message: `服务器错误(${status})`, detail: res });
} }
requestTask.abort && requestTask.abort(); if (requestTask && requestTask.abort) {
requestTask.abort();
}
} }
}); });
requestTask.onChunkReceived(res => { requestTask.onChunkReceived(res => {
// 检查请求是否已被中止 // 第一道防线立即检查请求ID和终止状态
if (hasError || requestTask.isAborted) return; 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); const base64 = uni.arrayBufferToBase64(res.data);
let data = ''; let data = '';
try { try {
@@ -69,18 +152,28 @@ function agentChatStream(params, onChunk) {
// 某些平台可能不支持 atob可以直接用 base64 // 某些平台可能不支持 atob可以直接用 base64
data = base64; data = base64;
} }
// 第二道防线:解析前再次检查
if (isAborted || hasError || requestTask === null || requestId !== currentRequestId) {
console.log('🚫 数据块已终止或过期,忽略 - 第二道检查当前ID:', requestId, '请求ID:', currentRequestId);
return;
}
const messages = parseSSEChunk(data); const messages = parseSSEChunk(data);
messages.forEach(msg => { 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 // #endif
}); });
return { return promise
promise,
requestTask
};
} }
// window.atob兼容性处理 // window.atob兼容性处理
@@ -152,4 +245,4 @@ function parseSSEChunk(raw) {
return results; return results;
} }
export { agentChatStream } export { agentChatStream, stopAbortTask }