Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-20 09:36:20 +08:00
commit 4d05b5674e
3 files changed
+100 -28

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"
+84 -17
View File
@@ -13,7 +13,7 @@
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat'; import { useChat } from '../composables/useChat';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search } from 'lucide-vue-next'; import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid } from 'lucide-vue-next';
import { marked } from 'marked'; import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { config } from '../config'; import { config } from '../config';
@@ -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,
@@ -571,7 +572,9 @@ const copiedIndex = ref<number | null>(null);
const { messages, isThinking, conversationId, sendMessage } = useChat(); const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref(''); const input = ref('');
const currentAgent = ref<any>(null); const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string }>>([]);
const showGeneralFeedbackDialog = ref(false); const showGeneralFeedbackDialog = ref(false);
const showAgentPanel = ref(true);
const OA_BASE_URL = 'http://oa.well-trust.com:8888'; const OA_BASE_URL = 'http://oa.well-trust.com:8888';
const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`; const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`;
@@ -1125,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);
@@ -1265,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)) {
@@ -1273,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();
} }
@@ -1535,6 +1569,28 @@ const loadAgent = async () => {
} }
}; };
const loadUserAgents = async () => {
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (res.ok) {
const agents = await res.json();
userAgents.value = Array.isArray(agents) ? agents.filter((a: any) => a.id !== agentId) : [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
}
} catch (e) {
userAgents.value = [];
showAgentPanel.value = false;
}
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === agentId) return;
const url = router.resolve(`/chat/${agent.id}`).href;
window.open(url, '_blank');
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送 // 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => { onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown); document.addEventListener('mousedown', handleDocumentPointerDown);
@@ -1542,6 +1598,7 @@ onMounted(async () => {
window.addEventListener('resize', syncViewportWidth); window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile(); await syncCurrentUserProfile();
await loadAgent(); await loadAgent();
await loadUserAgents();
await loadHistory(); await loadHistory();
@@ -1574,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 },
); );
@@ -1630,7 +1693,7 @@ const showChatRating = ref(false);
<div class="flex items-center justify-between p-4"> <div class="flex items-center justify-between p-4">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div> <div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div>
<span class="font-bold text-slate-800 dark:text-slate-100">Hxops Alagent</span> <span class="font-bold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
</div> </div>
<button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"> <button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<PanelLeftClose class="h-5 w-5" /> <PanelLeftClose class="h-5 w-5" />
@@ -1680,21 +1743,23 @@ const showChatRating = ref(false);
</div> </div>
<div class="mt-auto flex flex-col p-4"> <div class="mt-auto flex flex-col p-4">
<!-- Upgrade card disabled for now. Keep code for future rollout. <div v-if="userAgents.length > 0 && showAgentPanel" class="mb-4 rounded-2xl border border-slate-200 bg-slate-50/70 p-3 dark:border-slate-700 dark:bg-slate-800/60">
<div class="mb-4 rounded-2xl border border-brand-100 bg-brand-50/70 p-4 dark:border-brand-500/20 dark:bg-brand-900/10"> <div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-500 dark:text-slate-400">
<div class="mb-2 flex items-center gap-1 font-bold text-brand-700 dark:text-brand-300"> <LayoutGrid class="h-3.5 w-3.5" /> 智能体
<Crown class="h-4 w-4" /> 专业版
</div> </div>
<ul class="mb-3 space-y-1 text-[11px] text-slate-600 dark:text-slate-300"> <div class="grid grid-cols-2 gap-1.5">
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 统一Agent知识库入口</li> <button
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 优化Chat界面及交互</li> v-for="agent in userAgents"
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 修改文档预览bug等</li> :key="agent.id"
</ul> @click="switchToAgent(agent)"
<button class="w-full rounded-xl bg-brand-600 py-2 text-xs font-medium text-white shadow-md shadow-brand-500/20 transition-colors hover:bg-brand-700 dark:bg-brand-500 dark:hover:bg-brand-400"> class="flex items-center justify-center gap-1.5 rounded-xl px-2 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-white hover:shadow-sm dark:text-slate-200 dark:hover:bg-slate-700/50 truncate"
🚀 升级说明 >
<div v-if="agent.icon_url" class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat" :style="{ backgroundImage: `url(${agent.icon_url})` }"></div>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600 dark:bg-brand-900/30 dark:text-brand-400">{{ agent.name.charAt(0) }}</div>
<span class="truncate">{{ agent.name }}</span>
</button> </button>
</div> </div>
--> </div>
<!-- Bottom Icons --> <!-- Bottom Icons -->
<div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef"> <div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef">
@@ -1722,6 +1787,7 @@ const showChatRating = ref(false);
</div> </div>
<div class="flex gap-3"> <div class="flex gap-3">
<button @click="userAgents.length === 0 ? undefined : (showAgentPanel = !showAgentPanel)" :class="showAgentPanel && userAgents.length > 0 ? 'text-brand-600 dark:text-brand-400' : ''" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" :title="userAgents.length === 0 ? '暂无可用智能体' : (showAgentPanel ? '收起智能体' : '展开智能体')"><LayoutGrid class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button> <button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button> <button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button>
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button> <button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button>
@@ -1768,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'"
> >
+1 -1
View File
@@ -1470,7 +1470,7 @@ onMounted(async () => {
<Bot class="h-6 w-6" /> <Bot class="h-6 w-6" />
</div> </div>
<div class="min-w-0"> <div class="min-w-0">
<div class="text-2xl font-extrabold tracking-tight text-[#14213d]">Hxops</div> <div class="text-2xl font-extrabold tracking-tight text-[#14213d]">和信AI</div>
<div class="truncate text-xs font-medium text-slate-400"> <div class="truncate text-xs font-medium text-slate-400">
{{ currentUser?.username }} / {{ currentUser?.role }} {{ currentUser?.username }} / {{ currentUser?.role }}
</div> </div>