kongdeqiang
2026-10-10 ad24c871d74a417db5412fd9d1fa60411c33ae7f
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
package com.custom.webui.service.impl;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.config.props.LlmProperties;
import com.custom.webui.config.props.RagProperties;
import com.custom.webui.dto.req.ChatMetaRequest;
import com.custom.webui.dto.req.MessageUpdateRequest;
import com.custom.webui.dto.resp.MessageDTO;
import com.custom.webui.dto.resp.RagChunk;
import com.custom.webui.dto.resp.StreamEvent;
import com.custom.webui.entity.Chat;
import com.custom.webui.entity.ChatCollection;
import com.custom.webui.entity.Message;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.entity.RagCollection;
import com.custom.webui.entity.UploadFile;
import com.custom.webui.entity.ChatCategory;
import com.custom.webui.mapper.ChatCategoryMapper;
import com.custom.webui.mapper.ChatCollectionMapper;
import com.custom.webui.mapper.ChatMapper;
import com.custom.webui.mapper.MessageMapper;
import com.custom.webui.mapper.RagCollectionMapper;
import com.custom.webui.mapper.UploadFileMapper;
import com.custom.webui.service.ChatService;
import com.custom.webui.service.LlmService;
import com.custom.webui.service.MessageService;
import com.custom.webui.service.RagProxyService;
import com.custom.webui.util.MessageTreeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
 
/**
 * 消息与流式对话服务实现。
 *
 * <p><b>流式对话的完整时序</b>(详见 {@link #streamChat}):
 * <pre>
 *  HTTP 请求进入
 *      │
 *      ├─ 同步:校验会话归属、确定 parentId、落库 user 消息
 *      ├─ 同步:创建 done=0 的 assistant 占位消息(前端拿到 id 立即渲染气泡)
 *      ├─ 同步:返回 SseEmitter(HTTP 头此时已提交为 text/event-stream)
 *      │
 *      └─ 异步(sseExecutor 线程池):
 *             RAG 检索 ──> 组装 prompt ──> 调 LLM 流式接口
 *                                              │
 *                      每收到一块 ──────────────┘──> SSE 推送 delta 事件
 *                                              │
 *                       流结束 ──> 写回完整 content + done=1 ──> 推送 done 事件 ──> complete()
 * </pre>
 *
 * <p><b>关键设计决策</b>:
 * <ol>
 *   <li><b>占位消息先行落库</b>:让 done=0 成为「生成中」的持久化状态。
 *       即使服务端进程崩溃,用户刷新后也能看到那条被中断的消息,
 *       而不是凭空消失或永远转圈。</li>
 *   <li><b>定期增量落库</b>:每约 2 秒把已生成的内容写回 DB。
 *       代价是少量额外写,收益是进程被 kill 时最多只丢 2 秒内容。</li>
 *   <li><b>客户端断开即中断生成</b>:onCompletion/onError 回调里 cancel 掉
 *       执行流任务的 Future,让 Thread.interrupt 传到 LLM 读取循环,
 *       及时释放线程 —— 这是防 SSE 内存/线程泄漏的核心。</li>
 * </ol>
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
 
    /** 增量落库间隔(毫秒) */
    private static final long FLUSH_INTERVAL_MILLIS = 2000L;
 
    /** 新建会话的默认标题;标题仍等于它时才用首条提问覆盖 */
    private static final String DEFAULT_CHAT_TITLE = "新对话";
 
    /**
     * 会话标题最大长度(按 Unicode 码点计)。
     * 24 个字在侧边栏单行里大约刚好不溢出,再长就会被 CSS 省略号截断 ——
     * 与其让 CSS 截,不如在后端就截好,前端拿到的标题本身就是完整的短标题。
     */
    private static final int MAX_TITLE_LENGTH = 24;
 
    private final MessageMapper messageMapper;
    private final ChatMapper chatMapper;
    private final ChatCollectionMapper chatCollectionMapper;
    private final RagCollectionMapper ragCollectionMapper;
    private final ChatCategoryMapper chatCategoryMapper;
    private final UploadFileMapper uploadFileMapper;
    private final ChatService chatService;
    private final LlmService llmService;
    private final RagProxyService ragProxyService;
    private final LlmProperties llmProperties;
    private final RagProperties ragProperties;
    private final ObjectMapper objectMapper;
    private final ExecutorService sseExecutor;
 
    /** 定时落库线程池,仅做轻量 DB 写入,1 个线程足够 */
    private final ScheduledExecutorService flusher;
 
    /**
     * 编程式事务模板。
     *
     * <p>为什么不用 {@code @Transactional}:{@code streamChat} 需要<b>同步返回</b>
     * SseEmitter,不能整体包在事务里(会把 HTTP 请求线程和数据库连接一起挂住几分钟)。
     * 因此只有「user 消息 + assistant 占位」这一小段需要原子性,
     * 用 TransactionTemplate 显式圈定范围最清晰,也避免了同类内部方法
     * 自调用导致 @Transactional 失效的经典陷阱。
     */
    private final TransactionTemplate transactionTemplate;
 
    public MessageServiceImpl(MessageMapper messageMapper,
                              ChatMapper chatMapper,
                              ChatCollectionMapper chatCollectionMapper,
                              RagCollectionMapper ragCollectionMapper,
                              ChatCategoryMapper chatCategoryMapper,
                              UploadFileMapper uploadFileMapper,
                              ChatService chatService,
                              LlmService llmService,
                              RagProxyService ragProxyService,
                              LlmProperties llmProperties,
                              RagProperties ragProperties,
                              ObjectMapper objectMapper,
                              PlatformTransactionManager transactionManager,
                              @Qualifier("sseExecutor") ExecutorService sseExecutor) {
        this.messageMapper = messageMapper;
        this.chatMapper = chatMapper;
        this.chatCollectionMapper = chatCollectionMapper;
        this.ragCollectionMapper = ragCollectionMapper;
        this.chatCategoryMapper = chatCategoryMapper;
        this.uploadFileMapper = uploadFileMapper;
        this.chatService = chatService;
        this.llmService = llmService;
        this.ragProxyService = ragProxyService;
        this.llmProperties = llmProperties;
        this.ragProperties = ragProperties;
        this.objectMapper = objectMapper;
        this.sseExecutor = sseExecutor;
        this.transactionTemplate = new TransactionTemplate(transactionManager);
 
        ThreadFactory tf = r -> {
            Thread t = new Thread(r, "sse-flusher");
            t.setDaemon(true);
            return t;
        };
        this.flusher = new ScheduledThreadPoolExecutor(1, tf);
        // 定时任务被取消后立即从队列移除,避免堆积已废弃的 flush 任务
        ((ScheduledThreadPoolExecutor) this.flusher).setRemoveOnCancelPolicy(true);
    }
 
    @PreDestroy
    public void shutdown() {
        flusher.shutdownNow();
    }
 
    // ============================================================
    // 查询与编辑
    // ============================================================
 
    @Override
    public List<MessageDTO> getMessageTree(Long userId, Long chatId) {
        // 先做归属校验,越权直接 404
        chatService.requireOwnedChat(userId, chatId);
 
        List<Message> flat = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getChatId, chatId)
                        .orderByAsc(Message::getCreatedAt)
                        .orderByAsc(Message::getId));
 
        return MessageTreeUtil.buildTree(flat);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageDTO updateMessage(Long userId, Long chatId, Long messageId, MessageUpdateRequest request) {
        Message message = requireOwnedMessage(userId, chatId, messageId);
 
        Message update = new Message();
        update.setId(messageId);
        update.setContent(request.getContent());
        if (request.getModel() != null && !request.getModel().isBlank()) {
            update.setModel(request.getModel().trim());
        }
        // 手动编辑意味着内容已确定,标记为完成,避免前端一直显示「生成中」
        update.setDone(true);
        messageMapper.updateById(update);
 
        // 会话排序需要跟着消息变化走,否则侧边栏顺序会显得错乱
        touchChat(chatId);
 
        Message refreshed = messageMapper.selectById(messageId);
        log.info("编辑消息 messageId={} chatId={} 原长度={} 新长度={}",
                messageId, chatId,
                message.getContent() == null ? 0 : message.getContent().length(),
                request.getContent().length());
        return MessageTreeUtil.toDto(refreshed);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMessage(Long userId, Long chatId, Long messageId) {
        requireOwnedMessage(userId, chatId, messageId);
 
        // 收集自身 + 全部子孙:删中间节点时后续对话已失去上下文,一并删除更符合直觉
        List<Message> all = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery().eq(Message::getChatId, chatId));
 
        Map<Long, List<Long>> childrenByParent = new HashMap<>();
        for (Message m : all) {
            if (m.getParentId() != null) {
                childrenByParent.computeIfAbsent(m.getParentId(), k -> new ArrayList<>()).add(m.getId());
            }
        }
 
        List<Long> toDelete = new ArrayList<>();
        collectSubtree(messageId, childrenByParent, toDelete);
        if (toDelete.isEmpty()) {
            return;
        }
 
        messageMapper.deleteBatchIds(toDelete);
        touchChat(chatId);
        log.info("删除消息子树 chatId={} rootMessageId={} 共删除 {} 条", chatId, messageId, toDelete.size());
    }
 
    /** 深度优先收集子树 id(含自身) */
    private void collectSubtree(Long rootId, Map<Long, List<Long>> childrenByParent, List<Long> acc) {
        acc.add(rootId);
        List<Long> children = childrenByParent.get(rootId);
        if (children == null) {
            return;
        }
        for (Long child : children) {
            collectSubtree(child, childrenByParent, acc);
        }
    }
 
    @Override
    public Message requireOwnedMessage(Long userId, Long chatId, Long messageId) {
        // 先校验会话归属,再校验消息归属,两道关卡都是必要的:
        // 只校验消息的话,攻击者可以构造「自己的会话 id + 他人的消息 id」组合
        chatService.requireOwnedChat(userId, chatId);
 
        Message message = messageMapper.selectById(messageId);
        if (message == null || !message.getChatId().equals(chatId)) {
            throw BusinessException.notFound("消息不存在");
        }
        return message;
    }
 
    @Override
    public Long findLeaflessParent(Long chatId) {
        // 取该会话最新的一条消息作为父节点。
        // 注意这里用「最新」而不是「没有子节点的」,因为用户可能在
        // 中间分支上继续追问,此时该分支已有子节点但最新消息仍在它的子树里。
        List<Message> latest = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getChatId, chatId)
                        .orderByDesc(Message::getCreatedAt)
                        .orderByDesc(Message::getId)
                        .last("LIMIT 1"));
        return latest.isEmpty() ? null : latest.get(0).getId();
    }
 
    // ============================================================
    // SSE 流式对话核心
    // ============================================================
 
    @Override
    public SseEmitter streamChat(Long userId, Long chatId, String content,
                                 Long parentId, String modelName, boolean useRag,
                                 String imageText, List<Long> imageFileIds) {
 
        // 允许「只发图片不打字」:有图片时内容可以为空。
        // 此时给一个占位文案,否则消息树里会出现一条空白气泡,
        // 侧边栏标题、检索 query 也都没有着落。
        boolean hasImages = imageFileIds != null && !imageFileIds.isEmpty();
        if (content == null || content.isBlank()) {
            if (!hasImages) {
                throw BusinessException.badRequest("消息内容不能为空");
            }
            content = "[图片]";
        }
 
        Chat chat = chatService.requireOwnedChat(userId, chatId);
        ChatMetaRequest meta = chatService.parseMeta(chat);
 
        // 确定挂载点:显式指定优先,否则接在当前分支末尾
        Long effectiveParentId = parentId != null ? parentId : findLeaflessParent(chatId);
        if (effectiveParentId != null) {
            // 校验父消息确实属于该会话,防止挂到别的会话的消息上造成跨会话数据污染
            Message parent = messageMapper.selectById(effectiveParentId);
            if (parent == null || !parent.getChatId().equals(chatId)) {
                throw BusinessException.badRequest("parentId 不属于当前会话");
            }
        }
 
        String effectiveModel = (modelName != null && !modelName.isBlank())
                ? modelName.trim()
                : (meta.getModelName() != null && !meta.getModelName().isBlank()
                        ? meta.getModelName() : llmService.defaultModel());
 
        // 同步落库:user 消息 + assistant 占位消息
        PersistResult persisted = persistUserAndPlaceholder(
                chatId, effectiveParentId, content, effectiveModel, imageText, imageFileIds);
 
        // 0L = 永不超时。SSE 连接的生命周期由「流结束」或「客户端断开」决定,
        // 不由超时决定;设成固定值会在长回答生成到一半时把连接掐断。
        //
        // Spring 实现细节:SseEmitter(0L) 会以 0 延迟提交一个超时任务,
        // 该任务执行时未必真的触发 onTimeout(ResponseBodyEmitter 内部
        // 会检查 timeout 是否为 null)。功能上安全,只是多一次空任务调度。
        // 若希望语义更直白,可改用 new SseEmitter(Long.MAX_VALUE)。
        SseEmitter emitter = new SseEmitter(0L);
 
        AtomicReference<Future<?>> taskRef = new AtomicReference<>();
        AtomicBoolean clientGone = new AtomicBoolean(false);
 
        // ---- 客户端断开 / 出错 / 正常完成时的资源回收 ----
        // 这是防泄漏的关键:EventSource.close() 或页面卸载会触发 onCompletion,
        // 我们借此中断服务端的生成线程。
        emitter.onCompletion(() -> {
            log.debug("SSE 连接完成 chatId={} messageId={}", chatId, persisted.assistantMessageId());
            cancel(taskRef, clientGone, chatId, persisted.assistantMessageId());
        });
        emitter.onTimeout(() -> {
            log.warn("SSE 连接超时 chatId={}", chatId);
            cancel(taskRef, clientGone, chatId, persisted.assistantMessageId());
        });
        emitter.onError(e -> {
            log.warn("SSE 连接异常 chatId={} err={}", chatId, e.toString());
            cancel(taskRef, clientGone, chatId, persisted.assistantMessageId());
        });
 
        // ---- 异步执行生成任务 ----
        // sseExecutor 声明为 ExecutorService,因此可以直接 submit 拿到 Future
        Future<?> task = sseExecutor.submit(
                () -> runGeneration(emitter, chat, meta, effectiveModel,
                        persisted, useRag, imageText, clientGone));
        taskRef.set(task);
 
        return emitter;
    }
 
    /**
     * 真正的生成流程,运行在 sseExecutor 线程上。
     *
     * <p>这里的每个 catch 分支都必须保证 emitter 被 complete 或 completeWithError,
     * 否则连接会一直挂在那里直到 Tomcat 回收。
     */
    private void runGeneration(SseEmitter emitter,
                               Chat chat,
                               ChatMetaRequest meta,
                               String model,
                               PersistResult persisted,
                               boolean useRag,
                               String imageText,
                               AtomicBoolean clientGone) {
        Long chatId = chat.getId();
        Long assistantMessageId = persisted.assistantMessageId();
 
        // 累积区:只在当前生成线程内访问,无需加锁
        StringBuilder buffer = new StringBuilder();
        AtomicReference<String> lastFlushed = new AtomicReference<>("");
        List<StreamEvent.Source> sources = new ArrayList<>();
 
        java.util.concurrent.ScheduledFuture<?> flushTask = null;
 
        try {
            // 1) start 事件:前端拿到 assistantMessageId,建立占位气泡
            send(emitter, "start", StreamEvent.start(
                    chatId, persisted.userMessageId(), assistantMessageId, model));
 
            // 2) 会话标题
            //
            // 放在最前面而不是等流结束:标题只依赖「首条用户提问」,
            // 与模型输出毫无关系。若等到生成结束再下发,遇到慢模型
            // (7B 量化模型在 CPU 上可能跑几十秒)侧边栏会长时间显示「新对话」,
            // 用户以为没生效。这里在首个 token 之前就定好,零等待。
            maybeGenerateTitle(chat, emitter);
 
            // 3) RAG 检索
            String ragContext = null;
            if (useRag && ragProperties.isEnabled()) {
                ragContext = retrieveContext(chatId, persisted.userMessageContent(), sources);
            }
 
            // 4) 组装完整 prompt 上下文(含图片 OCR 文字)
            List<LlmService.LlmMessage> context =
                    buildContext(chat, meta, persisted, ragContext, imageText);
 
            // 4) 启动定期落库定时器(进程被 kill 时最多丢 FLUSH_INTERVAL 的内容)
            flushTask = flusher.scheduleAtFixedRate(
                    () -> flushPartial(assistantMessageId, buffer, lastFlushed),
                    FLUSH_INTERVAL_MILLIS, FLUSH_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
 
            // 5) 调用 LLM 并逐块推送
            llmService.streamChat(context, new LlmService.LlmOptions(
                            model,
                            meta.getTemperature(),
                            meta.getTopP(),
                            meta.getNumCtx()),
                    (token, thinking) -> {
                        // thinking 内容不入库,仅实时推给前端展示
                        if (!thinking) {
                            buffer.append(token);
                        }
                        send(emitter, "delta", StreamEvent.delta(assistantMessageId, token, thinking));
                    });
 
            // 6) 流结束:写回完整内容,done=1
            String fullContent = buffer.toString();
            finishAssistantMessage(assistantMessageId, fullContent,
                    buildMetadata(model, sources, chatId));
            touchChat(chatId);
 
            send(emitter, "done", StreamEvent.done(assistantMessageId, fullContent, sources));
 
            emitter.complete();
 
        } catch (Exception e) {
            log.error("流式生成失败 chatId={} messageId={}", chatId, assistantMessageId, e);
 
            // 把已生成的部分内容落库并标记完成,避免留下永远 done=0 的消息
            String partial = buffer.toString();
            String errorMessage = friendlyError(e);
            finalizeOnFailure(assistantMessageId, partial, errorMessage);
 
            if (!clientGone.get()) {
                // 尽力而为地通知前端;此时连接可能已断,send 失败可忽略
                send(emitter, "error", StreamEvent.error(errorMessage));
                try {
                    emitter.complete();
                } catch (Exception ignore) {
                    // 连接已关闭,忽略
                }
            }
        } finally {
            if (flushTask != null) {
                flushTask.cancel(false);
            }
            if (clientGone.get()) {
                log.info("客户端提前断开 chatId={} messageId={} 已保存 {} 字",
                        chatId, assistantMessageId, buffer.length());
            }
        }
    }
 
    // ==================== 落库相关 ====================
 
    /**
     * 原子地保存 user 消息与 assistant 占位消息。
     *
     * <p><b>为什么必须在一个事务里</b>:这两条记录是强关联的。
     * 如果只写入 user 消息而 assistant 占位失败,前端会收到一个
     * 永远不会有回复的提问;反过来则会凭空出现一条空的 AI 气泡。
     * 用 {@link TransactionTemplate} 把两条 insert 圈在同一个事务里,
     * 任一失败则整体回滚。
     *
     * <p>assistant 占位消息的 {@code parentId} 指向 user 消息,
     * 这是消息树能够产生分支的基础:重新生成时会在同一个 user 消息下
     * 再插入一条 assistant 消息,两条互为兄弟节点。
     */
    private PersistResult persistUserAndPlaceholder(Long chatId, Long parentId,
                                                    String content, String model,
                                                    String imageText,
                                                    List<Long> imageFileIds) {
        return transactionTemplate.execute(status -> {
            Message userMessage = new Message();
            userMessage.setChatId(chatId);
            userMessage.setParentId(parentId);
            userMessage.setRole(Message.ROLE_USER);
            userMessage.setContent(content);
            userMessage.setDone(true); // 用户消息本身就是完整的
            // 把图片 id 与 OCR 文字一起记进 metadata。
            // 两者都要存:
            //   imageFileIds -> 刷新页面后仍能显示原图
            //   imageText    -> 「重新生成」时能复用图片上下文,
            //                   否则同一个问题重新生成会得到「不知道你在说什么」
            if ((imageFileIds != null && !imageFileIds.isEmpty())
                    || (imageText != null && !imageText.isBlank())) {
                try {
                    Map<String, Object> imgMeta = new java.util.LinkedHashMap<>();
                    if (imageFileIds != null && !imageFileIds.isEmpty()) {
                        imgMeta.put("imageFileIds", imageFileIds);
                    }
                    if (imageText != null && !imageText.isBlank()) {
                        // OCR 文本可能很长,按上下文上限截断,避免 metadata 无限膨胀
                        imgMeta.put("imageText", abbreviate(imageText, ragProperties.getMaxContextChars()));
                    }
                    userMessage.setMetadata(objectMapper.writeValueAsString(imgMeta));
                } catch (Exception e) {
                    log.warn("写入图片元数据失败: {}", e.getMessage());
                }
            }
            userMessage.setCreatedAt(LocalDateTime.now());
            messageMapper.insert(userMessage);
 
            Message assistant = new Message();
            assistant.setChatId(chatId);
            // assistant 挂在 user 消息下,这是消息树分枝的基础
            assistant.setParentId(userMessage.getId());
            assistant.setRole(Message.ROLE_ASSISTANT);
            assistant.setContent("");
            assistant.setModel(model);
            assistant.setDone(false); // 生成中
            assistant.setCreatedAt(LocalDateTime.now());
            messageMapper.insert(assistant);
 
            return new PersistResult(userMessage.getId(), content, assistant.getId());
        });
    }
 
    /** 定期把已生成的内容写回 DB */
    private void flushPartial(Long messageId, StringBuilder buffer, AtomicReference<String> lastFlushed) {
        // StringBuilder 非线程安全:这里用 toString 快照,且容忍瞬时不一致
        String snapshot;
        try {
            snapshot = buffer.toString();
        } catch (Exception e) {
            return;
        }
        if (snapshot.isEmpty() || snapshot.equals(lastFlushed.get())) {
            return;
        }
        try {
            Message patch = new Message();
            patch.setId(messageId);
            patch.setContent(snapshot);
            messageMapper.updateById(patch);
            lastFlushed.set(snapshot);
        } catch (Exception e) {
            // 定时落库失败不应影响主流程,丢弃本次快照即可
            log.warn("增量落库失败 messageId={} err={}", messageId, e.getMessage());
        }
    }
 
    /**
     * 流正常结束:写完整内容并置 done=1。
     *
     * <p>不加 {@code @Transactional}:这是单条 update,本身即原子操作;
     * 而且它由生成线程调用,包事务只会白白多占一个数据库连接。
     */
    private void finishAssistantMessage(Long messageId, String content, String metadata) {
        Message patch = new Message();
        patch.setId(messageId);
        patch.setContent(content);
        patch.setDone(true);
        patch.setMetadata(metadata);
        messageMapper.updateById(patch);
    }
 
    /** 流异常结束:保留已生成内容,标记 done=1 并记录错误原因 */
    private void finalizeOnFailure(Long messageId, String partial, String errorMessage) {
        try {
            Message patch = new Message();
            patch.setId(messageId);
            // 部分内容也保留:用户能看到模型说到一半的内容,比空白更有信息量
            patch.setContent(partial.isEmpty() ? "(生成失败:" + errorMessage + ")" : partial);
            patch.setDone(true);
            patch.setMetadata(objectMapper.writeValueAsString(Map.of("error", errorMessage)));
            messageMapper.updateById(patch);
        } catch (Exception e) {
            log.error("标记失败消息状态时出错 messageId={}", messageId, e);
        }
    }
 
    private void touchChat(Long chatId) {
        try {
            Chat patch = new Chat();
            patch.setId(chatId);
            patch.setUpdatedAt(LocalDateTime.now());
            chatMapper.updateById(patch);
        } catch (Exception e) {
            log.warn("更新会话活跃时间失败 chatId={}", chatId);
        }
    }
 
    // ==================== 上下文组装 ====================
 
    /**
     * 构造发给 LLM 的完整上下文。
     *
     * <p>顺序:system prompt(含 RAG 片段)→ 历史对话(当前分支的祖先链)→ 本轮用户输入。
     *
     * <p>历史只取<b>当前分支</b>的祖先链,这是消息树设计的直接收益:
     * 用户在不同分支上切换时,模型看到的上下文会随之变化,
     * 不会把其他分支的内容误当作本次对话的历史。
     */
    private List<LlmService.LlmMessage> buildContext(Chat chat,
                                                     ChatMetaRequest meta,
                                                     PersistResult persisted,
                                                     String ragContext,
                                                     String imageText) {
        List<LlmService.LlmMessage> context = new ArrayList<>();
 
        // ---- system prompt ----
        StringBuilder systemPrompt = new StringBuilder();
        if (meta.getSystemPrompt() != null && !meta.getSystemPrompt().isBlank()) {
            systemPrompt.append(meta.getSystemPrompt().trim());
        }
        if (ragContext != null && !ragContext.isBlank()) {
            if (!systemPrompt.isEmpty()) {
                systemPrompt.append("\n\n");
            }
            systemPrompt.append("""
                    以下是从用户知识库中检索到的参考资料,每条前面有 [编号] 与来源信息。
                    请遵守以下规则:
                    1. 优先依据这些资料回答;如果资料中没有相关信息,
                       请明确说明「知识库中未找到相关内容」,不要编造。
                    2. 在引用了某条资料的句子末尾标注对应编号,格式为 [1]、[2],
                       可同时标注多个,如 [1][3]。编号必须与资料的编号一致。
                    3. 只标注真正用到的资料,不要为了凑数引用无关资料。
                    4. 不要复述资料的文件名与章节名,来源会由界面单独展示。
 
                    """).append(ragContext);
        }
        // ---- 随消息上传的图片内容(OCR 结果)----
        // 作为 system 消息注入而不是拼进用户输入:
        // 这样用户看到的自己那条消息仍是原本的文字,不会被一堆 OCR 文本淹没。
        if (imageText != null && !imageText.isBlank()) {
            if (!systemPrompt.isEmpty()) {
                systemPrompt.append("\n\n");
            }
            systemPrompt.append("""
                    用户随消息上传了图片,以下是图片中的文字内容(由 OCR 识别,可能有识别误差):
                    ---
                    """).append(abbreviate(imageText, llmProperties.getPerPartCharLimit()))
                    .append("""
                    ---
                    请结合这些图片内容回答用户的问题。如果用户的问题与图片内容相关,
                    请直接依据图片中的信息作答;若图片内容与问题无关,不必强行提及。
                    """);
        }
 
        if (!systemPrompt.isEmpty()) {
            context.add(new LlmService.LlmMessage(Message.ROLE_SYSTEM, systemPrompt.toString()));
        }
 
        // ---- 历史对话:沿 parentId 回溯当前分支 ----
        List<Message> history = loadBranchHistory(chat.getId(), persisted.assistantMessageId());
        // assistant 占位消息内容为空,过滤掉
        List<LlmService.LlmMessage> historyMessages = history.stream()
                .filter(m -> m.getContent() != null && !m.getContent().isBlank())
                .filter(m -> Message.ROLE_USER.equals(m.getRole())
                        || Message.ROLE_ASSISTANT.equals(m.getRole()))
                .map(m -> new LlmService.LlmMessage(m.getRole(), m.getContent()))
                .toList();
 
        // ---- 按字符预算装配历史 ----
        //
        // 关键点:**从最近的消息往回装**,装到预算用完为止。
        // 之前的实现是「取最近 20 条后全部塞进去」,只受条数限制、
        // 不受 token 限制 —— 20 条长回答轻易就能到上万字符,
        // 加上图片 OCR 文字直接超过 num_ctx,Ollama 便从头静默截断,
        // 把最前面的 system 消息(图片内容、知识库资料)整段丢掉,
        // 于是「模型好像没看到图片」。这是本项目最难查的一类 bug:
        // 不报错、不报警,只是模型装作没看见。
        int budget = Math.max(500, llmProperties.getContextCharBudget());
        int systemCost = systemPrompt.length();
        int remaining = budget - systemCost;
 
        if (remaining <= 0) {
            // system 部分已占满预算(例如超长 OCR 文字),
            // 此时优先保住 system —— 它承载本轮的新信息(图片/资料),
            // 比历史对话重要得多。历史整体放弃,并留下明确日志。
            log.warn("system 内容已占满上下文预算 chatId={} systemChars={} budget={},"
                            + "本轮不携带历史对话。可调大 webui.llm.context-char-budget 或 num-ctx",
                    chat.getId(), systemCost, budget);
        } else {
            int limit = Math.max(1, llmProperties.getHistoryLimit());
            int from = Math.max(0, historyMessages.size() - limit);
 
            // 从最近一条往前累加,超出预算就停
            java.util.LinkedList<LlmService.LlmMessage> picked = new java.util.LinkedList<>();
            int used = 0;
            for (int i = historyMessages.size() - 1; i >= from; i--) {
                LlmService.LlmMessage msg = historyMessages.get(i);
                int cost = msg.content() == null ? 0 : msg.content().length();
                if (used + cost > remaining) {
                    break;
                }
                picked.addFirst(msg);
                used += cost;
            }
 
            context.addAll(picked);
 
            int skipped = (historyMessages.size() - from) - picked.size();
            if (skipped > 0) {
                log.info("历史对话按字符预算裁剪 chatId={} 保留={} 条 丢弃={} 条 "
                                + "(budget={} system={} 已用={})",
                        chat.getId(), picked.size(), skipped, budget, systemCost, used);
            } else {
                log.debug("上下文组装完成 chatId={} system={}字 历史={}条 合计={}字(预算{})",
                        chat.getId(), systemCost, picked.size(), systemCost + used, budget);
            }
        }
 
        // 最终兜底:万一还是超(例如单条用户消息本身就极长),
        // 打印一条可定位的告警,避免又变成「静默失效」
        int totalChars = systemCost + context.stream()
                .filter(m -> !Message.ROLE_SYSTEM.equals(m.role()))
                .mapToInt(m -> m.content() == null ? 0 : m.content().length())
                .sum();
        if (totalChars > budget) {
            log.warn("上下文仍超出预算 chatId={} 合计={} 字 > 预算={} 字,"
                            + "Ollama 可能从开头截断(system 在最前,风险最高)。"
                            + "请调大 webui.llm.context-char-budget 或 Ollama 的 num_ctx",
                    chat.getId(), totalChars, budget);
        }
 
        return context;
    }
 
    /**
     * 加载从会话根到指定消息的完整链路。
     *
     * <p>实现上用一次全量查询 + 内存回溯,而不是递归 SQL:
     * 单会话消息量通常在数百条量级,一次查询的开销远低于多次 round-trip,
     * 且逻辑更直观、易测试。消息量真的变大时再切换到递归 CTE 或路径枚举。
     */
    private List<Message> loadBranchHistory(Long chatId, Long leafMessageId) {
        List<Message> all = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getChatId, chatId)
                        .orderByAsc(Message::getCreatedAt)
                        .orderByAsc(Message::getId));
 
        Map<Long, Message> byId = new HashMap<>(all.size() * 2);
        for (Message m : all) {
            byId.put(m.getId(), m);
        }
        return MessageTreeUtil.pathToRoot(byId, leafMessageId);
    }
 
    /**
     * RAG 检索并填充 sources。
     *
     * <p>全程容错:知识库检索失败绝不能让对话失败,最差情况退化成纯聊天。
     */
    private String retrieveContext(Long chatId, String query, List<StreamEvent.Source> sources) {
        try {
            List<String> collections = new ArrayList<>(chatCollectionMapper.selectList(
                            Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                    .stream().map(ChatCollection::getCollectionName).toList());
 
            // 整类绑定:把该会话绑定的分类展开成集合。
            // 在这里展开(而不是绑定时写死集合名)的关键收益是 ——
            // 之后往分类里新增的文档,已有会话能自动检索到。
            List<Long> boundCategoryIds = chatCategoryMapper.selectList(
                            Wrappers.<ChatCategory>lambdaQuery().eq(ChatCategory::getChatId, chatId))
                    .stream().map(ChatCategory::getCategoryId).toList();
            if (!boundCategoryIds.isEmpty()) {
                List<Long> fileIds = uploadFileMapper.selectList(
                                Wrappers.<UploadFile>lambdaQuery()
                                        .select(UploadFile::getId)
                                        .in(UploadFile::getCategoryId, boundCategoryIds))
                        .stream().map(UploadFile::getId).toList();
                if (!fileIds.isEmpty()) {
                    for (RagCollection rc : ragCollectionMapper.selectList(
                            Wrappers.<RagCollection>lambdaQuery()
                                    .in(RagCollection::getFileId, fileIds)
                                    .eq(RagCollection::getStatus, RagCollection.STATUS_READY))) {
                        if (!collections.contains(rc.getCollectionName())) {
                            collections.add(rc.getCollectionName());
                        }
                    }
                }
                log.debug("会话 {} 绑定 {} 个分类,展开后共 {} 个集合",
                        chatId, boundCategoryIds.size(), collections.size());
            }
 
            if (collections.isEmpty()) {
                log.debug("会话 {} 未绑定知识库,跳过 RAG 检索", chatId);
                return null;
            }
 
            List<RagChunk> chunks = ragProxyService.search(
                    query, collections, ragProperties.getDefaultTopK());
            if (chunks.isEmpty()) {
                return null;
            }
 
            // 向量库里记录的 filename 是磁盘存储名(UUID.ext),
            // 直接展示会给用户看一串无意义的哈希。这里用集合名反查
            // upload_file 表,换成用户上传时的原始文件名。
            Map<String, String> displayNames = resolveDisplayNames(collections);
 
            for (RagChunk c : chunks) {
                StreamEvent.Source s = new StreamEvent.Source();
                String displayName = displayNames.get(c.getCollectionName());
                s.setFilename(displayName != null ? displayName : c.getFilename());
                // 章节:让引用从「文件名」细化到「文档的哪一节」
                s.setSection(c.getSection());
                s.setScore(c.getScore());
                s.setSnippet(abbreviate(c.getText(), 120));
                s.setChunkIndex(c.getChunkIndex());
                s.setCollectionName(c.getCollectionName());
                sources.add(s);
            }
 
            return ragProxyService.buildRagContext(chunks);
        } catch (Exception e) {
            log.warn("RAG 检索失败,降级为纯对话 chatId={} err={}", chatId, e.getMessage());
            return null;
        }
    }
 
    /**
     * 用会话的<strong>第一条用户提问</strong>作为标题。
     *
     * <p>触发条件:会话标题仍是默认值「新对话」。已有标题(用户手动改过、
     * 或已设置过)则不再覆盖,避免把用户取的名字冲掉。
     *
     * <p><b>为什么不再调用 LLM 做摘要?</b>
     * 早先的实现是把首条提问丢给模型「概括成 15 字标题」,实践下来问题很多:
     * <ul>
     *   <li>小模型经常不听话 —— 实测问「你是谁」,qwen2.5:7b 返回的标题是
     *       「身份未知」,与提问毫无关系,比原文还差</li>
     *   <li>多一次 LLM 往返,首轮对话结束时间被拖长</li>
     *   <li>需要额外的超时、降级、引号清洗逻辑,维护成本高</li>
     * </ul>
     * 直接截取首条提问既符合用户预期(「标题就是我说的第一句话」),
     * 又是零延迟、确定性的行为。因此这里刻意不做任何模型调用。
     */
    private void maybeGenerateTitle(Chat chat, SseEmitter emitter) {
        try {
            if (chat.getTitle() != null && !DEFAULT_CHAT_TITLE.equals(chat.getTitle())) {
                return;
            }
 
            // 取该会话第一条 user 消息 —— 会话标题就来自它
            List<Message> firstUserMessages = messageMapper.selectList(
                    Wrappers.<Message>lambdaQuery()
                            .eq(Message::getChatId, chat.getId())
                            .eq(Message::getRole, Message.ROLE_USER)
                            .orderByAsc(Message::getId)
                            .last("LIMIT 1"));
            if (firstUserMessages.isEmpty()) {
                return;
            }
 
            String title = buildTitleFromQuestion(firstUserMessages.get(0).getContent());
            if (title.isEmpty()) {
                return;
            }
 
            chatService.updateTitle(chat.getId(), title);
            send(emitter, "title", StreamEvent.title(chat.getId(), title));
            log.info("已用首条提问设置会话标题 chatId={} title={}", chat.getId(), title);
 
        } catch (Exception e) {
            // 取标题失败不该影响对话,记一笔即可
            log.warn("设置会话标题失败 chatId={} err={}", chat.getId(), e.getMessage());
        }
    }
 
    /**
     * 把用户提问规整成适合做侧边栏标题的短文本。
     *
     * <p>处理内容:
     * <ol>
     *   <li>把连续空白(含换行)压成单个空格 —— 多行提问在侧边栏里
     *       只能单行显示,留换行会导致高度异常</li>
     *   <li>去掉首尾空白与成对引号</li>
     *   <li>超过 {@link #MAX_TITLE_LENGTH} 个字符则截断并加省略号</li>
     * </ol>
     *
     * <p>注意用 {@code codePointCount} 而非 {@code length()}:Java 的
     * {@code String.length()} 数的是 UTF-16 码元,emoji 等增补字符占两个码元,
     * 直接按 length 截断可能把一个 emoji 劈成两半,产生乱码。
     */
    private String buildTitleFromQuestion(String question) {
        if (question == null || question.isBlank()) {
            return "";
        }
 
        String title = question.replaceAll("\\s+", " ").trim();
        // 去掉模型/用户可能带上的成对引号
        title = title.replaceAll("^[\"'“”‘’]+|[\"'“”‘’]+$", "").trim();
        if (title.isEmpty()) {
            return "";
        }
 
        if (title.codePointCount(0, title.length()) > MAX_TITLE_LENGTH) {
            int endIndex = title.offsetByCodePoints(0, MAX_TITLE_LENGTH);
            title = title.substring(0, endIndex) + "…";
        }
 
        // 兜底:数据库列宽 255,极端情况下再截一层,避免插入报错
        return title.length() > 255 ? title.substring(0, 255) : title;
    }
 
    /**
     * 把「向量集合名」映射到「用户上传时的原始文件名」。
     *
     * <p>为什么需要这一步:Python 侧写入向量元数据的 filename 是磁盘存储名
     * (形如 {@code 496ae5fa...md},由服务端生成以防路径穿越),
     * 它对用户毫无意义。集合名是确定性的 {@code user_{uid}_file_{fid}},
     * 通过 {@code rag_collection -> upload_file} 两跳就能换回可读的名字。
     *
     * <p>查不到时返回空映射,调用方回退到原始 filename —— 宁可显示哈希,
     * 也不能因为查库失败而丢掉整条引用信息。
     */
    private Map<String, String> resolveDisplayNames(List<String> collectionNames) {
        if (collectionNames == null || collectionNames.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            List<RagCollection> records = ragCollectionMapper.selectList(
                    Wrappers.<RagCollection>lambdaQuery()
                            .in(RagCollection::getCollectionName, collectionNames));
            if (records.isEmpty()) {
                return Collections.emptyMap();
            }
 
            List<Long> fileIds = records.stream()
                    .map(RagCollection::getFileId)
                    .filter(Objects::nonNull)
                    .toList();
            if (fileIds.isEmpty()) {
                return Collections.emptyMap();
            }
 
            Map<Long, String> filenameById = new HashMap<>();
            for (UploadFile file : uploadFileMapper.selectBatchIds(fileIds)) {
                filenameById.put(file.getId(), file.getFilename());
            }
 
            Map<String, String> result = new HashMap<>();
            for (RagCollection record : records) {
                String filename = filenameById.get(record.getFileId());
                if (filename != null) {
                    result.put(record.getCollectionName(), filename);
                }
            }
            return result;
        } catch (Exception e) {
            log.warn("解析文件显示名失败,引用将回退为存储名: {}", e.getMessage());
            return Collections.emptyMap();
        }
    }
 
    private String buildMetadata(String model, List<StreamEvent.Source> sources, Long chatId) {
        try {
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("model", model);
            metadata.put("finishedAt", LocalDateTime.now().toString());
            if (!sources.isEmpty()) {
                metadata.put("ragSourceCount", sources.size());
                metadata.put("ragSources", sources);
            }
            return objectMapper.writeValueAsString(metadata);
        } catch (Exception e) {
            return null;
        }
    }
 
    // ==================== SSE 发送与资源回收 ====================
 
    /**
     * 发送一个 SSE 事件。
     *
     * <p>客户端断开时 send 会抛 IOException。这里刻意<b>不</b>把它当成致命错误
     * 向上抛:让生成循环继续跑完并把内容落库,
     * 用户刷新页面后仍能看到完整回复,体验优于直接丢弃。
     */
    private void send(SseEmitter emitter, String eventName, Object payload) {
        try {
            emitter.send(SseEmitter.event()
                    .name(eventName)
                    .data(payload, org.springframework.http.MediaType.APPLICATION_JSON));
        } catch (IOException | IllegalStateException e) {
            // IllegalStateException:emitter 已 complete 后再 send
            log.debug("SSE 发送失败(客户端可能已断开)event={} err={}", eventName, e.getMessage());
        }
    }
 
    /** 取消生成任务并标记客户端已离开 */
    private void cancel(AtomicReference<Future<?>> taskRef, AtomicBoolean clientGone,
                        Long chatId, Long messageId) {
        clientGone.set(true);
        Future<?> task = taskRef.get();
        if (task != null && !task.isDone()) {
            // interrupt 会传到 MockLlmService 的 sleep 与 Ollama 的 socket 读取,
            // 从而尽快结束线程,避免线程池被废弃连接占满
            boolean cancelled = task.cancel(true);
            log.info("中断流式任务 chatId={} messageId={} cancelled={}", chatId, messageId, cancelled);
        }
    }
 
    /** 把内部异常翻译成用户能看懂、且能指导下一步操作的提示 */
    private String friendlyError(Exception e) {
        if (e instanceof BusinessException be) {
            return be.getMessage();
        }
        String msg = e.getMessage();
        if (msg != null && msg.contains("Connection refused")) {
            return "无法连接 LLM 服务,请确认 Ollama 已启动(OLLAMA_HOST=0.0.0.0 ollama serve)";
        }
        return "生成回复时发生错误: " + (msg == null ? e.getClass().getSimpleName() : msg);
    }
 
    private String abbreviate(String s, int max) {
        if (s == null) {
            return "";
        }
        String normalized = s.replaceAll("\\s+", " ").trim();
        return normalized.length() <= max ? normalized : normalized.substring(0, max) + "...";
    }
 
    /**
     * 持久化结果。用 record 承载,避免在多个方法间传递一长串参数。
     *
     * @param userMessageId      user 消息 id
     * @param userMessageContent user 消息内容(RAG 检索的 query)
     * @param assistantMessageId assistant 占位消息 id
     */
    private record PersistResult(Long userMessageId, String userMessageContent, Long assistantMessageId) {
    }
}