diff --git a/frontend/src/composables/useChat.ts b/frontend/src/composables/useChat.ts index 2b13106a..44252c3d 100644 --- a/frontend/src/composables/useChat.ts +++ b/frontend/src/composables/useChat.ts @@ -36,6 +36,7 @@ type RunStatus = 'running' | 'done' | 'error'; interface ChatRun { runId: number; + agentId: number; viewId: number; query: string; messages: ChatMessage[]; @@ -192,6 +193,7 @@ export function useChat() { const runMessages = messages.value; const run: ChatRun = { runId: ++runSeq, + agentId, viewId: runViewId, query, messages: runMessages, diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index cd091f65..4f9298ff 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -26,7 +26,7 @@ import { useTheme } from '../composables/useTheme'; import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth'; import { copyTextToClipboard } from '../utils/clipboard'; import { setLastChatAgentId } from '../utils/lastChatAgent'; -import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs'; +import { registerOpenAgentId } from '../utils/agentTabs'; import ChatShell from '../layouts/ChatShell.vue'; import { BusinessError } from '../api/client'; import { @@ -602,7 +602,7 @@ const previewFile = ref<{ name: string; url: string; actualExt?: string } | null const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => { if (file.datasetId && file.remoteDocumentId) { const data = await resolveChatSourceFile({ - agent_id: agentId, + agent_id: currentAgentId.value, dataset_id: file.datasetId, remote_document_id: file.remoteDocumentId, }); @@ -650,7 +650,10 @@ const parsePlmPreviewLink = (href: string): SourceFileLink | null => { }; const route = useRoute(); const router = useRouter(); -const agentId = Number(route.params.agentId); +const currentAgentId = computed(() => { + const id = Number(route.params.agentId); + return Number.isFinite(id) && id > 0 ? id : 0; +}); // Sidebar state for mobile const isSidebarOpen = ref(false); @@ -1047,7 +1050,7 @@ const buildFileSpecsForSend = async (): Promise => { isUploadingAttachments.value = true; try { for (const item of locals) { - const uploaded = await uploadChatFile(agentId, item.file); + const uploaded = await uploadChatFile(currentAgentId.value, item.file); if (!uploaded?.id) { throw new Error('Missing upload id'); } @@ -1302,7 +1305,7 @@ const fetchLeaveAgents = async (isLoadMore = false) => { leaveAgentLoading.value = true; try { - const data = await listOaEmployees(agentId, { + const data = await listOaEmployees(currentAgentId.value, { keyword: leaveAgentKeyword.value, page: leaveAgentPage.value, page_size: 20, @@ -1334,7 +1337,7 @@ const loadAllAgents = async () => { if (!leaveAgentHasMore.value || leaveAgentLoading.value) return; leaveAgentLoading.value = true; try { - const data = await listOaEmployees(agentId, { + const data = await listOaEmployees(currentAgentId.value, { keyword: leaveAgentKeyword.value, page: 1, page_size: 100000, @@ -1636,7 +1639,7 @@ const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => { content: msg.content, payload: msg.payload, query: userQuery, - agent_id: agentId, + agent_id: currentAgentId.value, }); if (!conversationId.value && data.conversation_id) { conversationId.value = data.conversation_id; @@ -1745,7 +1748,7 @@ const startLocalLeaveFlow = async (content: string) => { try { const keyword = payload.form.applicantName || payload.form.employeeId; if (keyword) { - const data = await listOaEmployees(agentId, { keyword, page: 1, page_size: 1 }); + const data = await listOaEmployees(currentAgentId.value, { keyword, page: 1, page_size: 1 }); const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId); if (match) { payload.form.fillerJobTitle = match.jobtitle || ''; @@ -2059,6 +2062,7 @@ const displayHistory = computed(() => { const server = history.value || []; const serverIds = new Set(server.map((h) => h.conversation_id)); const pending: DisplayHistoryItem[] = (runs.value || []) + .filter((r) => r.agentId === currentAgentId.value) .filter((r) => r.runId !== activeRunId.value) .map((r) => ({ id: 0, @@ -2079,7 +2083,7 @@ const handleHistorySelect = (item: DisplayHistoryItem) => { if (item.__runId) { activateRun(item.__runId); } else { - const run = runs.value.find((r) => r.conversationId === item.conversation_id); + const run = runs.value.find((r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id); if (run && run.status === 'running') { activateRun(run.runId); } else { @@ -2138,7 +2142,7 @@ const handleSend = async (textOrEvent?: string | Event) => { if (typeof textOrEvent !== 'string') input.value = ''; attachments.value = []; - await sendMessage(content, agentId, selectedKb.value, files); + await sendMessage(content, currentAgentId.value, selectedKb.value, files); if (!conversationId.value && history.value.length === 0) { await loadHistory(); @@ -2355,7 +2359,7 @@ const regenerate = () => { // 加载历史记录 const loadHistory = async () => { try { - history.value = await listChatSessions(agentId); + history.value = await listChatSessions(currentAgentId.value); } catch (e) { console.error('Failed to load history', e); } @@ -2364,7 +2368,7 @@ const loadHistory = async () => { const clearAllHistory = async () => { openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => { try { - await deleteAllChatSessions(agentId); + await deleteAllChatSessions(currentAgentId.value); history.value = []; runs.value = []; if (conversationId.value || activeRunId.value) { @@ -2380,7 +2384,7 @@ const deleteHistoryItem = async (id: string, event: Event) => { event.stopPropagation(); openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => { try { - await deleteChatSession(id, agentId); + await deleteChatSession(id, currentAgentId.value); history.value = history.value.filter(h => h.conversation_id !== id); if (conversationId.value === id) { startNewChat(); @@ -2397,7 +2401,7 @@ const loadConversation = async (id: string) => { try { activeRunId.value = null; isThinking.value = false; - messages.value = await listChatMessages(id, agentId); + messages.value = await listChatMessages(id, currentAgentId.value); conversationId.value = id; } catch (e) { console.error('Failed to load conversation', e); @@ -2410,7 +2414,7 @@ const startNewChat = () => { const loadAgent = async () => { try { - currentAgent.value = await getUserAgent(agentId); + currentAgent.value = await getUserAgent(currentAgentId.value); } catch (e) { if (e instanceof BusinessError && e.status === 403) { msg.error(t('workspace.permission.denied') || 'Access denied'); @@ -2426,7 +2430,7 @@ const loadUserAgents = async () => { try { const agents = await listUserAgents(); userAgents.value = Array.isArray(agents) - ? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow') + ? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow') : []; if (userAgents.value.length === 0) { showAgentPanel.value = false; @@ -2438,10 +2442,9 @@ const loadUserAgents = async () => { }; const switchToAgent = (agent: { id: number; name: string }) => { - if (agent.id === agentId) return; + if (agent.id === currentAgentId.value) return; setLastChatAgentId(agent.id); - const url = router.resolve(`/chat/${agent.id}`).href; - openAgentChatTab(url, agent.id); + router.push(`/chat/${agent.id}`); }; const syncOpenAgentRegistration = () => { @@ -2454,16 +2457,63 @@ const onPageHide = () => { }; const goToWorkspace = (view?: string) => { - setLastChatAgentId(Number(route.params.agentId)); + setLastChatAgentId(currentAgentId.value); registerOpenAgentId(null); const query: Record = { no_redirect: '1' }; if (view) query.view = view; router.push({ path: '/workspace', query }); }; +const resetChatStateForAgentChange = () => { + createNewChatView(); + history.value = []; + attachments.value = []; + input.value = ''; + currentAgent.value = null; + copiedIndex.value = null; + showAttachmentMenu.value = false; + filePreviewVisible.value = false; + previewFile.value = null; +}; + +let routeSyncToken = 0; + +const syncChatStateForRoute = async () => { + const agentId = currentAgentId.value; + if (!agentId) return; + + const syncToken = ++routeSyncToken; + resetChatStateForAgentChange(); + stopVoiceInput(); + setLastChatAgentId(agentId); + syncOpenAgentRegistration(); + + await syncCurrentUserProfile(); + if (syncToken !== routeSyncToken) return; + + await loadAgent(); + if (syncToken !== routeSyncToken) return; + + await loadUserAgents(); + if (syncToken !== routeSyncToken) return; + + await loadHistory(); + if (syncToken !== routeSyncToken) return; + + const convId = route.query.conversation_id as string; + if (convId) { + await loadConversation(convId); + if (syncToken !== routeSyncToken) return; + } + + if (presetQuestion.value) { + input.value = presetQuestion.value; + await handleSend(); + } +}; + // 组件挂载时,如果存在预设问题,则自动触发一次发送 onMounted(async () => { - syncOpenAgentRegistration(); window.addEventListener('pagehide', onPageHide); window.addEventListener('hxops:logout', onAuthLogout); document.addEventListener('mousedown', handleDocumentPointerDown); @@ -2471,33 +2521,23 @@ onMounted(async () => { document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside); document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true }); window.addEventListener('resize', syncViewportWidth); - await syncCurrentUserProfile(); - setLastChatAgentId(Number(route.params.agentId)); - await loadAgent(); - await loadUserAgents(); - - await loadHistory(); - - const convId = route.query.conversation_id as string; - if (convId) { - await loadConversation(convId); - } - - if (presetQuestion.value) { - input.value = presetQuestion.value; - handleSend(); - } + await syncChatStateForRoute(); // Use config from config.ts instead of API showChatRating.value = config.workspace?.showChatRating ?? true; scheduleScrollChatToBottom(); }); watch( - () => route.params.agentId, - (id) => { - const nextId = Number(id); - if (Number.isFinite(nextId) && nextId > 0) setLastChatAgentId(nextId); - syncOpenAgentRegistration(); + () => [route.params.agentId, route.query.conversation_id, route.query.preset], + async ([nextAgentId, nextConversationId, nextPreset], [prevAgentId, prevConversationId, prevPreset]) => { + if ( + nextAgentId === prevAgentId + && nextConversationId === prevConversationId + && nextPreset === prevPreset + ) { + return; + } + await syncChatStateForRoute(); } ); @@ -3498,7 +3538,7 @@ const showChatRating = ref(false); { msg.warning(t('login.loginRequired')); return; } - const url = router.resolve(`/chat/${id}`).href; - openAgentChatTab(url, id); + router.push(`/chat/${id}`); }; const navigateWithQuickQuestion = (agentId: number, question: string) => { @@ -1123,11 +1121,10 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => { msg.warning(t('login.loginRequired')); return; } - const url = router.resolve({ + router.push({ path: `/chat/${agentId}`, query: { preset: question }, - }).href; - openAgentChatTab(url, agentId); + }); }; const handleWecomDeeplinkContext = async () => { @@ -1156,11 +1153,11 @@ const handleWecomDeeplinkContext = async () => { if (target === 'chat' && agentIdRaw && isLoggedIn.value) { const agentId = Number(agentIdRaw); if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) { - const url = router.resolve({ + await router.push({ path: `/chat/${agentId}`, query: preset ? { preset } : {}, - }).href; - openAgentChatTab(url, agentId); + }); + return; } }