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
package com.custom.webui.util;
 
import com.custom.webui.dto.resp.MessageDTO;
import com.custom.webui.dto.resp.StreamEvent;
import com.custom.webui.entity.Message;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
 
/**
 * 消息树组装工具。
 *
 * <p><b>这是整个系统的核心逻辑之一。</b>
 * 数据库中的 message 表是<strong>完全扁平</strong>的,没有任何树形 JSON;
 * 这里把扁平列表在内存中还原成树,并顺带算出前端做分支切换所需的全部信息。
 *
 * <p>算法(单遍 O(n)):
 * <ol>
 *   <li>按 parentId 把所有消息分桶(LinkedHashMap 保证同层内按创建时间有序)</li>
 *   <li>从 parentId == null 的根节点出发递归挂载 children</li>
 *   <li>每层为兄弟节点写入 siblingCount / siblingIndex / siblingIds</li>
 * </ol>
 *
 * <p>容错处理:
 * <ul>
 *   <li><b>孤儿节点</b>:parentId 指向一条已被删除或不存在的消息时,
 *       该节点会被当作根节点上浮,保证消息不会凭空消失</li>
 *   <li><b>成环</b>:visited 集合防止脏数据导致的无限递归</li>
 * </ul>
 */
public final class MessageTreeUtil {
 
    /**
     * 仅用于解析消息 metadata 的轻量 ObjectMapper。
     *
     * <p>静态持有是刻意的:本类是纯工具类,方法都是 static,无法注入 Spring 的
     * ObjectMapper。ObjectMapper 本身线程安全(配置完成后),因此静态实例没问题。
     */
    private static final ObjectMapper MAPPER = new ObjectMapper()
            .configure(com.fasterxml.jackson.databind.DeserializationFeature
                    .FAIL_ON_UNKNOWN_PROPERTIES, false);
 
    private MessageTreeUtil() {
    }
 
    /**
     * 把扁平消息列表组装成消息树。
     *
     * @param flatMessages 同一会话的所有消息,顺序不限
     * @return 根节点列表(通常只有一个根:会话的第一条 user 消息)
     */
    public static List<MessageDTO> buildTree(List<Message> flatMessages) {
        if (flatMessages == null || flatMessages.isEmpty()) {
            return new ArrayList<>();
        }
 
        // 1. 全部实体转 DTO,并建立 id -> DTO 的索引
        Map<Long, MessageDTO> dtoById = new HashMap<>(flatMessages.size() * 2);
        for (Message m : flatMessages) {
            if (m == null || m.getId() == null) {
                continue;
            }
            dtoById.put(m.getId(), toDto(m));
        }
 
        // 2. 按 parentId 分桶;parentId 为 null 的进 roots 桶
        Map<Long, List<MessageDTO>> childrenByParent = new LinkedHashMap<>();
        List<MessageDTO> roots = new ArrayList<>();
        for (MessageDTO dto : dtoById.values()) {
            Long parentId = dto.getParentId();
            // 孤儿节点:父消息不在本次结果集内,上浮为根,避免消息丢失
            if (parentId == null || !dtoById.containsKey(parentId)) {
                roots.add(dto);
            } else {
                childrenByParent.computeIfAbsent(parentId, k -> new ArrayList<>()).add(dto);
            }
        }
 
        // 3. 同层排序:按创建时间升序,时间相同用 id 兜底,保证顺序稳定可复现
        Comparator<MessageDTO> siblingOrder = Comparator
                .comparing(MessageDTO::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder()))
                .thenComparing(MessageDTO::getId, Comparator.nullsLast(Comparator.naturalOrder()));
        roots.sort(siblingOrder);
        childrenByParent.values().forEach(list -> list.sort(siblingOrder));
 
        // 4. 递归挂载子节点,同时写入兄弟序号等分支元数据
        List<MessageDTO> visited = new ArrayList<>();
        for (MessageDTO root : roots) {
            attach(root, childrenByParent, visited);
        }
 
        // 5. 为根层也补齐兄弟信息(正常情况下只有 1 个根)
        applySiblingInfo(roots);
 
        return roots;
    }
 
    /**
     * 递归挂载:把 node 的子节点接上,并设置 node.activeChildId。
     *
     * @param path 当前递归路径,用于检测脏数据造成的环
     */
    private static void attach(MessageDTO node,
                               Map<Long, List<MessageDTO>> childrenByParent,
                               List<MessageDTO> path) {
        // 成环保护:同一节点在同一条递归路径上出现第二次说明数据有环
        if (path.contains(node)) {
            return;
        }
        path.add(node);
 
        List<MessageDTO> children = childrenByParent.get(node.getId());
        if (children != null && !children.isEmpty()) {
            applySiblingInfo(children);
            for (MessageDTO child : children) {
                node.addChild(child);
                attach(child, childrenByParent, path);
            }
            // activeChildId 默认取最后一条子消息:
            // 重新生成场景下最后生成的 assistant 回复就是用户当前正在看的分支
            node.setActiveChildId(children.get(children.size() - 1).getId());
        }
 
        path.remove(path.size() - 1);
    }
 
    /** 为一组兄弟节点写入 siblingCount / siblingIndex / siblingIds。 */
    private static void applySiblingInfo(List<MessageDTO> siblings) {
        if (siblings == null || siblings.isEmpty()) {
            return;
        }
        List<Long> ids = new ArrayList<>(siblings.size());
        for (MessageDTO s : siblings) {
            ids.add(s.getId());
        }
        int total = siblings.size();
        for (int i = 0; i < total; i++) {
            MessageDTO s = siblings.get(i);
            s.setSiblingIds(ids);
            s.setSiblingCount(total);
            s.setSiblingIndex(i + 1);
        }
    }
 
    /**
     * 实体转 DTO。{@code done} 在库里是 tinyint,可能为 null,
     * 这里统一兜底为 true,避免历史脏数据被前端误判为「生成中」。
     */
    public static MessageDTO toDto(Message m) {
        MessageDTO dto = new MessageDTO();
        dto.setId(m.getId());
        dto.setChatId(m.getChatId());
        dto.setParentId(m.getParentId());
        dto.setRole(m.getRole());
        dto.setContent(m.getContent() == null ? "" : m.getContent());
        dto.setModel(m.getModel());
        dto.setDone(m.getDone() == null || Boolean.TRUE.equals(m.getDone()));
        dto.setMetadata(m.getMetadata());
        dto.setCreatedAt(m.getCreatedAt());
        // 从 metadata 里还原 RAG 引用来源。
        // 生成时来源是随 done 事件发给前端的,但那条 SSE 连接早已结束;
        // 不在这里还原的话,刷新页面后「这条回答引用了哪些文档」就丢了。
        dto.setSources(extractSources(m.getMetadata()));
        dto.setImageFileIds(extractImageFileIds(m.getMetadata()));
        dto.setImageText(extractImageText(m.getMetadata()));
        return dto;
    }
 
    /**
     * 从消息 metadata JSON 中提取 RAG 引用来源。
     *
     * <p>metadata 形如:
     * <pre>
     * {"model":"qwen2.5:7b","finishedAt":"...",
     *  "ragSources":[{"filename":"a.pdf","section":"2.1 消息树","score":0.24}]}
     * </pre>
     *
     * <p>容错:metadata 为 null、不是合法 JSON、没有 ragSources、或元素解析失败时,
     * 一律返回空列表 —— 历史消息本就没有引用信息,不该因此导致接口 500。
     */
    private static List<StreamEvent.Source> extractSources(String metadataJson) {
        if (metadataJson == null || metadataJson.isBlank()) {
            return new ArrayList<>();
        }
        try {
            JsonNode root = MAPPER.readTree(metadataJson);
            JsonNode arr = root.get("ragSources");
            if (arr == null || !arr.isArray()) {
                return new ArrayList<>();
            }
            List<StreamEvent.Source> sources = new ArrayList<>(arr.size());
            for (JsonNode node : arr) {
                StreamEvent.Source source = new StreamEvent.Source();
                source.setFilename(textOrNull(node, "filename"));
                source.setSection(textOrNull(node, "section"));
                source.setSnippet(textOrNull(node, "snippet"));
                source.setCollectionName(textOrNull(node, "collectionName"));
                if (node.hasNonNull("score")) {
                    source.setScore(node.get("score").asDouble());
                }
                if (node.hasNonNull("chunkIndex")) {
                    source.setChunkIndex(node.get("chunkIndex").asInt());
                }
                sources.add(source);
            }
            return sources;
        } catch (Exception e) {
            // 不打印堆栈级别,脏 metadata 不值得刷满日志
            return new ArrayList<>();
        }
    }
 
    /**
     * 从 metadata 中还原随消息上传的图片 id 列表。
     *
     * <p>与 {@link #extractSources} 同样的容错策略:任何异常都返回空列表,
     * 历史消息本就没有图片,不该因此让接口失败。
     */
    private static List<Long> extractImageFileIds(String metadataJson) {
        List<Long> ids = new ArrayList<>();
        if (metadataJson == null || metadataJson.isBlank()) {
            return ids;
        }
        try {
            JsonNode arr = MAPPER.readTree(metadataJson).get("imageFileIds");
            if (arr == null || !arr.isArray()) {
                return ids;
            }
            for (JsonNode node : arr) {
                if (node.isNumber()) {
                    ids.add(node.asLong());
                }
            }
        } catch (Exception e) {
            // 脏 metadata 不值得刷日志
        }
        return ids;
    }
 
    /** 还原随消息上传图片的 OCR 文字;没有则返回 null */
    private static String extractImageText(String metadataJson) {
        if (metadataJson == null || metadataJson.isBlank()) {
            return null;
        }
        try {
            JsonNode node = MAPPER.readTree(metadataJson).get("imageText");
            return node == null || node.isNull() ? null : node.asText();
        } catch (Exception e) {
            return null;
        }
    }
 
    private static String textOrNull(JsonNode node, String field) {
        JsonNode value = node.get(field);
        return value == null || value.isNull() ? null : value.asText();
    }
 
    /**
     * 沿着 parentId 向上回溯,返回从根到指定消息的链路(含自身),按时间正序。
     *
     * <p>用途:构造 LLM 上下文。发送新消息时需要把「当前分支」的历史带进 prompt,
     * 而当前分支就是新消息 parentId 的祖先链。
     * 若某个父节点已被删除形成断链,回溯会提前停止并返回已收集的部分,
     * 保证请求不会因为脏数据而失败。
     */
    public static List<Message> pathToRoot(Map<Long, Message> byId, Long leafId) {
        List<Message> chain = new ArrayList<>();
        Long cursor = leafId;
        int guard = 0;
        int limit = byId.size() + 1;
        while (cursor != null && guard++ <= limit) {
            Message node = byId.get(cursor);
            if (node == null) {
                break;
            }
            chain.add(node);
            cursor = node.getParentId();
        }
        // 回溯得到的是 leaf -> root,反转成 root -> leaf
        java.util.Collections.reverse(chain);
        return chain;
    }
 
    /** 判断一条消息是否属于指定的聊天,用于越权访问校验。 */
    public static boolean belongsToChat(Message m, Long chatId) {
        return m != null && Objects.equals(m.getChatId(), chatId);
    }
}