kongdeqiang
2026-10-12 ed3c2513c35efa714f2a377aef55501dd15d1fec
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
import { defineStore } from 'pinia'
import { computed, reactive, ref } from 'vue'
import * as chatApi from '@/api/chatApi'
import * as chatGroupApi from '@/api/chatGroupApi'
import { filenameFromDisposition, saveBlob } from '@/utils/download'
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([])
 
  /**
   * 已归档的会话。
   *
   * 单独一份而不是和 chats 混在一起靠字段过滤:
   * 主列表与归档列表是**两个视图**,各自有独立的加载时机与搜索关键词,
   * 混在一起后每次渲染都要过滤,很容易出现「归档了但主列表还显示」这类
   * 状态不一致。分开存放,归档动作就是把元素从一个数组搬到另一个。
   */
  const archivedChats = ref([])
  /** 归档列表是否已加载过 —— 用于区分「确实没有归档」和「还没查」 */
  const archiveLoaded = ref(false)
 
  /**
   * 用户自建的分组(文件夹)。
   *
   * 只存分组本身;「哪些会话在哪个分组里」由每条会话的 groupId 决定,
   * 前端按它分桶。这样移动会话只需要刷新会话列表,不必再拉一次分组。
   */
  const chatGroups = 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 会让标题栏、模型参数抽屉一起变空
      archivedChats.value.find((chat) => chat.id === activeChatId.value) ||
      null
  )
 
  // ============================================================
  // 会话
  // ============================================================
 
  async function loadChats() {
    chats.value = await chatApi.listChats(false)
    return chats.value
  }
 
  /** 加载归档列表 */
  async function loadArchivedChats() {
    archivedChats.value = await chatApi.listChats(true)
    archiveLoaded.value = true
    return archivedChats.value
  }
 
  // ---------------- 自建分组 ----------------
 
  async function loadChatGroups() {
    chatGroups.value = await chatGroupApi.listChatGroups()
    return chatGroups.value
  }
 
  async function createChatGroup(name) {
    const group = await chatGroupApi.createChatGroup(name)
    chatGroups.value.push(group)
    return group
  }
 
  async function renameChatGroup(groupId, name) {
    const updated = await chatGroupApi.renameChatGroup(groupId, name)
    const index = chatGroups.value.findIndex((g) => g.id === groupId)
    if (index !== -1) {
      chatGroups.value[index] = updated
    }
    return updated
  }
 
  /**
   * 删除分组:组内会话回到「未分组」。
   *
   * 必须重新拉会话列表 —— 会话本身没变(还在原处、还是原来的时间),
   * 但它们的 groupId 已经被后端清空,不刷新的话它们会挂在一个
   * 已经不存在分组下而整个消失。
   */
  async function deleteChatGroup(groupId) {
    const result = await chatGroupApi.deleteChatGroup(groupId)
    chatGroups.value = chatGroups.value.filter((g) => g.id !== groupId)
    await loadChats()
    return result?.movedChats ?? 0
  }
 
  /** 把会话移入 / 移出分组(groupId 传 null 表示移出) */
  async function moveChatToGroup(chatId, groupId) {
    const updated = await chatApi.moveChatToGroup(chatId, groupId)
    replaceInLists(updated)
    // 分组数字要跟着变,同时刷新顺序(后端仍按置顶/活跃排序)
    await Promise.all([loadChats(), loadChatGroups()])
    return updated
  }
 
  // ---------------- 搜索历史对话 ----------------
 
  /**
   * 建一个独立的搜索器。
   *
   * 主列表与归档列表要各有一份关键词与结果,所以做成工厂而不是两组变量:
   * 两组变量意味着「请求序号、竞态丢弃、loading 状态」这套逻辑要写两遍,
   * 而它恰恰是最容易写漏、写错的部分。
   */
  function createSearcher(archived) {
    /** 搜索关键词;为空表示未处于搜索态 */
    const keyword = ref('')
    /** 搜索结果(ChatDTO 数组,带 matchSnippet / matchType) */
    const results = ref([])
    const loading = ref(false)
    /**
     * 请求序号。搜索是「输入即查」,慢的旧请求可能后于新请求返回,
     * 直接把旧结果写进去就会出现「输入了新词却显示旧结果」。
     */
    let seq = 0
 
    async function run(raw) {
      const kw = (raw || '').trim()
      keyword.value = kw
 
      if (!kw) {
        results.value = []
        loading.value = false
        return []
      }
 
      const mine = ++seq
      loading.value = true
      try {
        const found = await chatApi.searchChats(kw, 30, archived)
        if (mine !== seq) {
          // 已有更新的请求发出,丢弃这次的结果
          return results.value
        }
        results.value = Array.isArray(found) ? found : []
        return results.value
      } catch (error) {
        if (mine === seq) {
          results.value = []
        }
        throw error
      } finally {
        if (mine === seq) {
          loading.value = false
        }
      }
    }
 
    function clear() {
      seq++   // 让在途请求失效
      keyword.value = ''
      results.value = []
      loading.value = false
    }
 
    return { keyword, results, loading, run, clear }
  }
 
  const mainSearch = createSearcher(false)
  const archiveSearch = createSearcher(true)
 
  // 主列表搜索:保留扁平命名,侧边栏直接用这些。
  //
  // 注意 Pinia 只对 **顶层** 返回的 ref 做自动解包:这里以顶层成员暴露,
  // 组件里就能直接 `chatStore.searchKeyword`;如果把整个 searcher 对象
  // 暴露出去,里面每个 ref 都得写 `.value`,极易写错。
  const searchKeyword = mainSearch.keyword
  const searchResults = mainSearch.results
  const searching = mainSearch.loading
  const searchChats = mainSearch.run
  const clearSearch = mainSearch.clear
 
  // 归档列表的搜索:同样以顶层成员暴露
  const archiveKeyword = archiveSearch.keyword
  const archiveResults = archiveSearch.results
  const archiveSearching = archiveSearch.loading
  const searchArchive = archiveSearch.run
  const clearArchiveSearch = archiveSearch.clear
 
  async function createChat(payload = {}) {
    const chat = await chatApi.createChat(payload)
    // 新会话插到最前,符合「最近活跃在最上」的排序约定
    chats.value.unshift(chat)
    return chat
  }
 
  /**
   * 用服务端返回的最新对象替换本地缓存里的同一条。
   *
   * 同时查两份列表:一条会话可能既不在主列表(已归档)也不在归档列表
   * (刚恢复),只查 chats 会让归档对话的重命名「看起来没生效」。
   */
  function replaceInLists(updated) {
    for (const list of [chats.value, archivedChats.value]) {
      const index = list.findIndex((chat) => chat.id === updated.id)
      if (index !== -1) {
        // 用替换而不是 Object.assign:保证所有字段都与后端一致
        list[index] = updated
      }
    }
    return updated
  }
 
  async function renameChat(chatId, title) {
    return replaceInLists(await chatApi.updateChat(chatId, { title }))
  }
 
  async function updateChatMeta(chatId, meta) {
    return replaceInLists(await chatApi.updateChat(chatId, { meta }))
  }
 
  /**
   * 置顶 / 取消置顶。
   *
   * 操作完重新拉取主列表,而不是本地改一个字段了事:
   * 置顶会改变这条会话在列表中的**位置**(进入置顶区),
   * 而排序规则在后端(pinned DESC, pinned_at DESC, updated_at DESC)。
   * 本地自己排一遍就会出现「前端顺序和后端顺序不一致」,
   * 刷新一次又跳回去 —— 让唯一的排序权威留在后端,前端只负责分组。
   */
  async function setPinned(chatId, pinned) {
    const updated = await chatApi.updateChat(chatId, { pinned })
    replaceInLists(updated)
    await loadChats()
    return updated
  }
 
  /**
   * 归档 / 取消归档。
   *
   * 归档是一次「跨列表搬移」:主列表少一条、归档列表多一条。
   * 两份列表都重新拉,保证两边都一致(归档列表还要按归档时间倒序)。
   */
  async function setArchived(chatId, archived) {
    const updated = await chatApi.updateChat(chatId, { archived })
    await Promise.all([loadChats(), loadArchivedChats()])
    return updated
  }
 
  async function removeChat(chatId) {
    await chatApi.deleteChat(chatId)
    chats.value = chats.value.filter((chat) => chat.id !== chatId)
    archivedChats.value = archivedChats.value.filter((chat) => chat.id !== chatId)
    // 搜索结果里也可能残留这一条,一并清掉,避免点进去报 404
    mainSearch.results.value = mainSearch.results.value.filter((chat) => chat.id !== chatId)
    archiveSearch.results.value = archiveSearch.results.value.filter((chat) => chat.id !== chatId)
 
    if (activeChatId.value === chatId) {
      activeChatId.value = null
      tree.value = []
      clearSelections()
    }
  }
 
  /**
   * 下载会话为 json / txt / pdf。
   *
   * 文件名优先用服务端 Content-Disposition 里的建议名(它带了标题与时间戳),
   * 拿不到时才用本地拼的兜底名。
   *
   * @returns {Promise<string>} 实际保存的文件名
   */
  async function exportChat(chatId, format) {
    const response = await chatApi.exportChat(chatId, format)
    const blob = response.data
    const disposition = response.headers?.['content-disposition']
    const chat = chats.value.find((c) => c.id === chatId)
      || archivedChats.value.find((c) => c.id === chatId)
    const fallback = `${chat?.title || '对话'}_${chatId}.${format}`
 
    const filename = filenameFromDisposition(disposition) || fallback
    saveBlob(blob, filename)
    return filename
  }
 
  // ============================================================
  // 消息树
  // ============================================================
 
  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()
            // 会话被归档时不在主列表里,标题等变化只体现在归档列表,
            // 不刷新就会出现「在归档对话里聊完,标题还是旧的」
            if (archivedChats.value.some((chat) => chat.id === chatId)) {
              await loadArchivedChats()
            }
          } 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,
    archivedChats,
    archiveLoaded,
    chatGroups,
    activeChatId,
    tree,
    streaming,
    streamError,
    streamingMessageId,
    selections,
    // getters
    nodeMap,
    path,
    activeChat,
    // actions
    loadChats,
    loadArchivedChats,
    loadChatGroups,
    createChatGroup,
    renameChatGroup,
    deleteChatGroup,
    moveChatToGroup,
    searchKeyword,
    searchResults,
    searching,
    searchChats,
    clearSearch,
    // 归档列表的搜索(独立的另一套状态)
    archiveKeyword,
    archiveResults,
    archiveSearching,
    searchArchive,
    clearArchiveSearch,
    createChat,
    renameChat,
    updateChatMeta,
    setPinned,
    setArchived,
    exportChat,
    removeChat,
    loadMessages,
    switchBranch,
    getBranchPosition,
    editMessage,
    removeMessage,
    sendMessage,
    regenerate,
    stopStreaming,
    resetView
  }
})