kongdeqiang
2026-10-09 f55d84f8479f35f780c535d2d4f4836727363255
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
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<void>}
   */
  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<Long> 接收,重复 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
  }
})