Files
syops/frontend/src/features/chat/composables/useChatPage.ts
T

494 lines
16 KiB
TypeScript

/**
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
*/
import { computed, markRaw, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { config } from '@/config';
import { useMessage } from '@/shared/composables/useMessage';
import { useIsMobile } from '@/shared/composables/useIsMobile';
import { useTheme } from '@/shared/composables/useTheme';
import { listChatMessages } from '../api/chat.api';
import { stripReasoningPrelude } from '../utils/chatText';
import type { ChatDeps } from './chat.deps';
import { useChat } from './useChat';
import { useChatAgent } from './useChatAgent';
import { useChatAttachments } from './useChatAttachments';
import { useChatBrowserPanel } from './useChatBrowserPanel';
import { useChatGuides } from './useChatGuides';
import { useChatLeave } from './useChatLeave';
import { useChatQueryPreview } from './useChatQueryPreview';
import { useChatRouteSync } from './useChatRouteSync';
import { useChatScroll } from './useChatScroll';
import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatStore } from '../stores/chat.store';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
createChatPageMarkdownApi,
createChatPageSendApi,
createLeaveMessageHandlers,
createShippingMappingHandlers,
createShippingPickerRefHolder,
useChatPageDialogs,
useChatPageUser,
useChatPageVoice,
useChatPageToolRun,
} from '../page';
import type { ChatMessage } from '../types/chat.types';
const getLatestAssistantMessage = (items: ChatMessage[]) => {
for (let i = items.length - 1; i >= 0; i -= 1) {
if (items[i]?.role === 'assistant') {
return items[i];
}
}
return null;
};
const hasMeaningfulAssistantMessage = (message: ChatMessage | null | undefined) => {
if (!message) return false;
if (String(message.content || '').trim()) return true;
return Boolean(message.type && message.type !== 'text');
};
const shouldApplyServerConversationSnapshot = (localMessages: ChatMessage[], serverMessages: ChatMessage[]) => {
if (serverMessages.length < localMessages.length) return false;
const localAssistant = getLatestAssistantMessage(localMessages);
if (!hasMeaningfulAssistantMessage(localAssistant)) return true;
const serverAssistant = getLatestAssistantMessage(serverMessages);
if (!hasMeaningfulAssistantMessage(serverAssistant)) return false;
const localContent = String(localAssistant?.content || '').trim();
const serverContent = String(serverAssistant?.content || '').trim();
if (!localContent) return true;
if (!serverContent) return false;
if (serverContent.length < localContent.length) return false;
return serverContent.includes(localContent);
};
export function useChatPage() {
const { t, locale } = useI18n();
const route = useRoute();
const router = useRouter();
const msg = useMessage();
const { isMobile } = useIsMobile();
const { appliedTheme, toggleLightDark } = useTheme();
const deps: ChatDeps = { t, locale, msg, router, route };
const chatStore = useChatStore();
const { sidebarCollapsed } = storeToRefs(chatStore);
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const { currentUser, currentUserDisplayName, currentUserEmployeeId, onAuthLogout, handleLogout, goToAdmin } =
useChatPageUser(router);
const chatScrollContainer = ref<HTMLElement | null>(null);
/** markRaw:避免 reactive(page) 解包内部 Ref,供 template ref 回写 */
const scrollContainerHolder = markRaw({ el: chatScrollContainer });
const input = ref('');
const isSidebarOpen = ref(false);
const copiedIndex = ref<number | null>(null);
const {
messages,
isThinking,
conversationId,
runs,
activeRunId,
activateRun,
createNewChatView,
loadConversationState,
sendMessage,
} = useChat();
const browser = useChatBrowserPanel({
warn: (text) => msg.warning(text),
invalidUrlMessage: t('chat.invalidBrowserUrl'),
enterUrlMessage: t('chat.enterBrowserUrl'),
});
const queryPreview = useChatQueryPreview({ currentAgentId });
const scroll = useChatScroll({ container: chatScrollContainer, messages });
scroll.setupThinkingScrollWatch(isThinking, conversationId);
let resetShippingConversationState = () => {};
const resetPeripheralState = () => {
browser.close();
queryPreview.close();
resetShippingConversationState();
};
const disposePeripherals = () => {
browser.stopResize();
scroll.dispose();
};
const chatGuides = useChatGuides({ currentAgentId });
const agent = useChatAgent({ deps, currentAgentId, chatGuides });
const attachmentApi = useChatAttachments({
deps,
currentAgentId,
currentAgent: agent.currentAgent,
});
const sourceFiles = useChatSourceFiles({ agentId: currentAgentId, t, msg, isMobile });
const {
filePreviewVisible,
previewFile,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getSourceLinks,
getMessageLinks,
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
parsePlmPreviewLink,
} = sourceFiles;
watch(currentAgentId, (id) => {
chatStore.setCurrentAgentId(id > 0 ? id : null);
}, { immediate: true });
const dialogs = useChatPageDialogs(messages);
const { openDeleteConfirmDialog } = dialogs;
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
let startNewChat: () => void;
const {
history,
loadHistory,
clearHistory,
displayHistory,
activeHistoryKey,
handleHistorySelect,
refreshHistoryAfterSend,
setupConversationIdHistoryWatch,
clearAllHistory,
deleteHistoryItem,
} = useChatSessions({
deps,
currentAgentId,
conversationId,
activeRunId,
runs,
activateRun,
loadConversation: (id, opts) => loadConversation(id, opts),
isSidebarOpen,
onConfirmDelete: openDeleteConfirmDialog,
startNewChat: () => startNewChat(),
});
setupConversationIdHistoryWatch();
const leave = useChatLeave({
deps,
currentAgent: agent.currentAgent,
currentAgentId,
currentUser,
currentUserDisplayName,
currentUserEmployeeId,
messages,
conversationId,
isThinking,
history,
loadHistory,
});
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
conversationId,
currentAgentId,
});
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
const shipping = useChatShipping({
deps,
currentAgent: agent.currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
history,
loadHistory,
input,
chatScrollContainer,
attachments: attachmentApi.attachments,
selectedKb: agent.selectedKb,
isUploadingAttachments: attachmentApi.isUploadingAttachments,
attachmentPolicy: attachmentApi.attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
loadConversation: (id, opts) => loadConversation(id, opts),
createNewChatView,
});
resetShippingConversationState = shipping.resetShippingConversationState;
const conversationApi = createChatPageConversationApi({
deps,
route,
router,
currentAgentId,
conversationId,
activeRunId,
messages,
isThinking,
loadConversationState,
createNewChatView,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
clearHistory,
clearAttachments: attachmentApi.clearAttachments,
input,
resetCurrentAgent: () => { agent.currentAgent.value = null; },
copiedIndex,
resetPeripheralState,
filePreviewVisible,
previewFile,
});
({ loadConversation, startNewChat } = conversationApi);
const { resetChatStateForAgentChange } = conversationApi;
const toolRun = useChatPageToolRun({
currentAgent: agent.currentAgent,
conversationId,
messages,
});
const voice = useChatPageVoice({
input,
isThinking,
msg,
t,
});
const markdown = createChatPageMarkdownApi({
messages,
isThinking,
prepareMarkdownDisplayText: shipping.prepareMarkdownDisplayText,
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
parsePlmPreviewLink,
openPreview,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
shouldExpandSourceDetails,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: shipping.getShippingMatchResultPayload,
canOpenQueryPreview: queryPreview.canOpen,
getQueryPreviewSummary: queryPreview.getSummary,
openQueryPreviewDialog: queryPreview.openDialog,
shippingActionButtonClass: shipping.shippingActionButtonClass,
onShippingActionClick: shipping.handleShippingActionClick,
});
const sendApi = createChatPageSendApi({
input,
messages,
isThinking,
currentAgentId,
selectedKb: agent.selectedKb,
isUploadingAttachments: attachmentApi.isUploadingAttachments,
attachmentPolicy: attachmentApi.attachmentPolicy,
attachments: attachmentApi.attachments,
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
refreshHistoryAfterSend,
refreshConversationAfterSend: async () => {
const currentConversationId = conversationId.value;
const currentAgent = currentAgentId.value;
if (!currentConversationId || !currentAgent) return;
// [STEP 1] 发送刚结束时先保留当前内存快照,避免服务端尚未完整落库的旧消息把新回答覆盖掉。
const localSnapshot = [...messages.value];
const loaded = await listChatMessages(currentConversationId, currentAgent);
const serverMessages = Array.isArray(loaded) ? loaded : [];
// [STEP 2] 若用户已切到其他 Agent/会话,丢弃这个迟到的刷新结果,避免把右侧问答区又切回旧会话。
if (conversationId.value !== currentConversationId || currentAgentId.value !== currentAgent) {
return;
}
// [STEP 3] 仅当服务端快照不比本地旧时才覆盖,修复“答案刚出来就消失”和后续发送被锁死的问题。
if (!shouldApplyServerConversationSnapshot(localSnapshot, serverMessages)) {
return;
}
loadConversationState(currentConversationId, serverMessages);
},
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
tryHandleShippingSend: shipping.tryHandleShippingSend,
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
msg,
t,
copiedIndex,
});
shipping.shippingBindSend(() => sendApi.handleSend());
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const showChatRating = ref(false);
const routeSync = useChatRouteSync({
deps,
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
resetChatStateForAgentChange,
cancelVoiceInput: voice.cancelVoiceInput,
syncCurrentUserProfile: leave.syncCurrentUserProfile,
loadAgent: agent.loadAgent,
loadUserAgents: agent.loadUserAgents,
loadHistory,
loadConversation,
resumeShippingTaskFromQuery: shipping.resumeShippingTaskFromQuery,
handleSend: sendApi.handleSend,
createNewChatView,
onAuthLogout,
onViewportResize: () => browser.syncViewportWidth(),
disposePeripherals,
scheduleScrollToBottom: () => scroll.scheduleScrollToBottom(),
onMountedExtra: () => {
showChatRating.value = config.workspace?.showChatRating ?? true;
},
input,
});
watch(locale, (newLang) => {
localStorage.setItem('hxops_lang', String(newLang));
});
const handleSidebarNewChat = () => {
startNewChat();
isSidebarOpen.value = false;
};
return {
t,
msg,
isMobile,
appliedTheme,
toggleLightDark,
currentAgentId,
currentUser,
chatScrollContainer,
scrollContainerHolder,
messages,
isThinking,
conversationId,
input,
browser,
queryPreview,
browserPanelOpen: browser.open,
browserDraftUrl: browser.draftUrl,
browserCurrentUrl: browser.currentUrl,
browserFrameKey: browser.frameKey,
browserPanelStyle: browser.panelStyle,
isBrowserResizing: browser.isResizing,
showQueryPreviewDialog: queryPreview.show,
queryPreviewLoading: queryPreview.loading,
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
activeGuideId: chatGuides.activeGuideId,
activeGuide: chatGuides.activeGuide,
showGuideSidebar: chatGuides.showSidebar,
openGuideModal: chatGuides.openModal,
...attachmentApi,
filePreviewVisible,
previewFile,
isSidebarOpen,
sidebarCollapsed,
toggleBrowserPanel: browser.toggle,
copiedIndex,
displayHistory,
activeHistoryKey,
handleHistorySelect,
clearAllHistory,
deleteHistoryItem,
isVoiceRecording: voice.isVoiceRecording,
isVoiceTranscribing: voice.isVoiceTranscribing,
handleVoiceFeatureClick: voice.handleVoiceFeatureClick,
...leave,
leaveMessageHandlers,
shippingMappingHandlers,
shippingPickerRefHolder,
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
messageBubbleHandlers: markdown.messageBubbleHandlers,
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
handleSend: sendApi.handleSend,
copyToClipboard: sendApi.copyToClipboard,
regenerate: sendApi.regenerate,
handleOpenFeedback: dialogs.handleOpenFeedback,
activeFeedbackMessageIndex: dialogs.activeFeedbackMessageIndex,
showGeneralFeedbackDialog: dialogs.showGeneralFeedbackDialog,
currentGeneralFeedbackChatLogId: dialogs.currentGeneralFeedbackChatLogId,
showDeleteConfirmDialog: dialogs.showDeleteConfirmDialog,
deleteConfirmMessage: dialogs.deleteConfirmMessage,
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
handleDeleteConfirm: dialogs.handleDeleteConfirm,
showChatRating,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingBatchSummary: shipping.shippingBatchSummary,
shippingBatchTasks: shipping.shippingBatchTasks,
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
shippingBatchTasksExpanded: shipping.shippingBatchTasksExpanded,
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
switchShippingFocusTask: shipping.switchShippingFocusTask,
resumeShippingTask: shipping.resumeShippingTask,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
handleSidebarNewChat,
goToWorkspace: routeSync.goToWorkspace,
switchToAgent: agent.switchToAgent,
loadUserAgents: agent.loadUserAgents,
handleLogout,
goToAdmin,
...toolRun,
};
}