chat回复滑动的起始位置

This commit is contained in:
runny committed 2026-05-20 09:15:10 +08:00
1 parent 316b8f326e
commit d473ca9a22
2 files changed
+57 -13

No files matched your search

+15 -10
View File
@@ -342,26 +342,33 @@ class DifyService:
retriever_resources: List[Any] = [] retriever_resources: List[Any] = []
attribution_parts: List[str] = [] attribution_parts: List[str] = []
max_retries = 3
for attempt in range(1, max_retries + 1):
try: try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response: with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
if current_app: if current_app:
current_app.logger.info( current_app.logger.info(
"[chat-stream] dify response status=%s reason=%s", "[chat-stream] dify response status=%s reason=%s attempt=%s",
response.status_code, response.status_code,
response.reason, response.reason,
attempt,
) )
if not response.ok and current_app: if not response.ok and current_app:
retryable = response.status_code in (404, 502, 503, 504)
try: try:
error_body = response.text[:2000] error_body = response.text[:2000]
except Exception: except Exception:
error_body = "<failed to read response body>" error_body = "<failed to read response body>"
current_app.logger.error( current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s payload=%s body=%s", "[chat-stream] dify bad response status=%s url=%s attempt=%s body=%s",
response.status_code, response.status_code,
url, url,
json.dumps(payload, ensure_ascii=False), attempt,
error_body, error_body,
) )
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
response.raise_for_status() response.raise_for_status()
for line in response.iter_lines(): for line in response.iter_lines():
@@ -393,8 +400,6 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data) DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'): elif event in ('message_end', 'agent_message', 'workflow_finished'):
# Keep metadata from non-message events, but avoid appending
# intermediate workflow/agent outputs into final user answer.
if event == 'message_end' and data.get('answer'): if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', '')) full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data) DifyService._collect_metadata(retriever_resources, attribution_parts, data)
@@ -405,7 +410,6 @@ class DifyService:
"[source-link] message_end: collected retriever resources=%s", "[source-link] message_end: collected retriever resources=%s",
len(retriever_resources), len(retriever_resources),
) )
# Resolve original source file URLs from external integration API.
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources) DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {} metadata = data.get('metadata') or {}
@@ -440,13 +444,14 @@ class DifyService:
latency, latency,
) )
# Pass-through SSE event (after optional enrichment).
# SSE frame delimiter must be real newlines, not literal "\n".
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
if current_app: if current_app:
current_app.logger.exception("[chat-stream] request exception: %s", e) current_app.logger.exception("[chat-stream] request exception attempt=%s: %s", attempt, e)
if attempt < max_retries:
time.sleep(attempt * 2)
continue
error_msg = json.dumps({'event': 'error', 'message': str(e)}) error_msg = json.dumps({'event': 'error', 'message': str(e)})
yield f"data: {error_msg}\n\n" yield f"data: {error_msg}\n\n"
+42 -3
View File
@@ -34,6 +34,7 @@ const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库']; const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(null); const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null; let scrollToBottomFrame: number | null = null;
let wasThinking = false;
marked.setOptions({ marked.setOptions({
gfm: true, gfm: true,
@@ -1127,6 +1128,39 @@ const scrollChatToBottom = async () => {
}); });
}; };
const scrollToMessage = async (index: number) => {
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
const el = container.querySelector(`[data-msg-index="${index}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
await nextTick();
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return;
const el = container.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scheduleScrollChatToBottom = () => { const scheduleScrollChatToBottom = () => {
if (scrollToBottomFrame !== null) { if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame); window.cancelAnimationFrame(scrollToBottomFrame);
@@ -1267,7 +1301,6 @@ const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value; const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return; if (!content.trim() || isThinking.value) return;
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = ''; if (typeof textOrEvent !== 'string') input.value = '';
if (isStrongLeaveIntent(content)) { if (isStrongLeaveIntent(content)) {
@@ -1275,13 +1308,12 @@ const handleSend = async (textOrEvent?: string | Event) => {
return; return;
} }
const userMsgIndex = messages.value.length;
await sendMessage(content, agentId, selectedKb.value); await sendMessage(content, agentId, selectedKb.value);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) { if (!conversationId.value && history.value.length === 0) {
await loadHistory(); await loadHistory();
} else if (conversationId.value) { } else if (conversationId.value) {
// Check if current conversation is in history, if not, reload
const exists = history.value.some(h => h.conversation_id === conversationId.value); const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory(); if (!exists) await loadHistory();
} }
@@ -1599,7 +1631,13 @@ watch(
conversationId: conversationId.value || '', conversationId: conversationId.value || '',
}), }),
() => { () => {
if (wasThinking && !isThinking.value) {
wasThinking = false;
scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollChatToBottom(); scheduleScrollChatToBottom();
}
}, },
{ deep: false }, { deep: false },
); );
@@ -1796,6 +1834,7 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index"> <template v-for="(msg, index) in messages" :key="index">
<div <div
v-if="shouldRenderMessage(msg)" v-if="shouldRenderMessage(msg)"
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up" class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'" :class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
> >