Commit 8bfc5f27 by weiyudumei

refactor: 统一使用 Promise 判断流结束,移除 END 消息判断

parent 6390aa55
...@@ -7,16 +7,18 @@ import { http } from '@/utils/request' ...@@ -7,16 +7,18 @@ import { http } from '@/utils/request'
export function fetchCheckTokenApi() { export function fetchCheckTokenApi() {
return http.post('/user/api/user_center/mobile/v1/check_token', {}) return http.post('/user/api/user_center/mobile/v1/check_token', {})
} }
export function fetchStreamResponse(url: string, body: Record<string, any>, onMessage: (msg: any) => void, signal?: AbortSignal) { export function fetchStreamResponse(url: string, body: Record<string, any>, onMessage: (msg: any) => void, signal?: AbortSignal): Promise<void> {
body.stream = true body.stream = true
const decoder = new TextDecoder('utf-8') const decoder = new TextDecoder('utf-8')
let buffer = '' let buffer = ''
let dataMsgBuffer = '' let dataMsgBuffer = ''
return new Promise<void>((resolve, reject) => {
function processMessage(reader: any) { function processMessage(reader: any) {
reader.read().then((content: any) => { reader.read().then((content: any) => {
// 检查是否已被中止 // 检查是否已被中止
if (signal?.aborted) { if (signal?.aborted) {
resolve() // 中止时也 resolve,表示流已结束
return return
} }
buffer += decoder.decode(content.value, { stream: !content.done }) buffer += decoder.decode(content.value, { stream: !content.done })
...@@ -59,19 +61,20 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe ...@@ -59,19 +61,20 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe
processMessage(reader) processMessage(reader)
} }
else { else {
onMessage({ // 流结束,resolve Promise(不再发送 END 消息)
type: 'END', resolve()
})
} }
}).catch((error: unknown) => { }).catch((error: unknown) => {
// 如果是 AbortError,不发送错误消息 // 如果是 AbortError,resolve 而不是 reject(因为这是主动取消)
if (error instanceof Error && error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
resolve()
return return
} }
onMessage({ onMessage({
type: 'ERROR', type: 'ERROR',
content: error, content: error,
}) })
reject(error) // 其他错误 reject Promise
}) })
} }
const tokenStr = window.localStorage.getItem('__TOKEN__') || '""' const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
...@@ -97,17 +100,24 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe ...@@ -97,17 +100,24 @@ export function fetchStreamResponse(url: string, body: Record<string, any>, onMe
return response.body?.getReader() return response.body?.getReader()
}) })
.then((reader) => { .then((reader) => {
if (!reader) {
reject(new Error('Failed to get reader from response'))
return
}
return processMessage(reader) return processMessage(reader)
}) })
.catch((error: unknown) => { .catch((error: unknown) => {
// 如果是 AbortError,不发送错误消息 // 如果是 AbortError,resolve 而不是 reject(因为这是主动取消)
if (error instanceof Error && error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
resolve()
return return
} }
onMessage({ onMessage({
type: 'ERROR', type: 'ERROR',
content: error, content: error,
}) })
reject(error)
})
}) })
} }
......
...@@ -298,20 +298,24 @@ export const Chat: React.FC = () => { ...@@ -298,20 +298,24 @@ export const Chat: React.FC = () => {
} }
if (msg?.type === 'DATA' && msg?.content?.code === '01010005') { if (msg?.type === 'DATA' && msg?.content?.code === '01010005') {
handleChatMaxCount(msg, question) handleChatMaxCount(msg, question)
return
} }
if (msg.type === 'END') { },
// 流式请求正常结束时重置 isAsking 状态 abortControllerRef.current.signal,
)
.then(() => {
// 流结束时执行(通过 Promise resolve 判断)
dispatch(setIsAsking(false)) dispatch(setIsAsking(false))
if (isNew) { if (isNew) {
setTimeout(() => { setTimeout(() => {
dispatch(fetchConversations()) dispatch(fetchConversations())
}, 2000) }, 2000)
} }
} })
}, .catch((error) => {
abortControllerRef.current.signal, // 流式请求出错时的处理
) console.error('[Chat] 流式请求失败:', error)
dispatch(setIsAsking(false))
})
} }
/** 获取qa记录 */ /** 获取qa记录 */
......
...@@ -524,18 +524,25 @@ export const TacticsChat: React.FC = () => { ...@@ -524,18 +524,25 @@ export const TacticsChat: React.FC = () => {
} }
if (msg?.type === 'DATA' && msg?.content?.code === '01010005') { if (msg?.type === 'DATA' && msg?.content?.code === '01010005') {
handleChatMaxCount(msg, question || '') handleChatMaxCount(msg, question || '')
return
} }
if (msg.type === 'END') { },
abortControllerRef.current.signal,
)
.then(() => {
// 流结束时执行(通过 Promise resolve 判断,而不是 END 消息)
console.log('[TacticsChat] 流式响应已完成')
dispatch(setIsAsking(false))
if (isNew) { if (isNew) {
setTimeout(() => { setTimeout(() => {
dispatch(fetchTacticsConversations()) dispatch(fetchTacticsConversations())
}, 2000) }, 2000)
} }
} })
}, .catch((error) => {
abortControllerRef.current.signal, // 流式请求出错时的处理
) console.error('[TacticsChat] 流式请求失败:', error)
dispatch(setIsAsking(false))
})
} }
/** 获取qa记录 */ /** 获取qa记录 */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment