合并代码,解决冲突

(cherry picked from commit 8b23bd771f04ceb1b9c1e3ae021d75001af5ba2f)
This commit is contained in:
hugo authored and sophie committed 2026-06-01 17:52:50 +08:00
1 parent 23badf7456
commit 93e99793d8
10 files changed
+626 -84

No files matched your search

+64 -2
View File
@@ -48,6 +48,7 @@ const emit = defineEmits<{
const { t } = useI18n();
const isLoading = ref(false);
const isDownloading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null);
@@ -298,6 +299,43 @@ const loadBinaryContent = async () => {
officeObjectUrl.value = URL.createObjectURL(blob);
};
const downloadFile = async () => {
if (!props.file?.url || !props.agentId || isDownloading.value) return;
isDownloading.value = true;
try {
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
download: '1',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const blob = await res.blob();
const downloadUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = props.file.name || 'download';
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
} catch (e: any) {
error.value = t('filePreview.msg.downloadFailed', {
reason: e?.message || t('filePreview.msg.unknownError'),
});
} finally {
isDownloading.value = false;
}
};
/**
* 在弹窗/文件变化时加载预览内容。
* 流程:
@@ -436,8 +474,18 @@ watch(
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
<div class="dialog-header dialog-header--compact items-start">
<div class="min-w-0">
<div class="label-field tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div>
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div>
@@ -532,6 +580,20 @@ watch(
<div class="mt-2 text-sm text-muted">
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
<div class="mt-4 flex gap-3">
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
</div>
<iframe
v-else
+87 -18
View File
@@ -32,6 +32,18 @@ interface ChatMessage {
rated?: boolean;
}
type RunStatus = 'running' | 'done' | 'error';
interface ChatRun {
runId: number;
viewId: number;
query: string;
messages: ChatMessage[];
conversationId: string | null;
status: RunStatus;
createdAt: string;
}
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
@@ -125,12 +137,35 @@ export function useChat() {
*/
const isThinking = ref(false);
const viewId = ref(0);
const runs = ref<ChatRun[]>([]);
const activeRunId = ref<number | null>(null);
let runSeq = 0;
/**
* conversationId: 当前会话 ID
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
*/
const conversationId = ref<string | null>(null);
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
if (!run) return;
messages.value = run.messages;
conversationId.value = run.conversationId;
isThinking.value = run.status === 'running';
activeRunId.value = runId;
};
const createNewChatView = () => {
viewId.value += 1;
messages.value = [];
conversationId.value = null;
isThinking.value = false;
activeRunId.value = null;
};
/**
* sendMessage
* 用途:发送消息并处理 SSE 流式响应
@@ -145,6 +180,20 @@ export function useChat() {
* agentId: 目标 Agent ID
*/
const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => {
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
viewId: runViewId,
query,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
console.info('[chat][send] start', {
agentId,
kbType,
@@ -152,19 +201,19 @@ export function useChat() {
conversationId: conversationId.value,
});
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
runMessages.push({ role: 'user', content: query });
// Lazily create assistant message only when answer/error arrives.
let botMsgIndex: number | null = null;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = messages.value.push({
botMsgIndex = runMessages.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: []
}) - 1;
}
return messages.value[botMsgIndex] || null;
return runMessages[botMsgIndex] || null;
};
isThinking.value = true;
@@ -234,7 +283,14 @@ export function useChat() {
conversationId: data?.conversation_id || conversationId.value,
});
if (data.event === 'message') {
if (data?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (messages.value === runMessages) conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
@@ -246,21 +302,20 @@ export function useChat() {
});
}
if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex];
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (data.event === 'message_end') {
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = messages.value[botMsgIndex];
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
}
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
@@ -278,16 +333,22 @@ export function useChat() {
});
}
if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex];
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (data.event === 'error') {
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data);
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
}
} catch (e) {
// Ignore malformed or partial payload fragments.
@@ -297,16 +358,24 @@ export function useChat() {
}
} catch (e: any) {
console.error('[chat][send] failed', e);
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
} finally {
isThinking.value = false;
console.info('[chat][send] end', {
messages: messages.value.length,
conversationId: conversationId.value,
});
if (messages.value === runMessages) {
isThinking.value = false;
console.info('[chat][send] end', {
messages: messages.value.length,
conversationId: conversationId.value,
});
} else {
console.info('[chat][send] end (detached)', {
activeConversationId: conversationId.value,
runViewId,
});
}
}
};
@@ -315,5 +384,5 @@ export function useChat() {
return text.replace(/\\n/g, '\n');
};
return { messages, isThinking, conversationId, sendMessage };
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage };
}
+72 -14
View File
@@ -611,7 +611,7 @@ const isSidebarCollapsed = ref(false);
const copiedIndex = ref<number | null>(null);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, sendMessage } = useChat();
const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
@@ -1623,6 +1623,48 @@ interface ChatHistoryItem {
}
const history = ref<ChatHistoryItem[]>([]);
type DisplayHistoryItem = ChatHistoryItem & { __runId?: number; __status?: string };
const activeHistoryKey = computed(() => {
if (conversationId.value) return conversationId.value;
if (activeRunId.value) return `pending:${activeRunId.value}`;
return '';
});
const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
conversation_id: r.conversationId || `pending:${r.runId}`,
title: (r.query || '').trim(),
created_at: r.createdAt,
__runId: r.runId,
__status: r.status,
}))
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
const merged = [...pending, ...server] as DisplayHistoryItem[];
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
return merged;
});
const handleHistorySelect = (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
} else {
const run = runs.value.find((r) => r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
} else {
loadConversation(item.conversation_id);
}
}
isSidebarOpen.value = false;
};
// 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => {
const q = route.query.preset;
@@ -1892,7 +1934,8 @@ const clearAllHistory = async () => {
});
if (res.ok) {
history.value = [];
if (conversationId.value) {
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
}
@@ -1923,9 +1966,11 @@ const deleteHistoryItem = async (id: string, event: Event) => {
};
const loadConversation = async (id: string) => {
if (conversationId.value === id) return;
if (conversationId.value === id && !activeRunId.value) return;
try {
activeRunId.value = null;
isThinking.value = false;
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
messages.value = await res.json();
@@ -1939,8 +1984,7 @@ const loadConversation = async (id: string) => {
};
const startNewChat = () => {
messages.value = [];
conversationId.value = null;
createNewChatView();
};
const loadAgent = async () => {
@@ -2043,6 +2087,17 @@ watch(
}
);
watch(
() => conversationId.value,
async (id, prev) => {
if (!id || id === prev) return;
const exists = history.value.some((item) => item.conversation_id === id);
if (!exists) {
await loadHistory();
}
}
);
onBeforeUnmount(() => {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('hxops:logout', onAuthLogout);
@@ -2165,29 +2220,32 @@ const showChatRating = ref(false);
</div>
<div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.history') }}</span>
<button v-if="history.length > 0" @click="clearAllHistory" class="text-xs text-muted transition-colors hover:text-secondary">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
<button v-if="displayHistory.length > 0" @click="clearAllHistory" class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
{{ $t('chat.clearAll') }}
</button>
</div>
<div class="flex-1 overflow-y-auto px-2 scrollbar-thin">
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-muted">{{ $t('chat.noHistory') }}</div>
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
<div v-else class="space-y-0.5">
<div
v-for="item in history"
v-for="item in displayHistory"
:key="item.conversation_id"
class="chat-history-item"
:class="{ 'chat-history-item--active': conversationId === item.conversation_id }"
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
>
<button
class="chat-history-link"
:class="{ 'chat-history-link--active': conversationId === item.conversation_id }"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
class="flex-1 truncate px-3 py-2.5 text-left text-sm pr-8"
:class="activeHistoryKey === item.conversation_id
? 'font-medium text-brand-700 dark:text-brand-300'
: 'text-slate-600 dark:text-slate-300'"
@click="handleHistorySelect(item)"
>
{{ item.title || $t('chat.newChat') }}
</button>
<button
v-if="!(item as any).__runId"
@click="deleteHistoryItem(item.conversation_id, $event)"
class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100"
:title="$t('chat.clearOneRecord')"