import { defineStore } from 'pinia' import { computed, reactive, ref } from 'vue' import * as chatApi from '@/api/chatApi' import { useAuthStore } from './authStore' import { streamChat as openSseStream } from '@/utils/sse' import { branchPosition, buildPath, extractActiveChildIds, flattenTree, switchBranch as switchBranchSelection } from '@/utils/treeBuild' // 乐观消息使用的临时 id。用负数避免与服务端自增 id(恒为正)冲突, // 这样替换真实 id 时不会出现「临时 id 恰好等于某条真实消息 id」的错乱。 let tempIdSeed = -1 const nextTempId = () => tempIdSeed-- /** * 会话与消息状态。 * * ## 消息树的状态模型 * * 后端返回嵌套树,我们额外维护三样东西: * - `tree` 原始嵌套树(唯一数据源,只被接口返回值覆盖) * - `nodeMap` 扁平索引,O(1) 查任意节点 * - `selections` parentId -> 选中的 childId,记录用户在分支间的选择 * * 渲染用的线性路径由 `path` 计算属性实时推导,不单独存储 —— * 避免「树改了但路径没同步」这类经典的状态不一致 bug。 */ export const useChatStore = defineStore('chat', () => { const chats = ref([]) const activeChatId = ref(null) const tree = ref([]) /** parentId -> childId,用户的分支选择 */ const selections = reactive({}) const streaming = ref(false) const streamError = ref('') /** 流式过程中被增量更新的消息 id,用于 UI 高亮「正在输入」 */ const streamingMessageId = ref(null) /** 当前 SSE 连接的控制器,用于「停止生成」 */ let streamController = null const nodeMap = computed(() => flattenTree(tree.value)) const path = computed(() => buildPath(tree.value, selections)) const activeChat = computed( () => chats.value.find((chat) => chat.id === activeChatId.value) || null ) // ============================================================ // 会话 // ============================================================ async function loadChats() { chats.value = await chatApi.listChats() return chats.value } // ---------------- 搜索历史对话 ---------------- /** 搜索关键词;为空表示未处于搜索态 */ const searchKeyword = ref('') /** 搜索结果(ChatDTO 数组,带 matchSnippet / matchType) */ const searchResults = ref([]) const searching = ref(false) /** * 请求序号。 * * 搜索是「输入即查」,慢的旧请求可能后于新请求返回, * 直接把旧结果写进去就会出现「输入了新词却显示旧结果」。 * 每次发起递增并记住序号,回来时对不上就丢弃。 */ let searchSeq = 0 async function searchChats(keyword) { const kw = (keyword || '').trim() searchKeyword.value = kw if (!kw) { searchResults.value = [] searching.value = false return [] } const seq = ++searchSeq searching.value = true try { const results = await chatApi.searchChats(kw) if (seq !== searchSeq) { // 已有更新的请求发出,丢弃这次的结果 return searchResults.value } searchResults.value = Array.isArray(results) ? results : [] return searchResults.value } catch (error) { if (seq === searchSeq) { searchResults.value = [] } throw error } finally { if (seq === searchSeq) { searching.value = false } } } /** 退出搜索态,恢复显示完整会话列表 */ function clearSearch() { searchSeq++ // 让在途请求失效 searchKeyword.value = '' searchResults.value = [] searching.value = false } async function createChat(payload = {}) { const chat = await chatApi.createChat(payload) // 新会话插到最前,符合「最近活跃在最上」的排序约定 chats.value.unshift(chat) return chat } async function renameChat(chatId, title) { const updated = await chatApi.updateChat(chatId, { title }) const index = chats.value.findIndex((chat) => chat.id === chatId) if (index !== -1) { // 用替换而不是 Object.assign:保证所有字段都与后端一致 chats.value[index] = updated } return updated } async function updateChatMeta(chatId, meta) { const updated = await chatApi.updateChat(chatId, { meta }) const index = chats.value.findIndex((chat) => chat.id === chatId) if (index !== -1) { chats.value[index] = updated } return updated } async function removeChat(chatId) { await chatApi.deleteChat(chatId) chats.value = chats.value.filter((chat) => chat.id !== chatId) if (activeChatId.value === chatId) { activeChatId.value = null tree.value = [] clearSelections() } } // ============================================================ // 消息树 // ============================================================ function clearSelections() { for (const key of Object.keys(selections)) { delete selections[key] } } /** * 加载会话的消息树。 * * @param {number} chatId * @param {boolean} preserveSelections * true 时保留用户已有的分支选择(流式结束后刷新用), * false 时按后端给的 activeChildId 重建(切换会话用)。 */ async function loadMessages(chatId, preserveSelections = false) { const previous = preserveSelections ? { ...selections } : null const data = await chatApi.listMessages(chatId) tree.value = Array.isArray(data) ? data : [] activeChatId.value = chatId clearSelections() Object.assign(selections, extractActiveChildIds(tree.value)) // 保留用户的选择:用户手动切到分支 1 后,刷新消息不应跳回分支 2 if (previous) { for (const [parentId, childId] of Object.entries(previous)) { const node = nodeMap.value.get(Number(parentId)) if (node?.children?.some((child) => child.id === Number(childId))) { selections[parentId] = Number(childId) } } } return tree.value } /** 切换某个多分支节点下选中的子分支 */ function switchBranch(message, delta) { return switchBranchSelection(message, delta, selections) } /** 查询某个节点当前显示第几个分支 */ function getBranchPosition(message) { return branchPosition(message, selections) } /** 把一条消息挂到指定父节点下(用于乐观渲染) */ function appendMessage(message, parentId) { if (parentId == null) { tree.value.push(message) return } const parent = nodeMap.value.get(parentId) if (!parent) { // 父节点不在当前树里(理论上不该发生),退化为追加到根,保证消息不丢 tree.value.push(message) return } if (!Array.isArray(parent.children)) { parent.children = [] } parent.children.push(message) // 新消息默认成为该父节点下的活跃分支 selections[parentId] = message.id } /** 用真实 id 替换乐观消息的临时 id */ function replaceMessageId(tempId, realId) { for (const node of nodeMap.value.values()) { if (node.id === tempId) { node.id = realId break } } for (const [parentId, childId] of Object.entries(selections)) { if (childId === tempId) { selections[parentId] = realId } } } /** 增量追加流式内容 */ function appendContent(messageId, delta) { const node = nodeMap.value.get(messageId) if (node) { node.content = (node.content || '') + delta } } /** 流结束时用完整内容校准(防止网络丢块导致内容不一致) */ function finalizeMessage(messageId, content, sources) { const node = nodeMap.value.get(messageId) if (!node) return node.done = true if (typeof content === 'string' && content.length > 0) { node.content = content } if (Array.isArray(sources) && sources.length > 0) { node.sources = sources } } function markMessageFailed(messageId, reason) { const node = nodeMap.value.get(messageId) if (!node) return node.done = true node.failed = true if (!node.content) { node.content = `(生成失败:${reason})` } } async function editMessage(chatId, messageId, content) { await chatApi.updateMessage(chatId, messageId, { content }) const node = nodeMap.value.get(messageId) if (node) { node.content = content } } async function removeMessage(chatId, messageId) { await chatApi.deleteMessage(chatId, messageId) await loadMessages(chatId, true) } // ============================================================ // 流式对话 // ============================================================ /** * 发送一条消息并接收流式回复。 * * 时序: * 1. 立即插入临时 user 消息 + 空 assistant 气泡(乐观渲染,零延迟反馈) * 2. 建立 SSE 连接 * 3. start 事件到达 → 把临时 id 换成服务端真实 id * 4. delta 事件 → 追加文本 * 5. done 事件 → 校准内容并重新加载整棵树(拿到服务端权威结构) * * @param {object} options * @param {number} options.chatId * @param {string} options.content * @param {number|null} [options.parentId] 挂载点;为空表示接在当前分支末尾 * @param {string|null} [options.model] * @param {boolean} [options.useRag] * @returns {Promise} */ async function sendMessage({ chatId, content, parentId = null, model = null, useRag = true, imageText = null, imageTextId = null, imageFileIds = null }) { if (streaming.value) { throw new Error('上一条回复还在生成中,请稍候或先停止生成') } // 允许「只发图片、不打字」:此时内容为空但图片存在 const hasImages = Array.isArray(imageFileIds) && imageFileIds.length > 0 if ((!content || !content.trim()) && !hasImages) { throw new Error('消息内容不能为空') } streamError.value = '' // 确定挂载点:显式传入优先,否则取当前渲染路径的最后一个节点 const effectiveParentId = parentId ?? (path.value.length > 0 ? path.value[path.value.length - 1].id : null) // ---- 乐观渲染 ---- const tempUserId = nextTempId() const tempAssistantId = nextTempId() const now = new Date().toISOString() // 图片为空时传 null,避免后端收到空数组还去写 metadata const effectiveImageIds = hasImages ? imageFileIds : null appendMessage( { id: tempUserId, chatId, parentId: effectiveParentId, role: 'user', content, done: true, pending: true, createdAt: now, // 乐观渲染阶段就把图片挂上,用户立刻看到自己发出去的图 imageFileIds: effectiveImageIds, children: [] }, effectiveParentId ) appendMessage( { id: tempAssistantId, chatId, parentId: tempUserId, role: 'assistant', content: '', done: false, pending: true, createdAt: now, children: [] }, tempUserId ) streaming.value = true streamingMessageId.value = tempAssistantId // 记录 id 映射,供事件回调使用 let userId = tempUserId let assistantId = tempAssistantId const auth = useAuthStore() const query = new URLSearchParams({ content, useRag: String(useRag) }) // 优先用暂存 id:长文本走 query 会触发 Tomcat 请求行上限 if (imageTextId) { query.set('imageTextId', imageTextId) } else if (imageText) { query.set('imageText', imageText) } if (effectiveImageIds) { // 后端用 List 接收,重复 key 即多个值 effectiveImageIds.forEach((id) => query.append('imageFileIds', String(id))) } if (effectiveParentId != null) { query.set('parentId', String(effectiveParentId)) } if (model) { query.set('model', model) } return new Promise((resolve) => { streamController = openSseStream({ url: `/api/chats/${chatId}/stream?${query.toString()}`, token: auth.token, onEvent(eventName, payload) { switch (eventName) { case 'start': { // 用服务端真实 id 替换临时 id if (payload.userMessageId) { replaceMessageId(userId, payload.userMessageId) userId = payload.userMessageId } if (payload.messageId) { replaceMessageId(assistantId, payload.messageId) assistantId = payload.messageId streamingMessageId.value = assistantId } if (payload.model) { const node = nodeMap.value.get(assistantId) if (node) node.model = payload.model } break } case 'delta': { appendContent(assistantId, payload.delta || '') break } case 'title': { // 后端自动生成了会话标题,同步到侧边栏 const chat = chats.value.find((item) => item.id === chatId) if (chat && payload.title) { chat.title = payload.title } break } case 'done': { finalizeMessage(assistantId, payload.content, payload.sources) break } case 'error': { streamError.value = payload.error || '生成失败' markMessageFailed(assistantId, streamError.value) break } default: break } }, onError(error) { streamError.value = error.message markMessageFailed(assistantId, error.message) }, async onClose() { // 收尾必须无条件恢复「可发送」状态。 // 之前这里依赖 sse.js 一定回调 onClose;一旦异常路径漏掉回调, // streaming 就卡在 true,发送按钮永久变灰,只能刷新页面。 // sse.js 现在保证 onClose 恰好触发一次,这里再确保收尾逻辑本身 // 不会因为中间某步抛错而提前中断。 streaming.value = false streamingMessageId.value = null streamController = null // 乐观消息的 pending 标记该清掉了 for (const node of nodeMap.value.values()) { if (node.pending) node.pending = false } // 重新拉取整棵树,拿到服务端的权威结构(含真正的 id、done 状态、 // 以及首条提问生成的标题)。保留用户的分支选择,避免视图跳动。 // // 但只有「用户仍然停留在本次流所属的会话」时才刷新: // 若用户在生成过程中切到了别的会话,这里的 loadMessages(chatId) // 会把新会话的消息树覆盖成旧会话的,属于典型的异步竞态。 try { if (activeChatId.value === chatId) { await loadMessages(chatId, true) } await loadChats() } catch { // 刷新失败不影响已渲染的内容,静默处理 } resolve() } }) }) } /** * 重新生成:以某条 user 消息为父节点,再生成一个 assistant 分支。 * * 这是消息树「分支」能力的入口 —— 新回复会成为已有回复的兄弟节点, * 前端用分支切换器在它们之间切换。 */ async function regenerate({ chatId, userMessageId, model = null, useRag = true }) { const userNode = nodeMap.value.get(userMessageId) if (!userNode) { throw new Error('找不到要重新生成的消息') } if (!userNode.content) { throw new Error('该消息内容为空,无法重新生成') } // parentId 传 user 消息本身,后端会把新 assistant 挂在它下面, // 从而与既有的 assistant 回复形成兄弟关系 // 把原消息的图片一并带上,否则重新生成会丢掉图片上下文, // 同一个问题却得到「不知道你在说什么」的回答 return sendMessage({ chatId, content: userNode.content, parentId: userMessageId, model, useRag, imageText: userNode.imageText || null, // 原消息落库时存的是文字本身,重新生成时重新暂存换取新 id imageTextId: null, imageFileIds: userNode.imageFileIds || null }) } /** * 主动停止生成。 * * 中断连接会让后端的 onCompletion/onError 触发,那里会 cancel 掉生成线程 * 并释放 SseEmitter —— 这是防泄漏的关键路径。 */ function stopStreaming() { // 先把控制器摘下来,避免 abort() 触发的回调(onClose)里再次访问它 const controller = streamController streamController = null // 立即无条件恢复可发送状态。 // 顺序很关键:必须在 abort() 之前就把 streaming 置 false。 // abort() 会同步触发 sse.js 的 onClose,而 onClose 内部还有一步 // 「重新拉取消息树」的 async 逻辑;若把它当作恢复 streaming 的唯一 // 途径,一旦该回调因为任何原因没走到(例如切会话时被竞态打断), // streaming 就会永久卡在 true,发送按钮变灰且只能刷新页面。 streaming.value = false streamingMessageId.value = null if (controller) { controller.abort() } // 把仍在生成中的气泡标记为已完成,避免一直显示「输入中」 for (const node of nodeMap.value.values()) { if (node.pending) node.pending = false if (node.done === false && node.role === 'assistant') { node.done = true node.stopped = true } } } /** 切换会话时清空当前视图状态 */ function resetView() { stopStreaming() tree.value = [] clearSelections() streamError.value = '' } return { // state chats, activeChatId, tree, streaming, streamError, streamingMessageId, selections, // getters nodeMap, path, activeChat, // actions loadChats, searchKeyword, searchResults, searching, searchChats, clearSearch, createChat, renameChat, updateChatMeta, removeChat, loadMessages, switchBranch, getBranchPosition, editMessage, removeMessage, sendMessage, regenerate, stopStreaming, resetView } })